# Box Developer Documentation > Complete documentation for Box Platform APIs, SDKs, and developer tools. Box Platform enables developers to integrate secure content management, collaboration, and AI capabilities into their applications. This comprehensive documentation covers all aspects of Box Platform development including APIs, SDKs, developer guides, and AI integrations. --- # Documentation Overview Box Platform provides a complete set of APIs and tools for building content-centric applications: ## Core Platform - **Box API**: RESTful APIs for file operations, metadata, collaboration, and administration - **Box UI Elements**: Pre-built UI components for file management and collaboration - **Authentication**: OAuth 2.0, JWT, and App Token authentication methods - **Webhooks**: Real-time notifications for content and user events ## AI & Intelligence - **Box AI APIs**: Document intelligence, content extraction, and AI-powered insights - **Text Generation**: AI-powered content creation and summarization - **Document Processing**: Automated document analysis and data extraction ## Developer Tools - **SDKs**: Official SDKs for Node.js, Python, Java, .NET, iOS, and Android - **CLI Tools**: Command-line interfaces for development and administration - **Sample Code**: Ready-to-use code examples and templates --- # Box Platform This section contains 15 documentation items covering page. ## Untitled *Type: page | Category: Learn Box Platform * Authentication Methods Box offers a variety of authentication methods for application development, each tailored to different use cases and… # Authentication Methods Box offers a variety of authentication methods for application development, each tailored to different use cases and application types. Regardless of the authentication method used, underlying principles still apply. If a user does not have access to content on the front end of the main Box web app, they will not be able to access the content using the API, unless they are impersonating another user. Some API endpoints require admin level privileges - like events. The following authorization methods are available to each Box application type. | Box Application Type | Supports OAuth 2.0? | JWT? | Client Credentials? | App Token? | | --- | --- | --- | --- | --- | | Platform App | Yes | Yes | Yes | No | | Limited Access App | No | Yes | No | Yes | | Custom Skill | No | No | No | No | ## OAuth 2.0 [OAuth 2.0](g://authentication/oauth2) is a client-side authentication method, widely used for its simplicity in authorizing users to Box API. It's an open standard that allows users to grant applications access to their data in other applications. Similar to how logging in to a website with Twitter, Facebook, or Google works, Box's client-side authentication involves redirecting a user from an app to the Box web app, where they log in and grant the app access to their data. For example, We use this auth type for users logging into our community forum. # When to use OAuth 2.0? Client-side authentication is the ideal authentication method for apps that: - Work with users who have existing Box accounts - Use Box for identity management, so users know they are using Box - Store data within each user account vs within an application's Service Account You can find a great Python OAuth 2.0 tutorial on [GitHub](https://github.com/box-community/box-python-oauth-template). ## JSON Web Token (JWT) JSON Web Tokens (JWT) is the most common server-side authentication method for the Box API. [JWT](g://authentication/jwt), an open standard, enables robust server-to-server authentication. This method, exclusive to Platform Apps, does not involve end-user interaction. It allows an app, if granted appropriate privileges, to act on behalf of any user in an enterprise, thus facilitating powerful and seamless integrations. Upon approval by an administrator, a JWT application will get assigned a service account to make API calls as by default. # When to use JWT? Server-side authentication with JWT is the ideal authentication method for apps that: - Work with users without Box accounts - Use their own identity system - Do not want users to know they are using Box - Store data within the application's Service Account and not a user's account - Want to manage public and private key pairs You can find a great Node JWT tutorial on [Medium](https://medium.com/box-developer-blog/authenticate-box-node-js-sdk-with-jwt-47fdd3aeec50). ## Client Credentials Grant (CCG) The [Client Credentials Grant](g://authentication/client-credentials) approach is used for server authentication, verifying an application's identity using a client ID and secret. It's a secure way of identifying an app when obtaining an Access Token. This method is particularly useful for scenarios requiring server-to-server interactions without user involvement. Depending on the application's configuration, it can authenticate as either the application's Service Account or as a Managed User. Upon approval by an administrator, a CCG application will get assigned a service account to make API calls as by default. # When to use CCG? Server-side authentication with JWT is the ideal authentication method for apps that: - Work with users without Box accounts - Use their own identity system - Do not want users to know they are using Box - Store data within the application's Service Account and not a user's account - Do not want to manage public and private key pairs You can find a great Python CCG tutorial on [Medium](https://medium.com/box-developer-blog/box-python-next-gen-sdk-getting-started-with-ccg-81be0abc82d9). ## App Token Auth [App Token Auth](g://authentication/app-token)is another server-side authentication option, utilizing fixed, long-lived Access Tokens that are restricted to the application's Service Account. This method is ideal for applications leveraging Box View and is designed for scenarios where the app only needs access to read and write data to its own account. By using App Token Auth, there's no need for end-user authorization, as the application automatically authenticates as the Service Account associated with it. It also is restricted to a subset of API [endpoints](g://authentication/app-token/endpoints). # When to use App Token Auth? Server-side authentication with App Tokens is the ideal authentication method for apps that: - Work in an environment that either has no user model, or has users without Box accounts - Use their own identity management system - Do not want users to know they are using Box - Store data within the application's Service Account and not a user's account ## Box Skills [Box Skills](g://skills/handle/payload/#access-tokens) are a unique application type used for custom processing of files uploaded to Box. It uses third-party Machine Learning services to extract information from files and apply it as metadata. Authentication for Custom Skills is streamlined with pre-authorized API credentials provided with each Skill Event, though this limits the API access. Custom Skills don't require a specific authentication type selection, focusing on simplicity and direct integration with Box's capabilities. # When to use Box Skills? Webhook based authentication with Box Skills is the ideal authentication method for apps that: - Work in third party machine learning environments - Potentially want users to know they are using Box - Achieve an end goal in tandem with other processes - Only want to process files that trigger the Box Skill You can find a great Box Skills tutorial on [Medium](https://medium.com/box-developer-blog/box-skills-ibm-watson-speech-to-text-tutorial-b7e3b3c0a8c7). ## Scopes When an application is created in the Developer Console, the user must configure application scopes. Similar to how users have permissions to access files and folders within Box, applications have their own set of permissions to perform certain actions on behalf of a Box user or a Box enterprise. The name for a set of permissions for an application is a "scope". In short, an application's scopes determine which [endpoints](page://reference) an application can successfully call and are reflected in the access provided by [Access Tokens](g://authentication/tokens) of the application. ### User permissions and scopes It is important to understand that even if an application has the right scopes to perform an action, the user associated with the Access Token making the call needs to have permission to perform the action as well and vice versa. For example, if your application is set up to read files, the authenticated user does need to have permission to read the file you are trying to access. To learn more about how scopes, token permissions, and user permissions work together, see our [security guide](g://security). Next step **Reference:** https://developer.box.com/platform/authentication-methods/ --- ## Untitled *Type: page | Category: Learn Box Platform * Box Platform 101 What is Box Box is a cloud-based content management and file sharing platform that enables individuals and businesses to… # Box Platform 101 ## What is Box [Box](https://www.box.com) is a cloud-based content management and file sharing platform that enables individuals and businesses to store, access, and collaborate on documents and files from anywhere. It offers features like secure file storage, real-time collaboration, and integrations with various productivity tools, enhancing team efficiency and data accessibility. Known for its focus on security and user-friendly interface, Box is widely used for managing digital assets and fostering collaboration within organizations. ## What is Box Platform [Box Platform](https://www.box.com/platform) is a set of tools and APIs offered by Box that allows developers to integrate and customize the capabilities of the Box cloud content management system into their own applications and services. It enables businesses and developers to build secure and scalable content-centric applications, leveraging features like file storage, sharing, and collaboration while maintaining control over data and access. With Box Platform, developers can create tailored solutions that enhance productivity and streamline content management workflows. ## How do I make applications In order to use the [Box API](page://reference), you first have to create an application in Box. This application serves as the gateway for any API call made to the platform. You can use two websites to accomplish this task: the Box Developer Site and the Box Developer Console. Let's take a closer look at what those are. ### Box Developer Site The Box Developer Site is this website you are reading right now. It is a comprehensive resource for developers building solutions on top of Box, and should be used alongside the developer console to create applications and make API calls. You can find a multitude of guides, the full OpenAPI spec, quick starts, sample code, etc all within its pages. The site is updated on a frequent basis with the latest updates posted to the [changelog](page://changelog). ### Box Developer Console The [Box Developer Console](https://app.box.com/developers/console) is an interactive interface that provides developers with tools and resources for managing their applications integrated with Box. It allows for the creation, configuration, and monitoring of apps, offering insights and control over how these apps interact with the Box platform. After you create an application in the console for the first time, you will start seeing a button in the bottom left of the main Box web app. You can use this button to access the console in the future. ## Box Platform Concepts In the following learn sections, we will go into more depth on various topics. But at a high level, these are some terms and concepts to be familiar with. ### User Types There are several [user types](https://support.box.com/hc/en-us/articles/4636533822483-Box-User-Types) to keep in mind when developing on Box Platform. These include users with admin privileges (such as Admin or Co-Admin users) and those without admin privileges (Managed or External Users). Additionally, there are platform-only users, which are categorized as Service Accounts and App Users. Each user type has specific roles and access levels within the Box environment, impacting how they interact with applications and content. At the core, if a user can access a piece of content from the main Box web app, they should be able to access it using the API. ### Application Type There are three main types of applications that can be created in the developer console. They include Platform App, Limited Access App, and Box Custom Skills. You can also create third party and web app integrations. ### Authentication Method Depending on the application type selected, there are one of five different authentication methods that can be used to gain an [access token](g://authentication/tokens). An access token is the key to get through the gateway that is your application to successfully make an API call to Box. Next step **Reference:** https://developer.box.com/platform/box-platform-101/ --- ## Untitled *Type: page | Category: Learn Box Platform * Application Types Box offers various application types to cater to different needs and use cases in application development. Each provides… # Application Types Box offers various application types to cater to different needs and use cases in application development. Each provides different capabilities and authentication method options. ## Platform App [Platform Apps](g://applications/app-types/platform-apps) are versatile and can accommodate most use cases. They allow developers to present Box functionalities within a custom interface. Box provides customizable UI Elements for tasks like browsing, searching, and previewing content. These apps support OAuth 2.0, JWT, and Client Credentials Grant for authentication. Platform Apps are ideal for applications that need to access both their own and others' files, upload and download files, and potentially be listed in the Box Integrations. ## Limited Access App [Limited Access Apps](g://applications/app-types/limited-access-apps) are specifically designed for leveraging Box View or previewing Box content within another application. They have access to a limited number of endpoints and only support App Token authentication. These apps are suitable for use cases like showcasing a professional’s portfolio on a website, providing user manuals on a support site, or creating a custom document viewer for e-books or architectural plans. ## Box Skills [Box Skills](g://applications/app-types/custom-skills), or Custom Skills, are applications that perform custom processing on files uploaded to Box. They use third-party Machine Learning services to extract information from files and apply it as metadata. These skills are enabled on a folder by a Box Admin, and the application server receives an event every time a file is uploaded. Custom Skills are best used for adding metadata to files and integrating with Machine Learning services without handling authentication. ## Web App Integrations [Web App Integrations](g://applications/web-app-integrations) allow third-party applications to integrate seamlessly with the Box user experience. They enable users to edit, share, or modify content stored in Box using a third-party application. Such integrations can add new features to Box users and be added to Recommended Web Integrations in Box Preview, enhancing the user experience by integrating with various content types and file extensions. ## Integrations Publication The [Box Integrations](g://applications/integrations/) is a platform for Box users to discover applications that can be used in conjunction with Box. For developers, listing their application in the Integrations is an effective way to reach new users, particularly for applications suited for use by other enterprises. The process for Integrations publication involves ensuring the app is production-ready, leverages OAuth 2.0 authentication, and submitting it for approval through the Developer Console. Once approved, applications can be featured, most popular, or recently added sections in the Integrations, and they can also be unpublished if necessary. Next step **Reference:** https://developer.box.com/platform/application-types/ --- ## Untitled *Type: page | Category: Learn Box Platform * Learn Box Platform If you are new to Box, start here! In the following pages, you'll learn how all the Box Platform concepts and components… # Learn Box Platform If you are new to Box, **start here**! In the following pages, you'll learn how all the Box Platform concepts and components work together to help you create an application quickly. ## Learn Sections These pages go into more depth on each topic. Checkout each one and become a Box Platform expert. - [Box Platform 101](page://platform/box-platform-101) - [Use Cases](page://platform/use-cases) - [User Types](page://platform/user-types) - [Application Types](page://platform/application-types) - [Authentication Methods](page://platform/authentication-methods) - [Support](page://platform/support) - [Tools](page://platform/tools) Get Started **Reference:** https://developer.box.com/platform/ --- ## Untitled *Type: page | Category: Learn Box Platform * Box Platform glossary This glossary includes terms and definitions used in Box Platform. If you need to find out what a term means, this is… # Box Platform glossary This glossary includes terms and definitions used in Box Platform. If you need to find out what a term means, this is your one stop page. | Box Resource Type/Term | Also known as (AKA) | Description | | --- | --- | --- | | Admin | Superuser, administrator, supervisor | The main admin on an enterprise account. Admins can manage users and groups, view and edit all of their organization’s files and folders, log in to any user’s account within their organization, edit settings for their organization, and run or access reports. The Box Admin is the principal account administrator. | | Admin Console | | The dashboard area for administering a particular enterprise. Accessible by the admin, group admins, and co-admins. | | Anonymous User | | A user that is not logged in. | | App user | | Box app user is a specific type of user within the Box Platform who is associated with applications or services that integrate with Box. App users are only accessible with the API, meaning they do not have login credentials. They can be created by a service account and are only applicable to applications leveraging server to server authentication. App users are tied to the application used to create them, and the user itself cannot be moved under another application. They can however collaborate on content outside of the application. | | Bookmark / web link | Symbolic link, Symlink, soft link, reference, relationship | A clickable reference that allows you to easily access external websites or specific locations within your content structure. | | Box Integrations | App Store | The first place for Box users to find out about applications that they can use in combination with Box. | | Box Command Line Interface | Box CLI | A user-friendly command line tool that allows both technical and non-technical users to leverage the Box API to perform routine or bulk actions. | | Box Custom Skill | Custom Skill, Box Skill | An application that performs custom processing for files uploaded to Box. Skills are designed to make it possible to use third-party machine learning services to automatically extract information from files uploaded to Box. | | Box Embed | | An HTML-based framework that makes it possible to embed the Box Web App experience anywhere in the 3rd party applications. Box Embed provides the ability to upload, search, comment, share, tag, and edit files using Box Edit. | | Box Platform | | An API-driven cloud content management and collaboration platform that provides developers with the tools and infrastructure to build platform applications, integrate workflows, and leverage powerful features for secure document storage, access control, versioning, metadata management, and real-time collaboration. | | Box Sample Code Catalog | | Allows developers and admins to search through code repositories of tools, automation scripts, self paced workshops, and demo apps in multiple programming languages. The catalog contains more that eighty open source repositories and guides. | | Box Shield | | A security solution offered by Box that helps protect sensitive data, prevent unauthorized access, and detect potential threats through automated classification and proactive monitoring. | | Box Skills | | Box Skills are AI-powered capabilities that enhance the functionality of Box by automatically extracting insights and metadata from content. | | Box Relay | | Box Relay allows you to create and configure workflow automations to automate and accelerate business processes centered around content. | | Box Verified Enterprise | BVE | Box Verified Enterprise is a certification program that ensures the security and compliance of an organization's content management system. | | Box UI Elements | | Pre-built UI components that allow developers to add elements of the main Box web application into their own applications. They can be used to navigate through, upload, preview, and select content stored on Box and are available both as React components and framework-agnostic JavaScript libraries. | | Cascade policy | | Box enables you to add metadata instances to a folder, and automatically cascade them to the folder's contents so you don't need to add the instances individually. Using cascading metadata, you can quickly add metadata to multiple files and sub-folders at one time. | | Classification | | An instance of the classification metadata template, containing the classification applied to the file or folder. | | Collaboration | | Working together on a file or folder. | | Collaborations | Permissions, Role-Based Access Control (RBAC), Access Control List (ACL), permission mapping | Collaborations define access permissions for users and groups to files and folders, similar to access control lists. A collaboration object grants a user or group access to a file or folder with permissions defined by a specific role. | | Collaborator | | Someone who shares access to a file or folder. | | Collaborated folder | Shared folder | A shared folder owned by someone within your enterprise. | | Collaboration roles | Permission levels, access levels | The collaboration roles define the level of permissions a user has for a specific file or folder. The collaboration roles in Box are Owner, Co-owner, Editor, Viewer Uploader, Previewer Uploader, and Viewer. Collaboration levels in Box follow a "waterfall" design in which individuals have access only to the folder they are invited into and any sub-folders beneath it. You can also be invited to individual files. | | Collection | | A collection of items, including files and folders. The contents of a collection can be explored in a similar way to which the contents of a folder is explored. | | Content Manager | | A feature in the Admin Console that allows you to: search for and download files and folders in your organization, browse by user to see the files and folders they can access, move files between folders, invite collaborators to folders, get shared links and modify access levels, and delete files and folders from any user’s trash. | | Co-admin | | A user other than the main admin, who has a subset of administrative privileges. Co-admins can perform the same duties as the organization’s admin, but they cannot make changes to the Admin’s permissions or other co-admins' permissions. The default access levels for co-admins include only the ability to manage users and groups, but they can be modified on a per-user basis. | | Platform App | | A tailored application that extends the functionality of Box by integrating with other tools and systems. It's used to streamline workflows and enhance collaboration. It can be created in the Developer Console and has several authentication methods available. | | Developer | Programmer | A skilled professional who designs, builds, and maintains software applications or systems and has access to the Developer Console. In Box, the developer can have an admin role. | | Developer Console | | A portal that allows developers to create, debug, test, and monitor their applications by providing real-time insights into code execution and system performance. | | Enterprise | Repository, content store, file cabinet, Docbase, vault | Enterprise in Box is a comprehensive suite of tools and services provided by Box for large organizations, offering secure file storage, collaboration features, access controls, workflow automation, compliance enforcement, and analytics. It enables efficient document management and teamwork while ensuring data security within an enterprise setting. | | Ethical walls | Information barriers | A mechanism that prevents exchanges or communication that could lead to conflicts of interest and therefore result in business activities ethically or legally questionable. | | Event | | Result of an action taken by the user. See Using the Enterprise Event Stream. | | External collaborator | External user | A collaborator who is not part of an enterprise. | | External collaborated folder | | A folder owned by someone outside your enterprise. | | File | Document, unstructured data | A digital container that stores information or data in a structured format. | | Folder | Directory, container | A directory containing files. | | Group admin | | Group admins can add existing users to their groups, create new users that will be assigned to their groups, and assign folder access to their groups. They can also run reports for their groups. | | Group | Team | Collaborative workspace where users can share files, collaborate on documents, and communicate with each other. | | Item | Object, Box object, content | Can represent a file, a folder or a web link. | | Limited access app | | Secure and restricted application created in the Developer Console that allows specific users to access and interact with designated content within the Box Platform. | | Managed user | | A user account that is centrally controlled and administered by an organization's admin. | | Metadata template | Document class, document type, content type, indexes | A predefined structure that captures and organizes important information about a document or file. | | Metadata attribute | Property, field, keyword, index Value | A metadata attribute is a piece of information that provides descriptive details about data, such as its type, format, or source. | | Personal folder | | A folder owned by an individual user. | | Report | | A file containing a specific data set. You can use the Admin Console Reports tab to run a variety of account-wide reports: usage logs, file/user statistics, and security audits. | | Sandbox | Testing environment | Managed, trackable, non-production, testing environment for developers. | | Service account | | A service account provides developers with a programmatic authentication mechanism for server-side integrations with Box. In other words, an application can authenticate to Box as the service, which is represented by a service account user. A service account can then be used to create other application specific users, called app users. | | Shared link | | A hyperlink to content stored in Box you can share with your coworkers and friends – both inside and outside of the company. Sending someone a shared link to a file or folder is a way to work together with that person around shared content. Customizable permission levels, expiration dates, and optional password-protection make Box shared links a secure, simple way to share important content. | | Software Developer Tool | SDK | A collection of tools, libraries, and documentation that helps developers create software applications for specific platforms or frameworks. | | Task | Action | A specific action or assignment that needs to be completed within the collaborative document creation editor. | | User | Identity, person, authority | An individual who utilizes the collaborative document creation editor to create, edit, and share documents with others. | | Unmanaged user | | A user account that is not centrally managed by an organization and has limited access and control over the content within Box. The unmanaged users may or may not also be external users. | | Version control | | The management and tracking of different versions of a document, ensuring that everyone is working on the most up-to-date version. | | Webhook | | A webhook is a way for an application to provide real-time data or notifications to another application by sending HTTP POST requests. | | Workflow | | Workflows within Box are automated sequences of tasks that help streamline and track the progress of document-centric processes, ensuring efficient collaboration and timely completion. | Next step **Reference:** https://developer.box.com/platform/box-glossary/ --- ## Untitled *Type: page | Category: Learn Box Platform * Start Creating Now that you have learned all about the various parts that makeup Box Platform, you are ready to jump in and start creating… # Start Creating Now that you have learned all about the various parts that makeup Box Platform, you are ready to jump in and start creating. Visit the [Box Developer Console](https://cloud.app.box.com/developers/console) to begin! If you are looking for other topics to learn about, be sure to checkout the following: - [Architecture patterns](page://platform/appendix/architecture-patterns): This page goes over some typical infrastructure patterns we see. - [User Models](page://platform/appendix//user-models): This page goes over how to use the users types discussed earlier in this series. - [Locating Common Values](page://platform/appendix/locating-values): This page goes over how to find pieces of information like user IDs. - [Errors](g://api-calls/permissions-and-errors/common-errors): This page lists out all the error codes you can receive **Reference:** https://developer.box.com/platform/start-creating/ --- ## Untitled *Type: page | Category: Learn Box Platform * Tools Box offers several tools for you to use to jump start your development. Check them out below. Sample Code Catalog The sample code… # Tools Box offers several [tools](g://tooling) for you to use to jump start your development. Check them out below. ## Sample Code Catalog The [sample code catalog](https://developer.box.com/sample-code/) is the most recent tool we have launched on the Box Developer site. It pulls code sample repositories from multiple places, consolidating them in one place for you to browse. It allows you to filter by language and task. We update the list regularly so the you have access to the most up to date code. ## Box CLI The Box Command Line Interface (CLI) is a tool for making requests to Box APIs from your terminal window or command prompt. It takes less than five minutes to set up and provides you direct access to the API. We also offer a suite of [sample scripts](g://cli/scripts) to jump start any administration automation tasks. ## SDKs Box supports several coding languages with our [SDK libraries](page://sdks-and-tools). It is highly recommended to use SDKs when creating a solution since the libraries automatically handle things like authentication and retry logic for you. In addition, the API reference pages contain samples for all the languages directly in the site; however, each Github repo has a docs section with all that language's samples too. ## Postman Collection As an industry standard in software development, Postman helps developers learn APIs quickly, providing real time testing and code samples. You can find our Postman Collection on the [Postman website](https://www.postman.com/boxdev). You can also check out the YouTube video below. Next step **Reference:** https://developer.box.com/platform/tools/ --- ## Untitled *Type: page | Category: Learn Box Platform * User Types A critical part of planning and developing an application is understanding the types of users involved. There are four main types… # User Types A critical part of planning and developing an application is understanding the types of users involved. There are four main types of users: managed (internal and external), admin, service account, and app users. Let's take a closer look at the differences. # What type of user does my application use? The type of user an application is authenticated as is dependent on the type of application created, as well as the type of authentication used to create an Access Token. ## Admin or Co-Admin User The Box Admin is the principal Box account administrator. They can make additional co-admins with similar or more restrictive administrative privileges. Admins and Co-Admins can directly edit, delete, enforce security settings, and run reports against these users via the Admin Console. ## Managed Users Each Box enterprise is assigned a unique enterprise ID. Managed Users are any users that belong to one enterprise ID. Managed Users consume a standard Box license and often, but not always, share the same email domain. # Log in as Admin User Some applications need permissions that only Admins have in order to properly operate and therefore require an Admin to log in. An example of this would be a security application that monitors enterprise events and takes action on suspicious events. The events endpoint can only be used by Admins or a Co-Admin with permission to access reporting. ## External Users An externally managed user, or External User, is a Managed User that belongs to a different enterprise ID. External users are often encountered when they are collaborated in on content owned by a Managed User of the application's enterprise, or when they authorize an OAuth 2.0 application. These users still have their own Box accounts, but cannot be managed via the Admin Console. ## Service Account A Service Account provides developers with a programmatic authentication mechanism for server-side integrations with Box. In other words, an application can authenticate to Box as the service, which is represented by a Service Account user. Service Accounts are only accessible with the API, meaning they do not have login credentials. A Service Account can then be used to create other application specific users, called App Users described further below. ### Creation A unique Box Service Account is automatically generated as soon as an application, leveraging server authentication, is [authorized](g://authorization/custom-app-approval) in the Admin Console. From that point forward, the Service Account represents the application in the Box enterprise. Since every Box account must have an email address, Box assigns one. The format will always be `AutomationUser_AppServiceID_RandomString@boxdevedition.com`. For example: `AutomationUser_123456_6jCo6Pqwo@boxdevedition.com`. This is why you may sometimes hear the Service Account referred to as an Automation User. The numbers surrounded by underscores are also unique to the application and are called a Service ID. To locate a Service ID in the [Developer Console](https://app.box.com/developers/console), click on the tile for an application and look at the URL. For example, `https://example.app.box.com/developers/console/app/123456`. As you can see, this application corresponds to the Service Account provided in the example above. By default, most Service Accounts are allocated 10GB of storage. This is because they abide by the storage allocation set in the **New User Default Settings** found under the **User Settings** tab of the Admin Console. This amount may differ based on whether an enterprise updated this setting or not. To update the amount of storage allocated to a Service Account after its creation, make an API call to the [update user](e://put-users-id) endpoint and pass in the desired value, in bytes, using the `space_amount` body parameter. Once the Service Account is generated, a section is automatically added to the General tab of the [Developer Console](https://app.box.com/developers/console) revealing the email address. If someone attempts to make API calls using a Service Account Access Token before the application is authorized in the Admin Console they will receive an error message: `"error": "unauthorized_client"` `"error_description": "This app is not authorized by the enterprise"` ### Use Cases - *Distribution Publishing*: upload and share files with any number of users whether or not they are authenticated - *On-Premises Systems and Devices*: programmatically ingest content from on-premises systems and connected devices - *Content Migration and Monitoring*: move content from on-premises to the cloud or between cloud providers - *Event Monitoring*: monitors events in an enterprise to ensure compliance and or trigger workflows based on actions - *Content Archive*: house minimally accessed content ### Permissions The endpoints that a Service Account Access Token can successfully interact with are determined by the application [scopes](g://api-calls/permissions-and-errors/scopes) configured in the [Developer Console](https://app.box.com/developers/console). Depending on the granted scopes, a Service Account may have the ability to perform Admin actions. # Admin Approval With the right [scopes](g://api-calls/permissions-and-errors/scopes) enabled, a Service Account can perform many Admin actions. For this reason JWT applications need explicit [Admin approval](g://authorization/custom-app-approval) before they can be used in an enterprise. ### UI Access Only Primary Admins have the ability to log in as a Service Account through the [Content Manager](https://support.box.com/hc/en-us/articles/360044197333-Using-the-Content-Manager) in the Admin Console. To do this, use the Content Manager's search bar to locate the name of the application, right click on it, and select “Log in to user’s account”. A Service Account can be thought of as having the permissions of a Box Co-Admin. Similar to co-admins being unable to manage each other, co-admins cannot log in as a Service Account user. Service Accounts are not currently visible in the users and group tab of the Admin Console. ### Folder Tree and Collaboration Because a Service Account represents an application as a user within the enterprise, it has its own folder tree and content ownership capabilities. By default this folder tree is empty because the Service Account does not initially own or collaborate on content. This is similar to when you first land on your All Files page in a newly provisioned Box account. To collaborate a Service Account on existing content use the assigned email address to invite them as you would any other user. If you are instead adding the collaboration [via the API](e://post-collaborations) you will need to use an Access Token for a user that already has access to the content and has the appropriate collaboration permissions to invite collaborators. You will also use the Service Account’s user ID, which is returned when making a call to the [get current user endpoint](e://get-users-me) using an Access Token for the Service Account. It is possible to assign a Service Account an email alias if that is easier to remember when adding collaborations. ### Box View A Service Account is also automatically generated when a Limited Access App is created in the [Developer Console](https://app.box.com/developers/console). This Service Account has some additional restrictions that a Service Account associated with a Platform App does not. - All content used within the Limited Access App must be uploaded and owned by the Service Account - The Service Account can not access any other user's information or content - The Service Account can not create or otherwise manage any type of new user - The Service Account can only access a subset of APIs related to previewing content ## App User App users are only accessible via the API, meaning they do not have login credentials. They can be created by a Service Account and therefore are only applicable to applications leveraging server to server authentication. App Users are tied to the application used to create them, and while they can collaborate on content outside of the application, the user itself cannot be moved under another application. ### Creation App users are created using a Service Account access token to call the [create user endpoint](e://post-users). The `is_platform_access_only` body parameter must be set to true or a managed user is created instead. Since every Box account must have an email address, Box assigns one. The format will always be `AppUser_AppServiceID_RandomString@boxdevedition.com`. For example: `AppUser_1234567_LOCqkWI79A@boxdevedition.com`. The numbers surrounded by underscores are also unique to the application and are called a Service ID. To locate a Service ID in the [Developer Console](https://app.box.com/developers/console), click on on the tile for an application and look at the URL. For example, `https://exampl.app.box.com/developers/console/app/1234567` . As you can see, this application corresponds to the App User in the example above. ### Use Cases App Users extend the functionality of Box’s Platform to applications serving any user, regardless of if they have an existing Box account. App users are often used by applications that manage their own user authentication, but want to store the data in unique Box user accounts. - *Customer Portals*: Websites or applications where clients or patients can log in to access information provided by employees at a company and/or to store and retrieve their own sensitive documents. - *Vendor Portals*: Content distribution sites for companies to provide materials including marketing collateral, price lists, product information, sales agreements or contracts, and other documents to vendors. Box's groups and permission model allow for companies to organize content for partners based on partner criteria and/or tier. - *Branded Customer Facing Applications*: The ability to create App Users on behalf of an end-user allows companies to build seamless customer-facing features such as permissions, auditing, and reporting. This is particularly valuable for regulated industries such as Financial Services and Healthcare. Moreover, user-based data from our [reporting capabilities](e://get-events) allows developers to leverage analytic tools to better understand user behavior. ### Permissions App Users cannot see or interact any content in the folder tree of the Service Account unless explicitly added as a collaborator. Again, because App Users does not have login credentials, they cannot access content outside of the platform application. ### UI Access App users are accessible via the [Users & Groups tab](https://support.box.com/hc/en-us/articles/360043695714-Admin-Console-Guide) of the Admin Console. To filter for these users, use the view options button > Role > App Users. App Users are also accessible through the [Content Manager](https://support.box.com/hc/en-us/articles/360044197333-Using-the-Content-Manager) in the Admin Console. ### Folder Tree and Collaboration Each App User has its own folder tree and content ownership capabilities. By default this folder tree is empty because they do not initially own or collaborate on content. This is similar to when you first land on your All Files page in a newly provisioned Box account. To collaborate an App User on existing content use the assigned email address to invite them as you would any other user. If you are instead adding the collaboration [via the API](e://post-collaborations) you will need to use an Access Token for a user that already has access to the content and has the appropriate collaboration permissions to invite collaborators. ## As-User If you are using OAuth 2.0, JWT, or CCG as the authentication method for your application, it is possible to make what are called `as-user` calls. This means that even though you created an original connection to the Box API as yourself or as a service account, you can make subsequent calls impersonating another user. This is useful in automating administrative tasks like folder reorganization or employee provisioning. In order to make `as-user` calls, the appropriate scope must be added to the application when creating it in the developer console. For example, in an OAuth 2.0 platform app, you would need to turn on this switch. Next step **Reference:** https://developer.box.com/platform/user-types/ --- ## Untitled *Type: page | Category: Learn Box Platform * Support The Box Developer Relations team loves to help developers in any way we can. Outside of interviewing developers regularly, we… # Support The Box Developer Relations team loves to help developers in any way we can. Outside of interviewing developers regularly, we provide the following options for you to connect with us. ## Developer Forum Recently, we relaunched our developer community. It is now even easier to connect with developers like yourself and ask questions about your development issues. You can also share any successes you have had. [Join Today](https://community.box.com/)! ## Medium Blog We + some of our partners write tutorials and make announcements on our [Medium blog](https://medium.com/box-developer-blog) regularly. Typically, we release content every Tuesday, but frequently, it is even more often than that. We welcome any requests for content on our developer forum. ## Box Platform Twitter Like the changelog on the developer site, we post Box Platform updates, as well as new blogs. You can follow at [Box Platform](https://twitter.com/BoxPlatform). Next step **Reference:** https://developer.box.com/platform/support/ --- ## Untitled *Type: page | Category: Learn Box Platform * Use Cases Before beginning application development, it is best to assess if your use case is a good fit for the Box Platform. Generally… # Use Cases Before beginning application development, it is best to assess if your use case is a good fit for the Box Platform. Generally speaking, content centric processes perform best. Some questions to ask when assessing if a use case include: - Is content always involved in the process? - Does the process involve moving content from one place to another? - Can the workflow abide by [waterfall permissions](https://support.box.com/hc/en-us/articles/360043697254-Understanding-Folder-Permissions)? - Does the process involve administrative tasks that may be automated? If you answered **yes** to the above questions, you most likely have a great use case for Box Platform. Some common customer solutions include: - Marketing asset management - Secure document vaults - Wealth management portals - Automatic folder creation based on user provisioning - Adding relevant metadata using machine learning - Claim reviews with built-in approval/rejection flows - Event monitoring for security and auditing Still not sure if you have a good use case? Reach out to your Box account team. Next step **Reference:** https://developer.box.com/platform/use-cases/ --- ## Untitled *Type: page | Category: Learn Box Platform * Branding Guidelines We are glad you are using Box Platform, and we want you to be able to broadcast to the world that you are using Box… # Branding Guidelines We are glad you are using Box Platform, and we want you to be able to broadcast to the world that you are using Box. However, it is very important that your application not be mistaken for an official Box application. For this reason, we created a guide to using our name and logo. ## Approved logos Approved Box logos can be found in [this Box folder](https://cloud.app.box.com/v/BoxCorporateLogo). ## Things to do ### Inform users Let users know when they’re connecting to Box. Many apps feature a “connect to cloud services” menu, or something similar. In this case, you should feel free to use our name and logo to help people find us. ### Contact us We’re here to help. Many situations can be ambiguous, and we’ll absolutely work with you to make sure that your app works within our guidelines. Contact us with any questions. ## Things not to do ### Do not impersonate Box Please don't call your application anything that might be mistaken for an official Box application. This means no use of the word "Box" unless it’s abundantly clear that it’s not official. For example, "Unofficial Box Client" is certainly clear enough, while "Box App for Android" is not. If you include your own brand name (for example, "My Company Box Client"), you’re probably fine. Nonetheless, this is probably the most ambiguous guideline, so please [contact us](https://support.box.com/hc/en-us/requests/new) if you have any questions, and we’ll get you sorted out right away! In short though, this means: - Don't use our logo or any similar logo or part of our logo as the icon for your application. - Don't use our name or logo in any way inside your application that would make it look like it’s an official Box application. ### Don't alter Box logo Don't alter the 'Box' logo in any way when using it in your application. ### Don't use older names Don't refer to us as `Box.net` or `Boxnet`. Our company is known as "Box" only. **Reference:** https://developer.box.com/platform/appendix/branding-guidelines/ --- ## Untitled *Type: page | Category: Learn Box Platform * Architecture Patterns We recommend creating a visual representation for your application before writing any code. The architecture patterns… # Architecture Patterns We recommend creating a visual representation for your application before writing any code. The architecture patterns shown below are generic and do not represent an exhaustive list of possibilities. Would you like assistance with application architecture? Contact your account team to purchase Box Consulting services. ## Administrative tasks Components: - A server or local machine running a PowerShell script - An identity provider with a user provisioning/deprovisioning service - A [Service Account](page://platform/user-types/#service-account) owned folder containing a personal folder for each user - A PowerShell script based on a time that monitors the [event stream](e://resources/event) and creates/collaborates each user on their personal folder ## Vault Portal Components: - A custom portal allowing users to collaborate in a non-Box branded environment - A load balancer distributing users to a web server with the deployed portal - Users can login using credentials maintained in an identity provider, which are then mapped to [App User](page://platform/user-types/#app-user) information from Box within a data server. - Other site data is stored on the data server ## Box Skill In this example, external users upload their resumes via a [file request](https://support.box.com/hc/en-us/articles/360045304813-Using-File-Request-to-get-Content-from-Anyone). A [Box Skill](g://applications/app-types/custom-skills) is set to monitor any upload/move/copy actions in a specific folder. When an event occurs, the file is sent to a cloud provider to be processed by any machine learning service. Once it is processed, information is [saved back to the file as metadata](e://post-files-id-metadata-global-boxSkillsCards). This metadata can then be used in another process or for future reference. **Reference:** https://developer.box.com/platform/appendix/architecture-patterns/ --- ## Untitled *Type: page | Category: Learn Box Platform * Locating Common Values User IDs As a developer To locate your own user ID via the Box web app, navigate to your All Files page. Click the… # Locating Common Values ## User IDs ### As a developer To locate your own user ID via the Box web app, navigate to your **All Files** page. Click the circle in the top right corner and select **Account Settings** from the dropdown menu. Your user ID is the **Account ID** value listed in the **Account Details** section of the **Account** tab. To locate your user ID via API, navigate to the Developer Console and generate a [Developer Token](g://authentication/tokens/developer-tokens) or obtain an [Access Token](g://authentication/tokens/access-tokens) for yourself. Use this token with the [get current user endpoint](e://get-users-me), which will return your user ID in the `id` field. ### As an Admin If your account type provides access to the [Content Manager](https://support.box.com/hc/en-us/articles/360044197333-Using-the-Content-Manager), click on the user in question from user list. The URL will reveal their user ID. For example, `https://.app.box.com/master/content/2267862105/0/0`, the user ID is `2267862105`. To locate user IDs via API, navigate to the Developer Console and generate a [Developer Token](g://authentication/tokens/developer-tokens) or obtain an [Access Token](g://authentication/tokens/access-tokens) for yourself. Then, make an API call to the [list enterprise users](e://get-users) endpoint. This will provide a list of all users in your enterprise. ## Enterprise ID ### As a developer To find your enterprise ID via API, navigate to the Developer Console and generate a [Developer Token](g://authentication/tokens/developer-tokens) or obtain an [Access Token](g://authentication/tokens/access-tokens) for yourself. Use this token with the [get current user endpoint](e://get-users-me) and request the `enterprise` field. ### As an Admin From the **Admin Console**, navigate to the **Account & Billing Tab**. The Enterprise ID is located under the **Account Information** section. ## Content IDs ### As a developer To locate a file ID via the Box web app, navigate to the file's preview in your browser and look at the URL. For example, the file ID of `https://app.box.com/file/1234567890` is `1234567890`. To locate a folder ID via the Box web app, navigate into the folder and look at the URL. For example, the folder ID of `https://app.box.com/folder/9876543210` is `9876543210`. To locate content IDs via the API, you may want to start by listing all items at the All Files level by passing `0` as the `folder_id` of the [list items in folder](e://get-folders-id-items) endpoint. ### As an Admin If you have access to the [Content Manager](https://support.box.com/hc/en-us/articles/360044197333-Using-the-Content-Manager), click on the user in question from the user list and then navigate to the content. The URL will reveal the folder and/or file id. For example, `https://app.box.com/master/content/1987212562/88560510648/0/532181212706`. The User ID is `1987212562`, the folder ID is `88560510648` and the file ID within that folder is `532181212706`. **Reference:** https://developer.box.com/platform/appendix/locating-values/ --- ## Untitled *Type: page | Category: Learn Box Platform * Appendix In this section, you will find some other getting started related material. It isn't vital to know from the get go, but it can help… # Appendix In this section, you will find some other getting started related material. It isn't vital to know from the get go, but it can help pinpoint you to a solution if you are having an issue. - [User Models](page://platform/appendix//user-models): This page goes over how to use the users types discussed earlier in this series. - [Architecture patterns](page://platform/appendix/architecture-patterns): This page goes over some typical infrastructure patterns we see. - [Locating Common Values](page://platform/appendix/locating-values): This page goes over how to find pieces of information like user IDs. - [Branding Guidelines](page://platform/appendix/branding-guidelines/): This page lists out various things to keep in mind if you plan to use the Box brand for your project **Reference:** https://developer.box.com/platform/appendix/ --- ## Untitled *Type: page | Category: Learn Box Platform * User Models Once you confirm your use case is a good fit for Box Platform and you have a solid understanding of the types of users involved… # User Models Once you confirm your [use case](page://platform/use-cases) is a good fit for Box Platform and you have a solid understanding of the [types of users](page://platform/user-types) involved, you can select a user model to begin [application architecture](page://platform/appendix/architecture-patterns). ## Classic In this model, the application has internal and external users. The external users share or collaborate on content with internal users who use the Box web application. - **Internal User Type**: [Managed Users](page://platform/user-types/#managed-users) - **External User Type**: [App Users](page://platform/user-types/#app-user) - **Content Owned By**: Application [Service Account](page://platform/user-types/#service-account) or [Managed Users](page://platform/user-types/#managed-users) - **Examples**: Vault Portals, Document Submissions, Field Worker Applications Benefits of this user model: 1. Removes the need to build additional functionality for internal users 2. Allows App Users to be mapped to your own identity system like `Auth0` 3. Allows reporting on all actions to meet to meet security and compliance requirements ## App User In this model, the application has internal and external users who all leverage the same custom UI. - **Internal User Type**: [App Users](page://platform/user-types/#app-user) - **External User Type**: [App Users](page://platform/user-types/#app-user) - **Content Owned By**: [App Users](page://platform/user-types/#app-user) - **Examples**: Vault Portals, Document Submissions, Field Worker Applications Benefits of this user model: 1. Allows for a custom experience for internal and external users 2. Separates managed user and application content by allowing managed users to have separate App User accounts 3. Allows App Users to be mapped to your own identity system like `Auth0` 4. Allows reporting on all actions to meet to meet security and compliance requirements or tracking in other systems ## Service Account In this model, the application has internal and external users, but the user object already exists. This model also works well when users are transient in nature, but the content must persist. - **Internal User Type**: [Managed Users](page://platform/user-types/#managed-users) - **External User Type**: Managed by your customer’s applications - **Content Owned By**: Application [Service Account](page://platform/user-types/#service-account) - **Examples**: Wealth Management Portal, Insurance Claim Workflow Benefits of this user model: 1. Useful when the App User model would complicate existing applications 2. Useful when there is not a good 1:1 end user/app user mapping, such as users mapped as groups 3. Permissions are easier to manage, since the Service Account owns all content 4. Ability to implement a token exchange to ensure that broad scoped access to the Service Account does not occur ## System to system In this model, no user content normally needs to be handled. - **External User Type**: N/A - **Internal User Type**: N/A - **Content Owned By**: Application [Service Account](page://platform/user-types/#service-account) - **Examples**: Back Office Applications, Integrations, User Provisioning, Folder Auto-Creation Benefits of this user model: 1. Useful when user construct isn’t needed (e.g. departmental or company owned content that transcends user ownership) 2. Allows for complete control of permission assignment to backend services since the Service Account can be granted elevated privileges **Reference:** https://developer.box.com/platform/appendix/user-models/ --- --- # Developer Guides This section contains 469 documentation items covering guide, quick-start. Categories: Guides , Box AI Studio , API Calls , Applications , Box Archive , Authentication , Authorization , Box AI , Box Relay , Box MCP Server , Box Sign , CLI , Collaborations , Comments , Collections , Box Doc Gen , Downloads , Events , Embed Box , Files , File Requests , Folders , Start Here , Integration Mappings , Legal Holds , Metadata , Mobile , Representations , Retention Policies , Search , Security , Shared Links , Box Skills , SSO & App users , Tasks , Tooling , Trash , Uploads , Users , Web Links , Webhooks ## Untitled *Type: guide | Category: Guides * Guides # Guides **Reference:** https://developer.box.com/guides/ --- ## Untitled *Type: guide | Category: Box AI Studio * Get started with AI studio Box AI Studio is available only for Enterprise Advanced accounts. To start creating custom AI agents with AI… # Get started with AI studio Box AI Studio is available only for Enterprise Advanced accounts. To start creating custom AI agents with AI studio you need a platform application with enabled Box AI scope and a developer token to authenticate your calls. ## Create a platform application First you need to create a platform application you will use to make calls. To create an application, follow the guide on [creating platform apps](g://applications/app-types/platform-apps). ## Enable Box AI studio To use Box AI studio, make sure it is enabled by a Box admin in the Admin Console. If you are a Box Admin, you will find the necessary information in [Enabling Box AI Studio and Managing Agents](https://support.box.com/hc/en-us/articles/37228079461267-Enabling-Box-AI-Studio-and-Managing-Agents/#h_01JH9HAMP43YYN6VWM51QCK413). To interact with Box AI API, you need the `ai.readwrite` [scope](g://api-calls/permissions-and-errors/scopes) added for your application. Before you add the scope, make sure that the Box Admin has granted you the access to Box AI API. If you can't see the **Manage AI** option in your app configuration settings, contact your admin. To add a scope: Open your application in Developer Console. Go to **Configuration** > **Required Access Scopes** > **Content Actions** Select the **Manage AI** scope. Box Platform will automatically include the scope when making the call. If you are added as an collaborator for a given app, but do not have Box AI API access, you will see the **Manage AI** scope checked and grayed out. This means the app owner has the AI scope enabled but you cannot change this setting. Submit your app for [authorization or enablement](g://authorization). If you want to enable Box AI API for an existing application, you must [re-authorize](g://authorization/custom-app-approval#re-authorization-on-changes) it. ## Generate a developer token You need a developer token to authenticate your app when sending requests. To generate a token: 1. Go to **Developer Console** > **My Platform Apps**. 2. Click the **Options menu** button (…) on the right. 3. Select **Generate Developer Token**. The token will be automatically generated and saved to clipboard. You can also open your app, go to **Configuration** > **Developer Token** and generate the token. A developer token is only valid for one hour. For additional details, see [developer token](g://authentication/tokens/developer-tokens). After you generate the token, you can use it in cURL or other clients, such as [Postman](g://tooling/postman), to make calls. **Reference:** https://developer.box.com/guides/ai-studio/getting-started-ai-studio/ --- ## Untitled *Type: guide | Category: Box AI Studio * Box AI Studio Box AI Studio is available only for Enterprise Advanced accounts. Box AI Studio allows you to build and manage custom AI… # Box AI Studio Box AI Studio is available only for Enterprise Advanced accounts. [Box AI Studio](https://support.box.com/hc/en-us/articles/37228079461267-Enabling-Box-AI-Studio-and-Managing-Agents) allows you to build and manage custom AI agents to best suit your business needs. For example, you can create an AI agent that acts as a compliance consultant, answering questions regarding customer documentation with the FedRAMP Moderate compliance in mind. ## Box AI Studio capabilities Currently, you can configure Box AI agent to answer user questions or generate text you can use in your documents. ## Supported languages Box AI studio works in a number of languages including English, Japanese, French, Spanish, and many more. However, the underlying models are primarily trained on English language documents. This means that prompts in other languages may return answers of lower quality than in English. Tests have shown satisfactory results for summarizing, checking grammar and spelling, and answering questions, but bear in mind that the results may be different than in English. Switch the language to Japanese to get better results for this language. **Reference:** https://developer.box.com/guides/ai-studio/ --- ## Untitled *Type: guide | Category: API Calls * Allow domain access To use the Box APIs it is important that your application and users have access to the following domains, where needed… # Allow domain access To use the Box APIs it is important that your application and users have access to the following domains, where needed. ## File preview To enable file preview, your application might need to load javascript file from the Box content delivery network (CDN). This file is loaded from the following domains. - `api.box.com` - `boxcdn.net` - `boxcloud.com` - `dl2.boxcloud.com` to `dl20.boxcloud.com` ## File downloads The following API domains are used to download files via the Box API. - `api.box.com` to initially request a file to download - `dl.boxcloud.com` to actually download files for authenticated users - `public.boxcloud.com` to actually download files for unauthenticated users Ensuring access to these domains is only a first step to downloading a file. To download a file the users need to have proper access permissions and need to be fully authenticated where needed. ## File uploads The following API domains are used to upload files via the Box API. - `api.box.com` to start a file upload - `upload.app.box.com` and `upload.box.com` to upload the file to Box **Reference:** https://developer.box.com/guides/api-calls/allowing-domain-access/ --- ## Untitled *Type: guide | Category: API Calls * API versioning strategy Box provides versioning capabilities for selected API endpoints. The version control system guarantees seamless… # API versioning strategy Box provides versioning capabilities for selected API endpoints. The version control system guarantees seamless functioning of existing endpoint versions, even if Box introduces new ones. API versioning empowers Box to continually enhance its platform, while also offering third-party developers a reliable avenue for feature updates and deprecations. To stay informed about the forthcoming API modifications, monitor the [Changelog](page://changelog) and maintain a current email address in the Developer Console's App Info section. In 2024, Box introduced year-based API versioning. All endpoints available at the end of 2024 were assigned the version `2024.0`. **No action is required for API users to continue using Box APIs.** To make version-aware API calls, include the `box-version` header with the value `2024.0` in your requests. ## How Box API versioning works Box API supports versioning in `header`. To determine which version to use, look at the API reference and included sample requests. ### Versioning in header Box API processes the `box-version` header which should contain a valid version name. For example, when a client wants to get a list of all sign requests using version `2025.0`, the request should look like this: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'box-version: 2025.0' \ --header 'Authorization: Bearer … ``` If the provided version is correct and supported by the endpoint, a response is sent to the client. If the endpoint is available in multiple versions, the response will include the `box-version` header, which indicates the version used to handle the request. Endpoints introduced after 2024 may return a `400` error code if the version is incorrect. More information about versioning errors can be found [here](g://api-calls/permissions-and-errors/versioning-errors). If your request doesn't include a version, the API defaults to the initial Box API version - `2024.0` - the version of endpoints available before year-based versioning was introduced. However, relying on this behavior is not recommended when adopting deprecated changes. To ensure consistency, always specify the API version, with each request. By making your application version-aware, you anchor it to a specific set of features, ensuring consistent behavior throughout the supported timeframe. ## Release schedule and naming convention Box can introduce a new breaking change to certain endpoints **once per year**, which results in a new API version. Introducing a new version of the Sign Request endpoint means that **all paths and HTTP methods** of an endpoint will support it. For example, if Sign Request endpoints receive a new version it will apply to all endpoints listed in the table: | Method | Request URL | Description | | --- | --- | --- | | GET | https://api.box.com/2.0/sign_requests/:id | Retrieves specific sign request details. | | GET | https://api.box.com/2.0/sign_requests/ | Retrieves all sign requests. | | POST | https://api.box.com/2.0/sign_requests/ | Creates new sign requests. | | POST | https://api.box.com/2.0/sign_requests/:id/resend | Sends a specific sign request again. | | POST | https://api.box.com/2.0/sign_requests/:id/cancel | Cancels a specific sign request. | ### Naming convention New API versions are labeled according to the calendar year of their release. **Example**: If a new version of the Sign Requests endpoint is released in 2025, it will be named `2025.0`. Box can issue a new breaking change to API endpoints **once** per year, reserving the right to release an additional breaking change to address security or privacy concerns. In such cases, the new version will be incremented by one in the suffix. **Example**: If security issues need addressing in the previously released version `2025.0` of Sign Requests, the new version will be labeled `2025.1`. Each stable version is supported for a minimum of 12 months. This means that when a new version is released, the previous version becomes deprecated and will be available for use, but no new features will be added. It also means, that a new version cannot be released sooner than every 12 months. We strongly recommend updating your apps to make requests to the latest stable API version. However, if your app uses a stable version that is no longer supported, then you will get a response with an HTTP error code `400 - Bad Request`. For details, see [Versioning Errors](g://api-calls/permissions-and-errors/versioning-errors). ### Endpoint versioning indication To keep you informed about the current API state, and improve the readability of the versioned API reference, the affected endpoints are marked with a pill based on the `x-stability-level` tag or `deprecated` attribute. | Schema element | Pill name | Description | | --- | --- | --- | | x-stability-level: beta | Beta | Endpoints marked with beta, are offered subject to Box’s Main Beta Agreement, meaning the available capabilities may change at any time. When the beta endpoint becomes stable, the beta indication is removed. | | x-stability-level: stable or no x-stability-level tag | Latest version | Latest version marks the most recent stable API version of an endpoint. | | deprecated: true | Deprecated | An endpoint is deprecated, which means it is still available for use, but no new features are added. Such an endpoint is annotated with the deprecated attribute set to true. | ## Versioning errors When using versioned API actions such as calling an incorrect API version in header or a deprecated version can lead to errors. For details on possible errors, see [versioning errors](g://api-calls/permissions-and-errors/versioning-errors). ## How Box SDK versioning works The versioning strategy applies only to [next generation generated SDKs](page://sdks-and-tools/#next-generation-sdks). Box SDKs support the **All Versions In** SDK approach. This means that every release of SDK provides access to all endpoints in any version which is currently live. All generated SDKs use manager's approach - they group all endpoints with the same domain in one manager. For example `FolderManager` contains methods to: `create_folder`, `get_folder_by_id`, `update_folder_by_id`, `delete_folder_by_id`, `get_folder_items` and `copy_folder`. This division is done based on the value of `x-box-tag` field, which is assigned to each method in Public API Service specification. It mostly corresponds to the root of the endpoint URL, but not necessarily. For example: `FolderManager` contains methods with `https://api.box.com/2.0/folders` root URL, but the same base URL is also used in some methods of `SharedLinkFoldersManager`. References to all managers are stored under one Box Client object. See an example of the endpoint's lifecycle: Initial state (only one version is available). ``` class FilesManager { async updateFileById( fileId: string, requestBody: UpdateFileByIdRequestBody, queryParams: UpdateFileByIdQueryParams, headers: UpdateFileByIdHeaders ): Promise < FileFull > {} } ``` A new `v2025_0` version of the endpoint is introduced (previous version is deprecated). The SDK introduces a new method for each new version of an endpoint. These methods are stored in the same manager as the old ones, but their names and corresponding classes are suffixed with the version number. The old method is deprecated with a notice indicating the minimal maintenance date – this will be the date when the endpoint will be considered for end-of-life status. ``` class FilesManager { /** * @deprecated This endpoint will be EOL'ed after 05-2026. */ async updateFileById( fileId: string, requestBody: UpdateFileByIdRequestBody, queryParams: UpdateFileByIdQueryParams, headers: UpdateFileByIdHeaders ): Promise<FileFull> {} async updateFileById_2025_0( fileId: string, requestBody: UpdateFileByIdRequestBody_2025_0, queryParams: UpdateFileByIdQueryParams_2025_0, headers: UpdateFileByIdHeaders_2025_0 ): Promise<FileFull_2025_0> {} } ``` The API endpoint is marked as End-of-Life (EOL) The SDK releases a breaking change release with removed end-of-life (EOL) endpoints. Ideally, we should group the end-of-life dates for all endpoints into one date per quarter to avoid releasing numerous new major versions of SDKs. ``` class FilesManager { async updateFileById_2025_0( fileId: string, requestBody: UpdateFileByIdRequestBody_2025_0, queryParams: UpdateFileByIdQueryParams_2025_0, headers: UpdateFileByIdHeaders_2025_0 ): Promise < FileFull_2025_0 > {} } ``` ## Breaking vs non-breaking changes Breaking changes in the Box API occur within versioned releases, typically accompanied by a new major API version. Minor adjustments, which do not disrupt existing functionality, can be integrated into an existing API version. The following table lists both breaking and non-breaking changes. | API Change | Breaking change | | --- | --- | | New endpoints | No | | New read-only or optional fields in request | No | | New required fields in request | Yes | | New string constant in request | Yes | | Deprecation | No | | Retired / End-of-Life endpoints | Yes | | Rename/reshape of a field, data type, or string constant | Yes | | More restrictive change to field validations | Yes | | Less restrictive change to field validations | No | | Changing HTTP status code returned by an operation | Yes | | Removing a declared property | Yes | | Removing or renaming APIs or API parameters | Yes | | Adding a required request header | Yes | | Adding more error codes | No | | Removing or modifying error codes | Yes | | Adding a member to an enumeration | Yes | The [oasdiff](https://github.com/Tufin/oasdiff/blob/main/BREAKING-CHANGES-EXAMPLES.md) tool allows detecting most of the possible breaking changes. ## AI agent configuration versioning [AI agent](g://box-ai/ai-agents) versioning gives the developers more control over model version management and ensures consistent responses. For details, see [AI agent configuration versioning guide](g://box-ai/ai-agents/ai-agent-versioning). ## Support policy and deprecation information When new versions of the Box APIs and Box SDKs are released, earlier versions will be retired. Box marks a version as `deprecated` at least 24 months before retiring it. In other words, a deprecated version cannot become end-of-life sooner than after 24 months. Similarly, for individual APIs that are generally available (GA), Box declares an API as `deprecated` at least 24 months in advance of removing it from the GA version. When we increment the major version of the API (for example, from `2025.0` to `2026.0`), we're announcing that the current version (in this example, `2025.0`) is immediately deprecated and we'll no longer support it 24 months after the announcement. We might make exceptions to this policy for service security or health reliability issues. When an API is marked as deprecated, we strongly recommend that you migrate to the latest version as soon as possible. In some cases, we'll announce that new applications will have to start using the new APIs a short time after the original APIs are deprecated. When customer calls deprecated API endpoint, the response will contain a header: ``` Deprecation: date="Fri, 11 Nov 2026 23:59:59 GMT" Box-API-Deprecated-Reason: https://developer.box.com/reference/deprecated ``` The date tells clients when this version was marked as deprecated. ## Versioning considerations When building your request, consider the following: - Endpoints in version `2024.0` can be called without specifying the version in the `box-version` header. If no version is specified and the `2024.0` version of the called endpoint does not exist, the response will return an HTTP error code `400 - Bad Request`. - If the `box-version` version header is specified but the requested version does not exist, the response will return an HTTP error code `400 - Bad Request`. For details, see [versioning errors](g://api-calls/permissions-and-errors/versioning-errors). When Box deprecates a resource or a property of a resource in the API, the change is communicated in one or more of the following ways: Calls that include the deprecated behavior return the response header `Box-API-Deprecated-Reason` and a link to get more information: ``` box-version: 2025.0 Deprecation: version="version", date="date" Box-API-Deprecated-Reason: https://developer.box.com/reference/deprecated ``` A deprecation announcement is posted in the developer changelog. The API reference is updated to identify the affected resource and any action you need to take. Affected endpoints are marked with **deprecated** pill. If there is an imminent backwards-incompatible change that affects your app, then the contact email for your app might be contacted about the deprecation. ## Additional resources - [API reference](page://reference) **Reference:** https://developer.box.com/guides/api-calls/api-versioning-strategy/ --- ## Untitled *Type: guide | Category: API Calls * Ensure consistency with headers Some Box APIs support headers used to ensure consistency between your application and Box. etag, if-match… # Ensure consistency with headers Some Box APIs support headers used to ensure consistency between your application and Box. ## etag, if-match, and if-none-match Many of the file system items (files or folders) that can be requested via the API return an `etag` value for the item. For example, a file resource returns an `etag` in the JSON response. ``` curl https://api.box.com/2.0/files/12345 \ -H "authorization: Bearer ACCESS_TOKEN" ``` ``` { "id": 12345, "etag": 1, "type": "file", "sequence_id": 3, "name": "Contract.pdf", ... } ``` This `etag` can be used as the value of a `if-match` or `if-none-match` header to either ensure a resource hasn't changed since the `etag` value was received, or to prevent unnecessary downloads for items that haven't changed. For example, to fetch the same file only if it has changed, pass in the `etag` value in a `if-none-match` header. ``` curl https://api.box.com/2.0/files/12345 \ -H "authorization: Bearer ACCESS_TOKEN" \ -H "if-none-match: 1" ``` This API call would result in an empty response if the file had not changed. ## Ensure consistent changes The `if-match` header allows your application to ensure that no changes are made to items when another application or a user has made changes to the item since your application last inspected it. This helps ensure that changes aren't lost when two applications or users are changing items at the same time. The following endpoints support this header. | if-match capable endpoints | | | --- | --- | | POST /files/:id/content | Upload a new file version | | PUT /files/:id | Update a file's information | | DELETE /files/:id | Delete a file | | PUT /folders/:id | Update a folder's information | | DELETE /folders/:id | Delete a folder | | PUT /web_links/:id | Update a web link's information | | DELETE /web_links/:id | Delete a web link | The response of these APIs calls depends on the existence of the item, and whether the `etag` value matches the most recent version. | Item found? | Etag match? | HTTP status | | --- | --- | --- | | Yes | Yes | 200 | | Yes | No | 412 | | No | Yes | 412 | | No | No | 404 | # Moving items The `if-match` header can not be used to prevent moving of files, folders, or web links. Instead, Box will always ensure that the latest item is moved to the new location. ## Prevent unnecessary request downloads The `if-none-match` header allows your application to ensure that no information is downloaded for items that have not changed since your application last inspected it. This helps ensure no unnecessary information is downloaded, speeding up your application and saving on bandwidth. | if-none-match capable endpoints | | | --- | --- | | GET /files/:id | Get a file's information | | GET /folders/:id | Get a folder's information | | GET /web_links/:id | Get a web link's information | | GET /shared_items | Get a shared item's information | The response of these APIs calls depends on the existence of the item, and whether the `etag` value matches the most recent version. | Item found? | Etag match? | HTTP Status | | --- | --- | --- | | Yes | Yes | 304 | | Yes | No | 200 | | No | Yes | 404 | | No | No | 404 | **Reference:** https://developer.box.com/guides/api-calls/ensure-consistency/ --- ## Untitled *Type: guide | Category: API Calls * API Calls The Box API is a restful API that follow common HTTP standards where possible. The following guides take a look at some of the… # API Calls The Box API is a restful API that follow common HTTP standards where possible. The following guides take a look at some of the useful features and common mistakes that a developer can encounter when working with these APIs. ## API calls insights Admins and co-admins can access the Platform Insights dashboard that provides information on the total number of API calls per application. See [Platform Insights](https://support.box.com/hc/en-us/articles/20738406915219-Platform-Insights) and [applications](g://applications) for details. **Reference:** https://developer.box.com/guides/api-calls/ --- ## Untitled *Type: guide | Category: API Calls * Language codes The Box API uses a modified version of the ISO 639-1 Language Code to specify a user's language. The following is a list of… # Language codes The Box API uses a modified version of the **ISO 639-1 Language Code** to specify a user's language. The following is a list of language codes used when [creating](e://post_users#param-language) or [updating](e://put_users_id#param-language). | Language | Code | | --- | --- | | Bengali | bn | | Danish | da | | German | de | | English (US) | en | | English (UK) | gb | | English (Canada) | e2 | | English (Australia) | e3 | | Spanish (Latin America) | s2 | | Spanish | es | | Finnish | fi | | French | fr | | French (Canada) | f2 | | Hindi | hi | | Italian | it | | Japanese | ja | | Korean | ko | | Norwegian (Bokmal) | nb | | Dutch | nl | | Polish | pl | | Portuguese | pt | | Russian | ru | | Swedish | sv | | Turkish | tr | | Chinese (Simplified) | zh | | Chinese (Traditional) | zt | **Reference:** https://developer.box.com/guides/api-calls/language-codes/ --- ## Untitled *Type: guide | Category: API Calls * Request extra fields The number of fields returned for a resource depends on the API endpoint used to request the resource. Use the fields… # Request extra fields The number of fields returned for a resource depends on the API endpoint used to request the resource. ## Use the fields query parameter To request a specific field for a resource that is not returned by default in the standard response, append the `fields` query parameter to your request. The value of this parameter is a comma separated list of field names. ``` curl https://api.box.com/2.0/files/12345?fields=is_package,lock \ -H "authorization: Bearer ACCESS_TOKEN" ``` ``` { "etag": "1", "id": "12345", "is_package": false, "lock": null, "type": "file" } ``` It is important to note that when a specific field is requested no other fields are returned except for those requested and the **base** set of fields. For a file, this base set is comprised of the `etag`, `id`, and `type` values. ## Resource variants The following resource variants are available in the Box API. ### Standard The default set of fields returned in an API response. The standard variant is returned when requesting a resource through the main APIs available for that resource. For example, when requesting the [`GET /files/:id`](endpoint://get_files_id) endpoint the API will return the standard variation of a file. ``` curl https://api.box.com/2.0/files/12345 \ -H "authorization: Bearer ACCESS_TOKEN" ``` ``` { "content_created_at": "2019-06-20T06:04:41-07:00", "content_modified_at": "2019-06-20T06:04:41-07:00", "created_at": "2019-06-20T07:28:42-07:00", "created_by": { "id": "191919191", "login": "joe@example.com", "name": "Joe Box", "type": "user" }, "description": "", "etag": "1", "file_version": { "id": "56663434454334", "sha1": "585afa5209bbd586c79499b7336601341ad06cce", "type": "file_version" }, "id": "12345", ... "size": 65000647, "trashed_at": null, "type": "file" } ``` ### Mini Where a resource is returned as a nested part of another response it is often reduced in size, only returning some of the more essential fields. This variant is commonly known as the mini resource variant. For example, when requesting the [`GET /folders/:id/items`](endpoint://get_folders_id_items) endpoint the API will return a mini variation of files and folders nested within the `item_collection`. ``` curl https://api.box.com/2.0/files/12345 \ -H "authorization: Bearer ACCESS_TOKEN" ``` ``` { "id": "0", "type": "folder", "item_collection": { "entries": [ { "etag": "1", "file_version": { "id": "56663434454334", "sha1": "585afa5209bbd586c79499b7336601341ad06cce", "type": "file_version" }, "id": "12345", "name": "Video.mp4", "sequence_id": "1", "sha1": "585afa5209bbd586c79499b7336601341ad06cce", "type": "file" } ... ] ... } ... } ``` To request more information for a nested resource we recommend calling the API for that resource to request it by ID, and optionally pass along the `field` query parameter. For example, to get the owner of a file returned when listing the items in a folder, request that file by ID with the query parameter `field=owned_by`. ### Full The total set of fields that can be returned in an API response. The full variant is returned when requesting a resource through the main APIs available for that resource and by appending the `fields` query parameter. For example, when requesting the [`GET /files/:id`](endpoint://get_files_id) endpoint with the `fields=is_package,lock` parameter the API will return the fields specified plus the basic fields for the file. ``` curl https://api.box.com/2.0/files/12345?fields=is_package,lock \ -H "authorization: Bearer ACCESS_TOKEN" ``` ``` { "etag": "1", "id": "12345", "is_package": false, "lock": null, "type": "file" } ``` **Reference:** https://developer.box.com/guides/api-calls/request-extra-fields/ --- ## Untitled *Type: guide | Category: API Calls * Sorting responses Where an API returns a collection of items it often supports sorting of API responses. Use the sort and direction query… # Sorting responses Where an API returns a collection of items it often supports sorting of API responses. Use the `sort` and `direction` query parameters to sort the collection either in ascending or descending order. ``` curl https://api.box.com/2.0/folders/0/items?sort=size&direction=DESC \ -H "authorization: Bearer ACCESS_TOKEN" ``` Not all API endpoints that return collections have support for sorting. Especially endpoints that use marker-based pagination often lack support for sorting the results. ## Sorting criteria The field to sort on is defined by the `sort` query parameter. Check the API endpoint's documentation for the possible options for this value. In some APIs the `sort` field is the second criteria by which the items are sorted. For example for the [`GET /folders/:id/items`](endpoint://get_folders_id_items) endpoint the results are always sorted by their type first before any other criteria. ## Sorting direction The sorting direction supports two values, either `ASC` for ascending order, or `DESC` for the reverse. **Reference:** https://developer.box.com/guides/api-calls/sorting/ --- ## Untitled *Type: guide | Category: API Calls * Suppress notifications For some API calls, you can block email and webhook notifications by including a box-notifications: off header with… # Suppress notifications For some API calls, you can block email and webhook notifications by including a `box-notifications: off` header with the API call. ``` curl -X POST https://api.box.com/2.0/folders \ -H "box-notifications: off" \ -H "authorization: Bearer ACCESS_TOKEN" \ -d '{ "name": "New Folder", "parent": { "id": "0" } }' ``` As an example, this can be used for a virus-scanning tool to download copies every user's files in an enterprise without every collaborator on the file receiving an email informing them of the download. All actions will still appear in users updates feed and the audit-logs. # Scope requirement Notification suppression is available for approved applications only. Contact support to request the required scopes to be enabled for your application. The following settings need to be configured for your application for this feature to properly work. - **Can suppress email notifications from API calls** - available on request via support - **Manage Enterprise Properties** - available via the developer console - Co-admin permissions of **Edit settings for your company**. Some notifications can not be suppressed, most notable the creation is users, comments, collaborations, task assignments, and when changing a user's login. **Reference:** https://developer.box.com/guides/api-calls/suppress-notifications/ --- ## Untitled *Type: guide | Category: API Calls * Status codes The following rules can be applied to interpret the HTTP status codes received when using the Box API. HTTP Status 200-299 Box… # Status codes The following rules can be applied to interpret the HTTP status codes received when using the Box API. | HTTP Status | | | --- | --- | | 200-299 | Box received, understood, and accepted the API request. The request has either completed or is in the process of being completed. | | 300-399 | Box received, understood, and accepted the API request, yet the client must take further action in order to complete the request. Often this includes redirect to other URLs. | | 400-499 | An client error occurred when handling the request, often because the client either did not provide the right parameters, did not have access to the resources, or tried to perform an action that is otherwise not possible. | | 500-599 | Box received and accepted the request, but an error occurred within Box while handling it. These errors signify a problem with Box, not a problem with the client's request | **Reference:** https://developer.box.com/guides/api-calls/status-codes/ --- ## Untitled *Type: guide | Category: API Calls * Types and formats The following sections explain some basic concepts about the types and formats that can be encountered within the Box APIs… # Types and formats The following sections explain some basic concepts about the types and formats that can be encountered within the Box APIs. ## Requests The Box APIs use JSON in the requests bodies. There are a few notable exceptions to this rule: - The [`POST /oauth2/token`](endpoint://post-oauth2-token) is used to request access tokens and as per the OAuth 2.0 specification it accepts the body to be sent with a content type of `application/x-www-form-urlencoded`. - Most of the APIs that are used to upload binary data, like the [`POST /files/content`](endpoint://post-files-content) endpoint, expect data to be sent as form data with a content type of `multipart/form-data`. Although not required, we highly recommend passing a header with each API request to define the content type of the data sent, for example `content-type: application/json`. ### Headers As per the HTTP specification, all request header names in the Box API are case-insensitive and can be provided in lowercase, uppercase, or any mixed case form. In other words, the content type header can be set as `CONTENT-TYPE: application/json`, `content-type: application/json`, `content-type: application/json` or even the slightly absurd `cOnTeNt-TyPe: application/json`. Header values **are** mostly case sensitive unless stated otherwise. ### GZip compression By default data sent from Box is not compressed. To improve bandwidth and response times it's possible to compress the API responses by including a `Accept-Encoding: gzip, deflate` request header. ### Date and times The Box APIs support [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) timestamps. The preferred way to format a date in a request is to convert the time to UTC, for example `2013-04-17T09:12:36-00:00`. In those cases where timestamps are rounded to a given day, the time component can be omitted. In this case, `2013-04-17T13:35:01+00:00` would become `2013-04-17`. In those cases where timestamps support millisecond precision the expected request format should be as followed `2013-04-17T09:12:36.123-00:00`. The timezone can differ between different files and folders because an enterprise's timezone can change over time. A common example is daylight saving time. Items created during standard time would have a different timezone than items created during daylight saving time. For this reason it's important to use a `RFC3339`-compliant date-time parser to handle dates returned by the API. Timestamps are restricted to dates after the start of the Unix epoch, `00:00:00 UTC` on January 1, 1970. ## Responses The Box APIs generally returns JSON in the response body. There are a few notable exceptions to this rule as well. - APIs that delete items return an empty body with a `204 No Content` HTTP status code. - APIs used to request binary data either return a `200 OK` status code with the binary data attached, or a `202 Accepted`, or `302 Found` status code with no body and a `location` header pointing to the actual binary file. The `content-type` response header can be used to understand the type of content returned in the API. Additionally, every API endpoint has it's response type documented in our API reference documentation. ### Headers As per the HTTP specification, all response header names in the Box API are case-insensitive and could change over time. This means that the API might return responses with a content type header of `CONTENT-TYPE: application/json`, `content-type: application/json` or `content-type: application/json`. Ideally your application should convert header names to a standard case upon request and then use that standardized set of headers to look up values of the headers. Header values **are** always case sensitive unless stated otherwise. ### Resources Most standard API responses where only one resource is returned follow the following format. ``` { "id": "12345", "type": "folder", ... } ``` Every one of these resources will always return an ID and the type of the resource. ### Collections Where an API response returns multiple items a collection is returned. Although the exact format of these collections can change from endpoint to endpoint they generally are formatted as follows. ``` { "total_count": 5000, "limit": 1000, "offset": 2000, "order": [ { "by": "type", "direction": "ASC" } ], "entries": [ { "id": 12345, "etag": 1, "type": "file", "sequence_id": 3, "name": "Contract.pdf" } ] } ``` | Field | Always present? | | | --- | --- | --- | | entries | Yes | A list of entries in the collection | | total_count | No | The total numbers in the collection that can be requested. This can be larger than this page of results | | limit | No | For endpoints that support offset-based pagination, this specifies the limit to the number of results returned | | offset | No | For endpoints that support offset-based pagination, this specifies the offset of results returned | | order | No | For endpoints that support sorting, this specifies the order the results are returned in | | next_marker | No | For endpoints that support marker-based pagination, this specifies the marker for the next page that can be returned | | prev_marker | No | For endpoints that support marker-based pagination, this specifies the marker for the previous page that can be returned | ### Request IDs When your API call returns in an error, our API will return an error object with a `request_id` field. ``` { "type": "error", "status": 400, "code": "item_name_invalid", "help_url": "https://developer.box.com/guides/api-calls/permissions-and-errors/common-errors/", "message": "Method Not Allowed", "request_id": "abcdef123456" } ``` When reaching out to support about specific error, please provide the full API response including the `request_id` to help our support team to quickly find your request. Most API calls also return a `box-request-id` response header. The value of this header should not be confused with the `request_id` value in the body of an error response. ### Large numbers In some cases the API can return extremely large numbers for a field. For example, a folder's size might have grown to many terabytes of data and as a result the `size` field of the folder might have grown to a very large number. In these cases these numbers are returned in [IEEE754](https://en.wikipedia.org/wiki/IEEE_754) format for example `1.2318237429383e+31`. **Reference:** https://developer.box.com/guides/api-calls/types-and-formats/ --- ## Untitled *Type: guide | Category: Applications * Applications Box Developer Console allows you to create applications you can then use to integrate with Box. My Platform Apps view displays… # Applications Box Developer Console allows you to create applications you can then use to integrate with Box. **My Platform Apps** view displays a list of already created applications and gives you quick access to their configuration details. This way, you don't need to open the app each time you want to generate a Developer Token, copy the Client ID, or generate a report. ## Features **My Platform Apps** page allows you to: - Search through the list of already created apps. - Filter the apps by **Enablement Status** and **Authentication Type**. - Create [a new app](g://applications/app-types/select). - Copy the app's [Client ID](g://authentication/client-credentials). - Rename the app and access its details with one click. - Check application [enablement](g://authorization/custom-app-approval#user-authentication-apps) and [authorization](g://authorization) status. Apps published to Integrations display status from Integrations. The **Options menu** available for every entry allows you to: - Access the configuration details of your application. - Generate a [Developer Token](g://authentication/tokens/developer-tokens). - Add collaborators to your application. - Run the [Platform App Diagnostics Report](g://api-calls/permissions-and-errors/app-diagnostics-report). ## Platform App Insights Admins and co-admins can access the Platform Insights dashboard that provides a comprehensive view of the organization’s platform usage. This includes app-related data, such as: - The total number of API calls per application. - A list of top applications within the enterprise. - A list of pending application approvals. - A list of applications awaiting enablement. See [Platform Insights](https://support.box.com/hc/en-us/articles20738406915219-Platform-Insights) for details. You need the following permissions to access and view Platform Insights: - View settings and apps for your company - Edit settings and apps for your company - Run new reports and access existing reports **Reference:** https://developer.box.com/guides/applications/ --- ## Untitled *Type: guide | Category: Box Archive * Add content to Box Archive To add content to an archive, you need to create it first. If you have not done this yet, use the Create Archive… # Add content to Box Archive To add content to an archive, you need to create it first. If you have not done this yet, use the [Create Archive](https://developer.box.com/reference/v2025.0/post-archives/) endpoint. ## Add file or folder to archive Use the [`PUT /files/:id`](e://put-files-id) API endpoint to add a file to an archive, or the [`PUT /folders/:id`](e://put-folders-id) endpoint to add a folder. The `id` parameter is the ID of the file/folder you want to add to the archive. To specify the destination, use the `parent.id` [parameter](https://developer.box.com/reference/put-folders-id/#param-parent-id) in the request body. This can be either an ID of an archive or the ID of a folder that is inside an archive. **Reference:** https://developer.box.com/guides/archives/add-content/ --- ## Untitled *Type: guide | Category: Box Archive * Box Archive Box Archive is available only for Enterprise Advanced accounts. Box Archive allows you to create and manage archives. An archive… # Box Archive Box Archive is available only for Enterprise Advanced accounts. Box Archive allows you to create and manage archives. An archive is a folder dedicated to storing content that is redundant, outdated, or trivial. Content in an archive is owned by the enterprise, and it is not accessible to previous owner and collaborators. ## Archives are folders Archives are a special type of folders. Box Archive APIs allow you to create, list and delete archives. However, there are other APIs that also work with archives or with content within archives. For a full list of supported APIs, see the [Supported APIs](g://archives/supported-apis) guide. ## Required scopes Before using any of the Box Archive APIs, make sure you can access [Box Archive in Admin Console](https://support.box.com/hc/en-us/p/Product_Page_2023?section-id=40168863437843). Your Box Platform app must have the `GCM` and `Read and write all files and folders` [scopes](https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/) enabled. If you plan to only view archives and not modify them, use the `Read all files and folders` instead of the `Read and write all files and folders` scope. The `GCM` scope is not available in the Developer Console and needs to be enabled by contacting customer support. **Reference:** https://developer.box.com/guides/archives/ --- ## Untitled *Type: guide | Category: Box Archive * Restore content from Box Archive This guide describes how to restore content that you archived by mistake. Restore file or folder from… # Restore content from Box Archive This guide describes how to restore content that you archived by mistake. ## Restore file or folder from archive Use the [`PUT /files/:id`](e://put-files-id) API endpoint to restore a file from an archive, or the [`PUT /folders/:id`](e://put-folders-id) endpoint to restore a folder from an archive. The `id` parameter is the ID of the file/folder you want to restore from an archive. To specify the destination, use the `parent.id` [parameter](https://developer.box.com/reference/put-folders-id/#param-parent-id) in the request body. This is the ID of a folder (can be owned by any user) where you want to restore the file/folder. To restore a file/folder to user's root folder, use `0` as the `parent.id` value. Additionally, pass the ID of the user in the `parent.user_id` [parameter](https://developer.box.com/reference/put-folders-id/#param-parent-user_id) in the request body. **Reference:** https://developer.box.com/guides/archives/restore-content/ --- ## Untitled *Type: guide | Category: Box Archive * Supported APIs for Box Archive The basic Box Archive APIs allow you to create, list and delete archives, but you can use other APIs to… # Supported APIs for Box Archive The basic Box Archive APIs allow you to create, list and delete archives, but you can use other APIs to interact with an archive or its content. See the table below for the full list of those APIs. Those APIs require the [`GCM` scope](https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/#global-content-manager-gcm) to be enabled in your application. This scope is not available in the Developer Console and needs to be enabled by contacting customer support. Additionally, some of the below APIs need to be enabled by contacting customer support to properly work with Box Archive. When contacting customer support, specify the user ID you plan to use those APIs with. | API Endpoint | Description | | --- | --- | | POST /archives | Create an archive. | | GET /archives | List all archives. | | DELETE /archives/:id | Delete an archive. | | PUT /files/:id | Add a file to an archive, restore a file from an archive, or move file within/between archives. Other updates to the file are not allowed. Requires contacting customer support to enable. | | PUT /folders/:id | Add a folder to an archive, restore a folder from an archive, or move folder within/between archives. Other updates to the folder are not allowed. Requires contacting customer support to enable. | | POST /files/content | Upload a file to an archive or to folder within archive. Requires contacting customer support to enable. | | GET /files/:id/content | Download a file from an archive or from folder within archive. | | POST /zip_downloads | Download a zip file of an archive or of a folder within archive. | | POST /folders | Create a folder within an archive. Requires contacting customer support to enable. | | GET /files/:id | Get details of a file within an archive. | | GET /folders/:id | Get details of archive or a folder within an archive. | | GET /folders/:id/items | List items within an archive or a folder within an archive. | | POST /files/:id/copy | Copy a file within an archive or to another archive. | | POST /folders/:id/copy | Copy a folder within an archive or to another archive. | | POST /files/:id/metadata/:scope/:template_key | Create metadata instance on a file within an archive. | | GET /files/:id/metadata/:scope/:template_key | View metadata instance on a file within an archive. | | GET /files/:id/metadata | List all metadata instances on a file within an archive. | | PUT /files/:id/metadata/:scope/:template_key | Update metadata instance on a file within an archive. | | DELETE /files/:id/metadata/:scope/:template_key | Delete metadata instance on a file within an archive. | | POST securityClassification | Create a classification label on a file within an archive. | | GET securityClassification | View a classification label on a file within an archive. | | PUT securityClassification | Update a classification label on a file within an archive. | | DELETE securityClassification | Delete a classification label on a file within an archive. | **Reference:** https://developer.box.com/guides/archives/supported-apis/ --- ## Untitled *Type: guide | Category: Authentication * Best Practices Client secret security Your client secret is confidential and needs to be protected. Because this is how we securely identify… # Best Practices ## Client secret security Your client secret is confidential and needs to be protected. Because this is how we securely identify an application's identity when obtaining an Access Token, you do not want to freely distribute a client secret. This includes via email, public forums and code repositories, distributed native applications, or client-side code. ## Cache tokens Because fetching new tokens is expensive, we recommend using a token cache to prevent unnecessary requests. After retrieving a token, store it in an in-memory cache, like Memcached, or a built-in ASP.NET cache service. By default, Access Tokens are valid for 60 minutes, but we recommend setting the expiration time to around 50 minutes to allow for a buffer. When you need a token, first check the cache for a valid token. If the token expired, get a new one and store it in the cache for 50 minutes. ``` def self.user_client(user_id) access_token=Rails.cache.fetch("box_tokens/user/#{user_id}", :expires_in => 50.minutes) do puts "getting new user token" response= Boxr::get_user_token(user_id, private_key: PRIVATE_KEY, private_key_password: ENV['JWT_PRIVATE_KEY_PASSWORD']) response.access_token end Boxr::Client.new(access_token) end ``` Official Box SDKs use token caching. ## Expired tokens Expired tokens return a 401: Unauthorized error. This error should be handled to refresh the token. ## Downscope tokens It is important to follow the principle of least privilege when thinking about Access Tokens. This can be accomplished through [downscoping](g://authentication/tokens/downscope), where a fully scoped Access Token is exchanged for a more restricted Access Token that can then be deployed to client-side code, mobile environments, or UI tools. ``` //Define resource/scopes that downscoped token has access to String resource = "https://api.box.com/2.0/files/RESOURCE_ID"; List<String> scopes = new ArrayList<String>(); scopes.add("base_preview"); scopes.add("item_download"); //Preform token exchange ScopedToken downscopedToken = client.getLowerScopedToken(scopes,resource); //Downscoped token available in downscopedToken.getAccessToken() ``` ## Revoke tokens Both fully scoped Access Tokens and Downscoped Tokens can be [revoked](g://authentication/tokens/revoke). This allows you to manage the lifespan of a token to reduce exposure when a user logs out , there is suspicious activity, or when you need to push new security enhancements. ## Developer Tokens Developer Tokens should only be used for development or testing purposes and never in production. **Reference:** https://developer.box.com/guides/authentication/best-practices/ --- ## Untitled *Type: guide | Category: Authentication * Authentication Authentication with the Box API uses an Access Token to identify a user. The way in which an Access Token is acquired depends… # Authentication Authentication with the Box API uses an Access Token to identify a user. The way in which an Access Token is acquired depends on the method used to authorize a user. The type of authorization available to an application depends on the use-case as well as the type of application that has been created in the developer console. | Box Application Type | Authentication methods | | --- | --- | | Platform App | OAuth 2.0, JWT, or Client Credentials Grant | | Limited Access App | App token | | Custom Skill | No authentication method selection needed | Learn how to select an authorization type ## Access Tokens for Authentication Every API endpoint requires a valid and active **Access Token** to make API calls. An Access Token is a unique string that identifies an authenticated Box user to the API endpoints. ``` curl https://api.box.com/2.0/users/me \ -H "authorization: Bearer EGmDmRVfhfHsqesn5yVYHAqUkD0dyDfk" ``` Learn more about Access Tokens **Reference:** https://developer.box.com/guides/authentication/ --- ## Untitled *Type: guide | Category: Authentication * Select Auth Method The type of authorization your application can use depends on the type of Box Application that you've configured in the… # Select Auth Method The type of authorization your application can use depends on the type of Box Application that you've configured in the developer console. Learn how to select the application type for your app The following authorization methods are available to each Box application type. | Box Application Type | Supports OAuth 2.0? | JWT? | Client Credentials? | App Token? | | --- | --- | --- | --- | --- | | Platform App | Yes | Yes | Yes | No | | Limited Access App | No | No | No | Yes | | Custom Skill | No | No | No | No | ## Client-side ### OAuth 2.0 OAuth 2.0 requires the application to redirect end-users to their browser to login to Box and authorize the application to take actions on their behalf. # When to use OAuth 2.0? Client-side authentication is the ideal authentication method for apps that: - work with users who have existing Box accounts - use Box for identity management, so users know they are using Box - store data within each user account vs. within an application's Service Account Learn about client-side authentication with OAuth 2.0 ## Server-side ### JWT Server-side authentication using JSON Web Tokens (JWT) does not require end-user interaction and, if granted the proper privileges, can be used to act on behalf of any user in an enterprise. Identity is validated using a JWT assertion and public/private keypair. # When to use JWT? Server-side authentication with JWT is the ideal authentication method for apps that: - work with users without Box accounts - use their own identity system - do not want users to know they are using Box - store data within the application's Service Account and not a user's account Learn about server-side authentication with JWT ### Client Credentials Grant Server-side authentication using Client Credentials Grant does not require end-user interaction and, if granted the proper privileges, can be used to act on behalf of any user in an enterprise. Identity is validated using the application's client ID and client secret. # When to use a Client Credentials Grant? Server-side authentication with Client Credentials Grant is the ideal authentication method for apps that: - work with users without Box accounts - use their own identity management system - do not want users to know they are using Box - store data within the application's Service Account and not a user's account Learn about server-side authentication with Client Credentials Grant ### App Token A server-side App Token is an authentication method where the application only has access to read and write data to its own account. This is mainly used by Box View applications. By using this authentication method there is no need to authorize a user as the application is automatically authenticated as the application's Service Account. # When to use App Tokens? Server-side authentication with App Tokens is the ideal authentication method for apps that: - work in an environment that either has no user model, or has users without Box accounts - use their own identity management system - do not want users to know they are using Box - store data within the application's Service Account and not a user's account Learn about server-side authentication with App Tokens ## Comparison The following is a quick overview of the key difference between client-side and server-side authentication. | | OAuth 2.0 | JWT | Client Credentials | App Tokens | | --- | --- | --- | --- | --- | | Requires user involvement? | Yes | No | No | No | | Requires admin approval? | No | Yes | Yes | Yes | | Can act on behalf of other users? | Yes | Yes | Yes | No | | Do users see Box? | Yes | No | No | No | | Can create App Users? | No | Yes | Yes | No | An Access Token is tied to a specific Box user and the way the token has been obtained determines who that user is. For example, when using client-side authentication the token represents the user who granted access to their account, while while when using server-side authentication the token defaults to the application's Service Account. **Reference:** https://developer.box.com/guides/authentication/select/ --- ## Untitled *Type: guide | Category: Authentication * Box API & SSO Many Box Enterprises use Single Sign On (SSO) to authenticate Managed Users logging in to Box. The way an application built on… # Box API & SSO Many Box Enterprises use **Single Sign On** (SSO) to authenticate [Managed Users](page://platform/user-types/#managed-users) logging in to Box. The way an application built on Box Platform interact with an SSO provider depends on the type of application being built. ## Platform Apps with Client-side Authentication When users authenticate with a [Platform App](g://applications/app-types/platform-apps) configured to use [OAuth 2.0](g://authentication/oauth2) Box will detect if the enterprise is configured to use SSO. If it is, Box will redirect the user to their browser and display the enterprise's configured SSO log-in screen. ### SSO Enabled vs Required Enterprises can configure their SSO in one of two ways: **SSO Required** or **SSO Enabled**. When SSO is enabled but not required, managed users will have the option to either: - log in with a Box username and password - log in with their SSO provider When SSO is enabled and required, Box will force all managed users to log in with their enterprise's configured SSO provider. In this case, any user that tries to log in must be configured on the SSO side, in addition to having a Box account matching the email address passed via SAML. It is not possible to exempt a user from SSO in an enterprise with SSO set to required, even if it is only used for platform use cases. ## Platform Apps with Server-side Authentication For [Platform Apps](g://applications/app-types/platform-apps) that use [JWT](g://authentication/jwt) or [Client Credentials Grant](g:///authentication/client-credentials) and [Limited Access Apps](guide://applications/web-app-integrations) that use [App Token](g://authentication/app-token) authentication, SSO is not used to authenticate with Box. Platform Apps using server-side authentication only use server-to-server API calls to communicate with Box. In this scenario, the way in which an end user is authenticated is determined by the application and not by Box. In other words, end user authentication with the application is determined by the application, while application's authorization to Box is a different matter completely. In these use cases the application authenticates not as a regular Managed User but as a Service Account or App User. These user types do not have access to any Managed User's data by default. For these applications to have access to other Managed User's data they will need explicit [admin approval](g://authorization/custom-app-approval). ## Custom Skills [Custom Skills](g://applications/app-types/custom-skills) are authenticated in a unique way where the application is provided with a unique set of access tokens for every skill event. In this case, the application does not directly interact with the users and therefore SSO is not involved. Even when using Skills, a user uploading a file to a folder that might trigger a Skill event would still need to log in to the web or mobile app. This log in would require them to use SSO where needed. **Reference:** https://developer.box.com/guides/authentication/sso/ --- ## Untitled *Type: guide | Category: Authorization * Platform App Approval Server authentication applications using JWT or Client Credentials Grant must be authorized by a Box Admin before use… # Platform App Approval Server authentication applications using [JWT](g://authentication/jwt) or [Client Credentials Grant](g://authentication/client-credentials) must be authorized by a Box Admin before use. Unpublished applications using [OAuth 2.0](g://authentication/oauth2) authentication may require enablement by a Box Admin if they are [inactive by default](g://security/#enterprise-settings-and-authorization). A Box Admin needs an application's Client ID in order to properly authorize or enable it in the Admin Console. You can use [Integrations](g://applications) view to quickly look up the authorization and enablement status of your application. ## Approval Notifications A semi-automated process to submit an app approval is available in the Developer Console for all platform application types. ### Server authentication apps Navigate to the **Authorization** tab for your application in the [Developer Console](https://app.box.com/developers/console). ### User authentication apps Navigate to the **Enablement** tab for your application in the [Developer Console](https://app.box.com/developers/console). Submitting the application for approval will send an email to your enterprise's Primary Admin to approve the application. When a Box Admin approves or declines your request, you will get an email with the decision. More information on this process is available in our [support article on app authorization](https://support.box.com/hc/en-us/articles/360043697014-Authorizing-Apps-in-the-Box-App-Approval-Process). ## Manual Approval The following steps provide instructions on how to manually approve the application. ### As a developer 1. Navigate to the **Configuration** tab for your application in the [Developer Console](https://app.box.com/developers/console). 2. Scroll down to the OAuth 2.0 Credentials section and copy the **Client ID** value to provide to a Box Admin. Alternatively, hover over the application in the [My Platform Apps](g://applications) view to look up the **ClientID** and then copy it using the `copy` button. # Finding a Box Admin If you don't know your enterprise Admin, go to your Box Account Settings page and scroll to the bottom. If an admin contact is set you should see their contact information under **Admin Contact**. ### As an Admin 1. Navigate to the [Admin Console](https://app.box.com/master/settings/custom) and select the **Integrations** tab (1) from the left navigation panel. 2. Click the **Platform Apps Manager** tab (2) at the top of your screen. 3. For both Server and User Authentication Apps screens, click the **Add Platform App** (3) button in the top right corner to add a new app. 4. Alternatively, you can use the Platform Apps Manager table menu (4) to authorize and enable apps. #### Server Authentication Apps #### User Authentication Apps In the popup that appears, enter the client ID for the application that the developer collected from the **Configuration** tab of the [Developer Console](https://app.box.com/developers/console). ## Re-authorization on changes When the application's scopes or access level change the application needs to be re-authorized. Repeat the process above and request a new Access Token for the new changes to take effect. In the same section where the application was initially authorized, an Admin can re-authorize the application by clicking on the ellipses to the right of the application name to **Reauthorize App**. **Reference:** https://developer.box.com/guides/authorization/custom-app-approval/ --- ## Untitled *Type: guide | Category: Authorization * Common Errors Unable to retrieve service of enterprise app authorization This error indicates that the entered client ID entered is invalid… # Common Errors ## Unable to retrieve service of enterprise app authorization This error indicates that the entered client ID entered is invalid. To resolve this issue, please re-copy the Client ID from the Developer Console and ensure you are not including any trailing characters. ## Something went wrong with adding the app authorization This error indicates you are a Box co-admin granted privileges to view, but not edit enterprise settings. You will need to have your Box Admin grant edit privileges in order to successfully authorize an application. ## Disabled by Administrator This error indicates that not all authorization requirements are satisfied. Please review our [authorization guide](g://authorization) to confirm the necessary steps for a given application. **Reference:** https://developer.box.com/guides/authorization/common-errors/ --- ## Untitled *Type: guide | Category: Authorization * Custom Skill Approval Custom Skills will must be enabled on a folder by the enterprise's Box Admin before use. As a developer As the… # Custom Skill Approval Custom Skills will must be enabled on a folder by the enterprise's Box Admin before use. ## As a developer As the developer, navigate to the application in the [Developer Console](https://app.box.com/developers/console) and copy the application's Client ID to provide to your admin. # Finding a Box Admin If you don't know your enterprise Admin, go to the Box [account settings][settings] page and scroll to the bottom. If an Admin contact is set you should see contact information under "Admin Contact". ## As an Admin To enable a Custom Skill application, navigate to the [Skills section of the Box Admin Console](https://app.box.com/master/skills) and click the "Add Skill" link to add a new skill. Enter the Client ID (API key) for the Custom Skill application. This is the Client ID provided by the developer. Click "Next" and select the folder(s) where the Box Skill application should operate. There are two options here: - **All content in your company** authorizes the Skill at the root folder of every user. This results in every file uploaded to any folder being processed by the Box Skill application. - **Select a list of folders** enables the application to a specific folder or set of folders on which the Skill application operates. Click "Enable Skill" and accept the terms and agreements. The Custom Skill is now enabled. Any new content added to the selected folder(s) will now trigger an event to be sent to the Invocation URL configured in the Box [Developer Console](https://app.box.com/developers/console). # 10 Skill applications per enterprise There is a limit of 10 enabled Skills per enterprise at any given time. Please contact your Box Sales Representative to enable more skills in an enterprise. **Reference:** https://developer.box.com/guides/authorization/custom-skill-approval/ --- ## Untitled *Type: guide | Category: Authorization * Authorization Some applications require explicit Admin authorization before use with an enterprise. The steps an Admin needs to take are… # Authorization Some applications require explicit Admin authorization before use with an enterprise. The steps an Admin needs to take are dependent on the developer-selected authentication method and enabled enterprise settings. ## Authentication methods The following [authentication methods](g://authentication/select) always require explicit Admin authorization: - [Server Authentication (with JWT)](g://authentication/jwt) - [Server Authentication (with Client Credentials Grant)](g://authentication/client-credentials) - [Custom Skill](g://applications/app-types/custom-skills) These authentication methods automatically generate a [Service Account](page://platform/user-types/#service-account). With the right [scopes](g://api-calls/permissions-and-errors/scopes) enabled, a Service Account can perform many Admin actions, thus requiring Admin authorization before use. [OAuth 2.0](g://authentication/oauth2) and [App Token](g://authentication/app-token) apps may also require explicit Admin authorization based on enabled enterprise settings. ## Enterprise settings Subsequent steps are required if any of the following enterprise settings are enabled: - Disable published third party apps by default - Disable unpublished apps by default - Require manual Admin authorization for Limited Access Apps These [settings](https://support.box.com/hc/en-us/articles/360044196653-Managing-custom-apps) can be found by navigating to: **Admin Console** > **Integrations** > **Platform Apps Manager** > **Platform Apps Settings** button. Published Platform Apps are any applications that can be found under Integrations. ## Required actions To see what steps an Admin must complete for a given app, review the following scenarios. **Disable published third party apps by default**: | Authentication Method | Enabled | Disabled | | --- | --- | --- | | OAuth 2.0 | Set to available in individual app controls | Ready for use | | Server Authentication (with JWT) | N/A | N/A | | Server Authentication (client credentials) | N/A | N/A | | App Token Authentication | N/A | N/A | **Disable unpublished apps by default**: | Authentication Method | Enabled | Disabled | | --- | --- | --- | | OAuth 2.0 | Enable in Integrations > Platform Apps Manager > User Authentication Apps > Select Platform App > Use More menu to enable the app. | Ready for use | | Server Authentication (with JWT) | Authorize and enable in Integrations > Platform Apps Manager > Server Authentication Apps Select Platform App > Use More menu to authorize the app. | Authorize in Integrations > Platform Apps Manager > Server Authentication Apps > Select Platform App > Use More menu to authorize the app. | | Server Authentication (client credentials) | Authorize and enable in Integrations > Platform Apps Manager > Server Authentication Apps > Select Platform App > Use More menu to authorize the app. | Authorize in Integrations > Platform Apps Manager > Server Authentication Apps > Select Platform App > Use More menu to enable the app. | | App Token Authentication | Authorize and enable in Integrations > Platform Apps Manager > Server Authentication Apps > Server Authentication Apps > Select Platform App > Use More menu to enable the app. | Ready for use | **Require manual Admin authorization for Limited Access Apps**: | Authentication Method | Enabled | Disabled | | --- | --- | --- | | OAuth 2.0 | N/A | N/A | | Server Authentication (with JWT) | N/A | N/A | | Server Authentication (client credentials) | N/A | N/A | | App Token Authentication | Authorize in Integrations > Platform Apps Manager > Server Authentication Apps Select Platform App > Use More menu to authorize the app. | Automatically authorized and enabled upon creation | **Reference:** https://developer.box.com/guides/authorization/ --- ## Untitled *Type: guide | Category: Authorization * Limited Access App Approval Limited Access Integrations are automatically authorized for use in an enterprise upon creation. However, if the… # Limited Access App Approval Limited Access Integrations are automatically authorized for use in an enterprise upon creation. However, if the enterprise setting to **Require manual Admin authorization for Limited Access Apps** is enabled, an Admin must preform additional steps. ## Approval Notifications A semi-automated process to submit an app approval is available in the Developer Console. Navigate to the **Authorization** tab for your application in the [Developer Console](https://app.box.com/developers/console). Submitting the application for approval will send an email to your enterprise's Primary Admin to approve the application. More information on this process is available in our [support article on app authorization](https://support.box.com/hc/en-us/articles/360043697014-Authorizing-Apps-in-the-Box-App-Approval-Process). ## Manual Approval The following steps provide instructions on how to manually approve the application. ### As a developer 1. Navigate to the **Configuration** tab for your application in the [Developer Console](https://app.box.com/developers/console). 2. Scroll down to the OAuth 2.0 Credentials section and copy the **Client ID** value to provide to a Box Admin. Alternatively, hover over the application in the [My Platform Apps](g://applications) view to look up the **ClientID** and then copy it using the `copy` button. # Finding a Box Admin If you don't know your enterprise Admin, go to your Box Account Settings page and scroll to the bottom. If an admin contact is set you should see their contact information under **Admin Contact**. ### As an Admin As a Box Admin, navigate to the [Admin Console](https://app.box.com/master/settings/custom) and select the **Integrations** > **Platform Apps Manager** > **Add Platform App** In the popup that appears, enter the Client ID for the application that the developer collected from the **Configuration** tab of the Developer Console. ## Re-authorization on changes When the application's scopes or access level change the application needs to be re-authorized. Repeat the process above and request a new Access Token for the new changes to take effect. In the same section where the application was initially authorized, an Admin can re-authorize the application by clicking on the ellipses to the right of the application name to **Reauthorize App**. **Reference:** https://developer.box.com/guides/authorization/limited-access-approval/ --- ## Untitled *Type: guide | Category: Authorization * Platform App Approval Server authentication applications using JWT or Client Credentials Grant must be authorized by a Box Admin before use… # Platform App Approval Server authentication applications using [JWT](g://authentication/jwt) or [Client Credentials Grant](g://authentication/client-credentials) must be authorized by a Box Admin before use. Unpublished applications using [OAuth 2.0](g://authentication/oauth2) authentication may require enablement by a Box Admin if they are [inactive by default](g://security/#enterprise-settings-and-authorization). A Box Admin needs an application's Client ID in order to properly authorize or enable it in the Admin Console. You can use [My Platform Apps](g://applications) view to quickly look up the authorization and enablement status of your application. ## Approval Notifications A semi-automated process to submit an app approval is available in the Developer Console for all platform application types. ### Server authentication apps Navigate to the **Authorization** tab for your application in the [Developer Console](https://app.box.com/developers/console). ### User authentication apps Navigate to the **Enablement** tab for your application in the [Developer Console](https://app.box.com/developers/console). Submitting the application for approval will send an email to your enterprise's Primary Admin to approve the application. When a Box Admin approves or declines your request, you will get an email with the decision. More information on this process is available in our [support article on app authorization](https://support.box.com/hc/en-us/articles/360043697014-Authorizing-Apps-in-the-Box-App-Approval-Process). ## Manual Approval The following steps provide instructions on how to manually approve the application. ### As a developer 1. Navigate to the **Configuration** tab for your application in the [Developer Console](https://app.box.com/developers/console). 2. Scroll down to the OAuth 2.0 Credentials section and copy the **Client ID** value to provide to a Box Admin. Alternatively, hover over the application in the [My Platform Apps](g://applications) view to look up the **ClientID** and then copy it using the `copy` button. # Finding a Box Admin If you don't know your enterprise Admin, go to your Box Account Settings page and scroll to the bottom. If an admin contact is set you should see their contact information under "Admin Contact". ### As an Admin 1. Navigate to the [Admin Console](https://app.box.com/master/settings/custom) and select the **Apps** tab (1) from the left navigation panel. 2. Click the **Platform Apps Manager** tab (2) at the top of your screen. 3. For both Server and User Authentication Apps screens, click the **Add App** (3) button in the top right corner to add a new app. 4. Alternatively, you can use the Platform Apps Manager table menu (4) to authorize and enable apps. #### Server Authentication Apps #### User Authentication Apps In the popup that appears, enter the client ID for the application that the developer collected from the **Configuration** tab of the [Developer Console](https://app.box.com/developers/console). ## Re-authorization on changes When the application's scopes or access level change the application needs to be re-authorized. Repeat the process above and request a new Access Token for the new changes to take effect. In the same section where the application was initially authorized, an Admin can re-authorize the application by clicking on the ellipses to the right of the application name to **Reauthorize App**. **Reference:** https://developer.box.com/guides/authorization/platform-app-approval/ --- ## Untitled *Type: guide | Category: Box AI * Box AI Box AI API allows you to use Box AI functionality in your platform applications. For example, you can implement Box AI question and… # Box AI Box AI API allows you to use Box AI functionality in your platform applications. For example, you can implement Box AI question and answer functionality in your third party application, or generate content right in your product’s content editor. ## Box AI API capabilities Box AI API provides a number of capabilities designed to help you leverage Large Language Models (LLMs) in your application workflows. Currently, you can ask Box AI to answer user questions, summarize the document content, or generate text you can use in your documents. You can also use Box AI to extract metadata from the provided input, such as a schema or metadata template. The [Box AI for UI Elements](g://embed/ui-elements/preview#box-ai-ui-element) functionality allows embedding Box AI in your apps. ### Ask questions to Box AI You can use Box AI API to ask questions about the content, for example, while working on documents you store in Box. Box AI can answer your questions about the content or generate a summary based on the file you supply. Have a look at [Box AI for Documents](https://support.box.com/hc/en-us/articles/22158484213267-Box-AI-for-Documents) to see an example of how users can interact with Box AI while working with their documents. ### Generate text with Box AI You can use Box AI API to generate text from scratch, from existing text within a Box Note, or based on a given document in Preview. For example, you can ask Box AI to create a template or meeting agenda based on an article you are viewing in Preview. Another example is Box Notes that uses Box AI to generate text and refine the already existing note content. For details, see [Box AI for Notes](https://support.box.com/hc/en-us/articles/22198577315347-Box-AI-for-Notes). ### Metadata extraction The [`POST /2.0/ai/extract`](e://post_ai_extract) and [`POST /2.0/ai/extract_structured`](e://post_ai_extract_structured) endpoints allow you to extract data from the provided input and return them in a form of key-value pairs. - Use the `extract_structured` endpoint to extract data according to a pre-defined structure obtained from the metadata template, or a set of fields. - Use the `extract` endpoint to extract data from a file using a prompt that can include a stringified version of formats such as JSON or XML, or even plain text. ### Configuration overrides You can use the `ai_agent` parameter available in the Box AI API requests to override the default agent configuration and introduce your own custom settings. For details, see [AI agent default configuration](g://box-ai/ai-agents/get-agent-default-config). ### Box AI for UI Elements Box AI for UI Elements is available in Content Preview allows asking questions about documents directly within platform applications. Check out how to use the [Box AI for UI Elements](g://embed/ui-elements/preview#box-ai-ui-element) to embed Box AI functionality in your projects. ## Supported languages Box AI works in a number of languages including English, Japanese, French, Spanish, and many more. However, the underlying models are primarily trained on English language documents. This means that prompts in other languages may return answers of lower quality than in English. Tests have shown satisfactory results for summarizing, checking grammar and spelling, and answering questions, but bear in mind that the results may be different than in English. Switch the language to Japanese to get better results for this language. ## Box AI API in User Activity Report (UAR) [User Activity Reports](https://support.box.com/hc/en-us/articles/4415012490387-User-Activity-Report) provide an overview of the actions the users are taking in Box. Box Admins use this report to view the actions taken by their users within a given time period, and this includes interactions with Box AI. The report contains the following action types that Box admins can select to get details for Box AI: - **AI query**: The user queried Box AI and received a response. - **Failed AI query**: The user queried Box AI but did not receive a response. **Reference:** https://developer.box.com/guides/box-ai/ --- ## Untitled *Type: guide | Category: Box Relay * Get Workflows The get workflows endpoint can be used to grab all workflows on a particular folder. It will return all workflows regardless… # Get Workflows The [get workflows](e://get-workflows) endpoint can be used to grab all workflows on a particular folder. It will return all workflows regardless of if there is a flow of type `WORKFLOW_MANUAL_START`. For more information on how to use these endpoints, refer to our [blog](https://medium.com/box-developer-blog/manual-start-workflow-api-box-relay-4f8d0f51b7a4) post. **Reference:** https://developer.box.com/guides/box-relay/get-workflows/ --- ## Untitled *Type: guide | Category: Box Relay * Box Relay Box Relay is a workflow automation application that enables Box power users to automate and accelerate business processes centered… # Box Relay [Box Relay](https://support.box.com/hc/en-us/articles/360044196213-Introducing-Box-Relay) is a workflow automation application that enables Box power users to automate and accelerate business processes centered around content. Currently, there are two API [endpoints](resource://workflow) developers can use with more planned to be released in the future. Both were created to work directly with [manual start flows](https://support.box.com/hc/en-us/articles/360044628853-Creating-and-Running-a-Manual-Start-Workflow). For more information on how to use these endpoints, refer to our [blog](https://medium.com/box-developer-blog/manual-start-workflow-api-box-relay-4f8d0f51b7a4) post. ## Required Scopes The following [scopes](g://api-calls/permissions-and-errors/scopes) must be enabled for an application before use of Box Relay's endpoints. - [Read all files and folders stored in Box](g://api-calls/permissions-and-errors/scopes/#read-all-files-and-folders) - [Write all files and folders stored in Box](g://api-calls/permissions-and-errors/scopes/#read-and-write-all-files-and-folders) - [Manage Box Relay](g://api-calls/permissions-and-errors/scopes/#manage-box-relay) Depending on the selected authentication method and enterprise's settings, your application may require Admin authorization or re-authorization before successful use of any newly selected scopes. ## Rate Limits Please see our [rate limit guide](g://api-calls/permissions-and-errors/rate-limits/#per-api-rate-limits) for more information. ## Testing Due to the feature parity, it may be useful to familiarize yourself with [Box Relay functionality using the Box web app](https://support.box.com/hc/en-us/articles/360044628853-Creating-and-Running-a-Manual-Start-Workflow) before leveraging the API. As with all API endpoints, we recommend testing via [developer sandbox environment](https://support.box.com/hc/en-us/articles/360043697274-Managing-developer-sandboxes-for-Box-admins) to eliminate the risk of impacting production content. **Reference:** https://developer.box.com/guides/box-relay/ --- ## Untitled *Type: guide | Category: Box Relay * Start Workflow The start workflow endpoint can be used to start a flow within a workflow of type WORKFLOW_MANUAL_START. Other flow types… # Start Workflow The [start workflow endpoint](e://post-workflows-id-start) can be used to start a flow within a workflow of type `WORKFLOW_MANUAL_START`. Other flow types cannot be started. If you have the flow set up to accept configurations at runtime, you must send in the optional `outcomes` array object. For more information on how to use this endpoint, refer to our [blog](https://medium.com/box-developer-blog/manual-start-workflow-api-box-relay-4f8d0f51b7a4) post. **Reference:** https://developer.box.com/guides/box-relay/start-workflow/ --- ## Untitled *Type: guide | Category: Box MCP Server * Box MCP Server Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to LLMs. MCP servers make… # Box MCP Server Model Context Protocol ([MCP](https://modelcontextprotocol.io/introduction)) is an open protocol that standardizes how applications provide context to LLMs. MCP servers make building advanced integrations simpler and less time consuming. Box MCP Server allows third party AI agents from platforms like Copilot Studio, Cursor, Claude for Desktop to access Box content seamlessly. It extends the agent’s capabilities by allowing it to perform actions related to content stored in Box. There are two types of Box MCP Servers: - remote Box MCP Server which you can create or enable in the Box Admin Console. It is hosted directly in Box. - self-hosted Box MCP Server which you can clone and host on your local machine, as this version in an open source Box Developer community project. Check the detailed guides on both types of Box MCP Servers, as the level of the implemented tools differs. Learn how to enable Box MCP Server: Enable the remote Box MCP Server in the Admin Console. It is hosted directly in Box. Beta An open source Box Developer community project. You can clone this Box MCP Sever and host it on your local machine. Open source Watch an interview with Box CTO, Ben Kus, and learn how MCP empowers AI agents to work dynamically across platforms, reducing the development effort. **Reference:** https://developer.box.com/guides/box-mcp/ --- ## Untitled *Type: guide | Category: Box Sign * Cancel Box Sign Request A Box Sign request, that has not yet been signed or declined, can be cancelled using the cancel Box Sign request… # Cancel Box Sign Request A Box Sign request, that has not yet been signed or declined, can be cancelled using the [cancel Box Sign request endpoint](e://post-sign-requests-id-cancel). Any outstanding signers will no longer be able to sign the document. Only the user who created the request, the requester, is able to cancel it. A request cannot be cancelled if it was declined, fully signed, or the document is still converting. **Reference:** https://developer.box.com/guides/box-sign/cancel-sign-request/ --- ## Untitled *Type: guide | Category: Box Sign * Create Box Sign Request At minimum, to create Box Sign request you need the a file you want to be signed, a destination folder for the… # Create Box Sign Request At minimum, to [create Box Sign request](e://post-sign-requests) you need the a file you want to be signed, a destination folder for the signed document/[signing log](https://support.box.com/hc/en-us/articles/4404095202579-Viewing-the-signing-log), and signers. Creation of the CFR Part 11 signature requests with public API is not supported. See [21 CFR Part 11 Compliance Support](https://support.box.com/hc/en-us/articles/24169443030163) for more information. ## Document preparation Preparing a document prior to sending a Box Sign request allows developers to add date, text, checkbox, and/or signature placeholders for signers. This can be done with UI or [tags](https://support.box.com/hc/en-us/articles/4404085855251-Creating-templates-using-tags) directly in the document. If this is not done, signers receive an unprepared document and can place signatures and fields at their own discretion. However, developers can leverage controls in the request that allow them to turn features for the unprepared document on and off. Setting `is_document_preparation_needed` to `true` provides a `prepare_url` in the response. Visiting this link in your browser allows you to complete document preparation and send the request in the UI. To learn more about document tags, please see our [support article](https://support.box.com/hc/en-us/articles/4404085855251-Creating-templates-using-tags). Prefill tags created in a template with the Box web app cannot be accessed from the API. ## Files Each Box Sign request begins with a file that needs to be signed. If the file does not already exist in Box, it must be [uploaded](e://post-files-content), in a separate API call, prior to creating the request. Multiple files can be signed in one request. File ID of the first file in a request is specified in the `source_files` body parameter. The requester must have download privileges to the file in Box. Review our [collaboration levels](https://support.box.com/hc/en-us/articles/360044196413-Understanding-Collaborator-Permission-Levels) to ensure this requirement is met. Supported file types include: - All [documents](g://representations/supported-file-types/#documents) - All [presentations](g://representations/supported-file-types/#presentations) - Images: `png`, `jpg`, `jpeg`, `tiff` only - Text-based files: `.csv`, `.txt` only All file types are converted to `.pdf` for the signature process. This converted document can be found in the `parent_folder` upon successfully sending a request. This means that the final, signed document is a `.pdf`, regardless of the original file type. As each signer completes the request, Box Sign will automatically add a new file version. File size limits are determined by your account type. Please see our [uploads guide](g://uploads/direct) for more information. ## Parent folder The folder ID specified in the `parent_folder` body parameter determines the destination of the final signed document and [signing log](https://support.box.com/hc/en-us/articles/4404095202579-Viewing-the-signing-log). This folder cannot be the All Files or root level, which is represented by folder ID `0`. ## Signers Each signer must be assigned a [role](https://support.box.com/hc/en-us/articles/4404105660947-Roles-for-signers): `signer`, `approver`, or `final copy_reader`. If the requester is not given a role, a signer with the role `final_copy_reader` is automatically created. This means they only receive a copy of the final, signed document and [signing log](https://support.box.com/hc/en-us/articles/4404095202579-Viewing-the-signing-log). Signers do not need to have an existing Box account, nor create one, in order to sign documents. Unlike other API endpoints, signers are invited by email address and not Box `user_id`. If necessary, signers can log in to Box before signing the request. In such case set the parameter `login_required` to `true` for signers. If the signer does not have an existing account, they will have an option to create a free Box account. Box Sign will only attempt to send signing emails to the email addresses provided for signers in the request. For Box users, this does not include email aliases unless specified. Please double check to ensure all provided signer email addresses are valid. ### Inputs The `inputs` parameter represents placeholders that the user can interact with. The `document_tag_id` parameter can be populated with data you want to pass when creating a sign request. ## Templates You can create a sign request using a template. To do so, you must provide the `template_id` parameter. See [this guide](g://box-sign/sign-templates) to learn more about using templates when creating sign requests. ## Redirects The URLs specified in the `redirect_url` and `declined_redirect_url` allow you to redirect signers to a custom landing page after signing or declining the sign request. For example, if you integrate your application with Box Sign, you can redirect signers back to your application or to a custom landing page. You can set redirect URLs globally for all signers as well as for specific signers only. This means that Box Sign will use specific URLs for signers of your choice, and global settings for the rest. If you don't configure any redirect URLs Box Sign will redirect signers to a default page. The default page includes the following note: "Once the document has been completed by all parties, a limited-time link to a finalized copy will be be emailed to you, and, if you have a Box account, a copy will be placed in your account." If you decide to redirect the signers to a different page, this information will not be available to signers. ## Multiple signers and signing order Signing order is determined by ordering the provided `order` numbers from smallest to largest. If two numbers are the same, signers will receive the request at the same time. Initially, only the signer(s) with the lowest assigned `order` number will receive a Box Sign request email. Once they sign, the following user(s) will an email and so on. Box Sign automatically adds a new version of the document to the `parent_folder` as each user signs. If any signer declines, any remaining signers will not receive a Box Sign request email. The overall request is declined. ## Request status - `converting`: The file is converted to a `.pdf` for the signing process once the sign request is sent. - `error_converting`: An issue was encountered while converting the file to a `.pdf`. - `created`: If `document_preparation_is_needed` is set to `true`, but the `prepare_url` has not yet been visited. - `sent`: The request was successfully sent, but no signer has interacted with it. - `error_sending`: An issue was encountered while sending the request. - `viewed`: Once the first, or only, signer clicks on **Review document** in the signing email or visits the signing URL. - `downloaded`: The signing document was downloaded by signer. - `signed`: All signers completed the request. - `signed and downloaded`: The signing document was signed and downloaded by signer. - `declined`: If any signer declines the request. - `cancelled`: If the request is cancelled via UI or API. - `expired`: The date of expiration has passed with outstanding, incomplete signatures. - `finalizing`: If all signers have signed the request, but the final document with signatures and the signing log has not been generated yet. - `error_finalizing`: If the `finalizing` phase did not complete successfully. Encountering an error status requires creating a new sign request to retry. **Reference:** https://developer.box.com/guides/box-sign/create-sign-request/ --- ## Untitled *Type: guide | Category: Box Sign * Embedded Sign client Box Embed allows you to embed Box Sign features into your own website. This way, users don't have to leave the website… # Embedded Sign client [Box Embed](g://embed/box-embed) allows you to embed Box Sign features into your own website. This way, users don't have to leave the website, go to Box Sign to sign the document, and then come back to finish the process. Instead, Box Embed allows them to complete the signing process within the external website. To integrate Box Sign experience within your own website, you need the `iframable_embed_url` parameter that is specifically designed to allow signing documents within the HTML `iframe` tag. A sample `iframable_embed_url` looks as follows: ``` https://app.box.com/embed/sign/document/f14d7098-a331-494b-808b-79bc7f3992a3/f14d7098-a331-494b-808b-79bc7f3992a4 ``` To get the `iframeable_embed_url` pass the [`embed_url_external_user_id`](e://post-sign-requests#param-signers-embed_url_external_user_id) parameter for each signer when calling the [create sign request](e://post-sign-requests) endpoint. The returned response will contain a unique `iframeable_embed_url` for that signer. To embed Sign features and make them available to the users, use the URL within the `iframe` tag: ``` <iframe src="https://app.box.com/embed/sign/document/f14d7098-a331-494b-808b-79bc7f3992a3/f14d7098-a331-494b-808b-79bc7f3992a4" width="{pixels}" height="{pixels}" frameborder="0" allowfullscreen webkitallowfullscreen msallowfullscreen ></iframe> ``` For details on working with Box Embed, see [this guide](g://embed/box-embed#programmatically). Box Embed uses the [Cloud Game](g://embed/box-embed#cloud-game) widget to prevent clickjacking. In this case, when the user wants to sign a document, they will have to interact with the widget and drag a cloud to the correct location before proceeding to document signing. **Reference:** https://developer.box.com/guides/box-sign/embedded-sign-client/ --- ## Untitled *Type: guide | Category: Box Sign * Box Sign Programmatically harness the full functionality of the Box Sign web app experience by leveraging Box Sign’s API endpoints to create… # Box Sign Programmatically harness the full functionality of the Box Sign web app experience by leveraging Box Sign’s API endpoints to create, list, resend, and cancel sign requests. ## Enablement The following account types support requests through the Box Sign API: Business, Business Plus, Enterprise, Enterprise Suites, Enterprise Plus, and Enterprise Advanced. To locate your account type, navigate to **Account Settings** and scroll down to the **Account Details** section of the **Account** tab. For Admin details on restricting access, please see our [support article](https://support.box.com/hc/en-us/articles/4404076971155-Enabling-Box-Sign). ## Required scopes The following [scopes](g://api-calls/permissions-and-errors/scopes) must be enabled for an application before use of Box Sign's endpoints. - [Read all files and folders stored in Box](g://api-calls/permissions-and-errors/scopes/#read-all-files-and-folders) - [Write all files and folders stored in Box](g://api-calls/permissions-and-errors/scopes/#read-and-write-all-files-and-folders) - [Manage signature requests](g://api-calls/permissions-and-errors/scopes/#manage-signature-requests) Depending on the selected authentication method and enterprise's settings, your application may require Admin authorization or re-authorization before successful use of any newly selected scopes. ## Events Please see our [events guide](g://events/event-triggers/sign-events) for more information. ## Webhooks Please see our [webhooks guide](g://webhooks/triggers) for more information. ## Rate Limits Please see our [rate limit guide](g://api-calls/permissions-and-errors/rate-limits/#per-api-rate-limits) for more information. ## Testing Due to the feature parity, it may be useful to familiarize yourself with [Box Sign functionality using the Box web app](https://support.box.com/hc/en-us/articles/4404105810195-Sending-a-document-for-signature) before leveraging the API. As with all API endpoints, we recommend testing via [developer sandbox environment](https://support.box.com/hc/en-us/articles/360043697274-Managing-developer-sandboxes-for-Box-admins) to eliminate the risk of impacting production content. **Reference:** https://developer.box.com/guides/box-sign/ --- ## Untitled *Type: guide | Category: Box Sign * Resend Box Sign Request The resend a Box sign request endpoint can be used to resend request emails to any remaining signers. A Box Sign… # Resend Box Sign Request The [resend a Box sign request endpoint](e://post-sign-requests-id-resend) can be used to resend request emails to any remaining signers. A Box Sign request cannot be resent if the [status](g://box-sign/create-sign-request/#request-status) is: `signed`, `cancelled`, `declined`, `expired`, `error_sending`, or `error_converting`. If a Box Sign request was recently sent, you will need to wait 10 minutes before resending. If you try before this time has passed you will receive a 400 error. Reminder emails can be enabled when creating a Box Sign request to avoid the need to resend the request. **Reference:** https://developer.box.com/guides/box-sign/resend-sign-request/ --- ## Untitled *Type: guide | Category: Box Sign * List Box Sign Requests All The get sign requests endpoint can be used to view a list of all Box Sign requests created by the user associated… # List Box Sign Requests ## All The [get sign requests endpoint](e://get-sign-requests) can be used to view a list of all Box Sign requests created by the user associated with the passed Access Token. ## By ID The [get sign requests by ID endpoint](e://get-sign-requests-id) can be used to view information about a specific Box Sign request. This endpoint requires the sign request's ID, which can be obtained by using the [get all Box Sign requests endpoint](e://get-sign-requests) or in the response when [creating a Box Sign request](e://post-sign-requests). **Reference:** https://developer.box.com/guides/box-sign/list-sign-requests/ --- ## Untitled *Type: guide | Category: Box Sign * Create Sign Request with Sign Template The Sign Request API allows you to use a predefined Box Sign template when creating a sign request… # Create Sign Request with Sign Template The Sign Request API allows you to use a predefined Box Sign template when creating a sign request. The template includes placeholders that are automatically populated with data when creating the request. ## Create Template Start with creating a Box Sign template that includes `text`, `date`, and `signature` fields you will need for you request. See the [template guides](https://support.box.com/hc/en-us/articles/4404094944915-Creating-templates) guide for detailed instructions. ## Get the Template ID To send a sign request, you need to pass the ID of the template you want to use. List the templates to find the `template_id`. The response is similar to the following one (abbreviated for guide purposes). For the full response example, see [Box Sign template API](e://get-sign-templates#response-example). You can also learn more about the specific parameters in the [Create Sign Request](e://post-sign-requests) guide. ``` "entries": [ { "id": "6ae28666-03c4-4ac1-80db-06a90d3b1361", "name": "Contract.pdf", "parent_folder": { "id": "157064745449", "etag": "0", "type": "folder", "sequence_id": "0", "name": "My Sign Requests" }, "source_files": [ { "id": "1216382236853", "etag": "0", "type": "file", "sequence_id": "0", "sha1": "ca9c75cda0d5e3c3c9b0a1e6d42cb5e29a211ab6", "file_version": { "id": "1327286673653", "type": "file_version", "sha1": "ca9c75cda0d5e3c3c9b0a1e6d42cb5e29a211ab6" } } ], "signers": [ { "email": "", "label": "reader", "public_id": "4Z8QZZV4", "role": "final_copy_reader", "is_in_person": false, "order": 1, "inputs": [...] }, { "email": "", "label": "signer1", "public_id": "4Z8QZZV4", "role": "signer", "is_in_person": false, "order": 1, "inputs": [...] }, { "email": "", "label": "signer2", "public_id": "13VK8794", "role": "signer", "is_in_person": false, "order": 1, "inputs": [ { "document_tag_id": "signer2_full_name", "id": "da431975-55c5-4629-86ae-3fb12dda1386", "type": "text", "text_value": null, "is_required": true, "content_type": "full_name", ... }, { "document_tag_id": null, "id": "b5a76a22-8d48-456e-a012-22a12fc91eb7", "type": "signature", ... }, { "document_tag_id": null, "id": "7e0cc4ee-b878-4739-afde-acbf69b117b2", "type": "date", "date_value": null, ... } ], } ] ... } ] ``` ## Create the sign request Follow these steps to [create sign request](e://post-sign-requests) using a template: In the request body, provide the `template_id`: ``` { "template_id": "6ae28666-03c4-4ac1-80db-06a90d3b1361", "parent_folder": { "id": "123456789", "etag": "0", "type": "folder", "sequence_id": "0", "name": "My Sign Requests" }, ... } ``` Add the signer email addresses and roles: ``` { "template_id": "6ae28666-03c4-4ac1-80db-06a90d3b1361", "parent_folder": { "id": "157064745449", "etag": "0", "type": "folder", "sequence_id": "0", "name": "My Sign Requests" }, "signers": [ { "email": "signer1@sample.com", "role": "signer" }, { "email": "signer2@sample.com", "role": "signer" } ] } ``` Add the `prefill_tags` to populate the fields. Make sure the signer order is the same as the one displayed on the template. If the template had `signer1` first and then `signer2`, the `POST` request must reflect the same order to assign the proper signers. ``` { "template_id": "6ae28666-03c4-4ac1-80db-06a90d3b1361", "parent_folder": { "id": "123456789000", "etag": "0", "type": "folder", "sequence_id": "0", "name": "My Sign Requests" }, "signers": [ { "email": "signer1@sample.com", "role": "signer" }, { "email": "signer2@sample.com", "role": "signer" } ], "prefill_tags": [ { "document_tag_id": "signer1_full_name", "text_value": "Aaron Levie" }, { "document_tag_id": "signer2_full_name", "text_value": "Albert Einstein" } ] } ``` Send the `POST` request. The response will be similar to the following: ``` { "is_document_preparation_needed": false, ... "signers": [ { "email": "reader@sample.com", "role": "final_copy_reader", }, { "email": "signer1@sample.com", "role": "signer", }, { "email": "signer2@sample.com", "role": "signer", } ], "id": "d02fefd2-15fa-431f-a127-2b4525616ae6", "prefill_tags": [ { "document_tag_id": "signer1_full_name", "text_value": "Aaron Levie", }, { "document_tag_id": "signer2_full_name", "text_value": "Albert Einstein", } ], "source_files": [], "parent_folder": { "id": "123456789000", "type": "folder", "name": "My Sign Requests" }, "name": "Contract.pdf", "type": "sign-request", "status": "created", "sign_files": { "files": [ { "id": "123456789", "type": "file", "name": "Contract.pdf", } ], "is_ready_for_download": true }, "template_id": "6ae28666-03c4-4ac1-80db-06a90d3b1361" } ``` **Reference:** https://developer.box.com/guides/box-sign/sign-templates/ --- ## Untitled *Type: guide | Category: Box Sign * Suppress default Box Sign notifications Box Sign API allows you to suppress the default Box email notifications sent during the Sign… # Suppress default Box Sign notifications Box Sign API allows you to suppress the default Box email notifications sent during the Sign workflow. ​​This feature facilitates the ownership of Box Sign notifications with the following options: You can use a fully-customized email notification template to send emails from your domain. Apart from emails, you can send push notifications or text messages.​ When you choose to suppress Box email notifications, your organization assumes responsibility for ensuring the delivery to Signers of all notifications at the appropriate time in the signing process and with the appropriate content, in compliance with all applicable laws and regulations, including with respect to obtaining Signer consent to the delivery methods used, if applicable. ## Using Box Sign API to suppress default notifications To suppress Box Sign email notifications, you must set the following parameters: Set the `suppress_notifications` parameter in the [`signers`](e://post-sign-requests/#param-signers) object to `true` to turn the notifications off. Set the [`embed_url_external_user_id`](e://post-sign-requests/#param-signers-embed_url_external_user_id) parameter to specify the user who will not receive notifications. This configuration turns off the automatic Box Sign email notifications for a given user. As a result, you can configure and send your own notifications. ``` curl -i -X POST "https://api.box.com/2.0/sign_requests" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "signers": [ { "role": "signer", "email": "example_email@box.com" "suppress_notifications": true "embed_url_external_user_id": "1234" } ], "source_files": [ { "type": "file", "id": "123456789" } ], "parent_folder": { "type": "folder", "id": "0987654321" } }' ``` ## Signing Log entries When Box Sign default notifications are suppressed, the Signing Log will indicate that the sender has suppressed all Box Sign notifications. The log will also provide information on the system used for purposes of notification delivery and the user ID of the signer on your organization’s system, as provided to Box Sign through your API integration. **Reference:** https://developer.box.com/guides/box-sign/suppress-sign-notifications/ --- ## Untitled *Type: guide | Category: CLI * CLI The Box Command Line Interface (CLI) is a tool for making requests to Box APIs from your terminal window or command prompt. Quick start… # CLI The Box Command Line Interface (CLI) is a tool for making requests to Box APIs from your terminal window or command prompt. ## Quick start [Get started using the Box CLI with OAuth 2.0](g://cli/quick-start). ## CLI setup and use - To use [server authentication](g://authentication/jwt) method, check out [this](g://cli/cli-docs/jwt-cli) guide. - To use [CCG authentication](g://authentication/client-credentials) method, check out [this](https://github.com/box/boxcli/tree/main/docs/configure.md#box-configureenvironmentsadd-path) guide. - To perform bulk actions using CLI commands, check out [this](https://github.com/box/boxcli/blob/main/docs/Bulk%20actions/README.md) guide. ## Sample scripts Using the Box CLI is great by itself, but it becomes even more powerful when combined with a Powershell script. We've created a [library](https://github.com/box/boxcli/tree/main/examples) of script templates for you to get started automating repetitive tasks. - [Explore sample scripts](g://cli/scripts/index) ## Advanced The GitHub page also has some additional guides that might be of interest to an advanced CLI user. - [Setup autocomplete](https://github.com/box/boxcli/blob/main/docs/autocomplete.md) - [Configure another app](https://github.com/box/boxcli/blob/main/docs/configure.md#box-configureenvironmentsadd-path) - [Switch accounts](https://github.com/box/boxcli/blob/main/docs/configure.md#box-configureenvironmentsswitch-user-userid) - [Token cache](https://github.com/box/boxcli/blob/main/docs/configure.md#box-configureenvironmentsupdate-name) **Reference:** https://developer.box.com/guides/cli/ --- ## Untitled *Type: guide | Category: Collaborations * Sharing with Groups To share a file or folder with a group of users, create a collaboration using the group ID, the ID of the file or folder… # Sharing with Groups To share a file or folder with a group of users, create a collaboration using the group ID, the ID of the file or folder, and the role or permissions level the group should have when accessing the file or folder. The collaboration roles are `editor`, `viewer`, `previewer`, `uploader`, `previewer uploader`, `viewer uploader`, `co-owner`, or `owner`. For a full description of each role, please refer to our [support documentation](https://support.box.com/hc/en-us/articles/360044196413-Understanding-Collaborator-Permission-Levels). ## Nested objects When creating a collaboration there are two nested objects within the request body: `accessible_by` and `item`. The `accessible_by` object specifies who the item should be shared with and includes a group `id` and the `type`. The `type` field should always be set to `group`. The `item` object specifies what is being shared. It includes a `type` field which should be set as `file` or `folder`, and an `id` for that file or folder. **Reference:** https://developer.box.com/guides/collaborations/groups/ --- ## Untitled *Type: guide | Category: Collaborations * Get Pending Collaborations To get the pending collaborations for a user, call the GET /collaborations API with a status of pending. This… # Get Pending Collaborations To get the pending collaborations for a user, call the `GET /collaborations` API with a `status` of `pending`. This only returns the current list of pending collaborations for a user. This API does not allow for returning all collaborations for a user. **Reference:** https://developer.box.com/guides/collaborations/pending/ --- ## Untitled *Type: guide | Category: Collaborations * Collaborations Collaborations define access permissions for users and groups to files and folders, similar to access control lists. A… # Collaborations Collaborations define access permissions for users and groups to files and folders, similar to access control lists. A collaboration object grants a user or group access to a file or folder with permissions defined by a specific role. The collaboration roles are `editor`, `viewer`, `previewer`, `uploader`, `previewer uploader`, `viewer uploader`, `co-owner`, or `owner`. For a full description of each role, please refer to our [support documentation](https://support.box.com/hc/en-us/articles/360044196413-Understanding-Collaborator-Permission-Levels). **Reference:** https://developer.box.com/guides/collaborations/ --- ## Untitled *Type: guide | Category: Comments * Create Comment To create a comment, call the POST /comments API with the message of the comment, as well as the ID of the file to leave the… # Create Comment To create a comment, call the [`POST /comments`](e://post_comments) API with the message of the comment, as well as the ID of the file to leave the comment on. A comment's message can also mentions users using the `@` sign. To do so, add the string `@[userid:name]` anywhere within the message. The `user_id` is the target user's ID, where the `name` can be any custom phrase. In the Box UI this name will link to the user's profile. Then, pass this string as the `tagged_message` instead of the `message`. **Reference:** https://developer.box.com/guides/comments/create-comment/ --- ## Untitled *Type: guide | Category: Collaborations * Share Content with User To share content with a user, create a collaboration using the user ID or email address, the ID of the content, and… # Share Content with User To share content with a user, create a collaboration using the user ID or email address, the ID of the content, and the role or permissions level the user should have when accessing the content. The collaboration roles are `editor`,`viewer`, `previewer`, `uploader`, `previewer uploader`, `viewer uploader`,`co-owner`, or `owner`. For a full description of each role, please refer to our [support documentation](https://support.box.com/hc/en-us/articles/360044196413-Understanding-Collaborator-Permission-Levels). ## Nested objects When creating a collaboration there are two nested objects within the request body: `accessible_by` and `item`. The `accessible_by` object specifies who the item should be shared with and includes a group `id` and the `type`. The `type` field should always be set to `user`. The `item` object specifies what is being shared. It includes a `type` field which should be set as `file` and an `id` for that file. **Reference:** https://developer.box.com/guides/collaborations/share-content/ --- ## Untitled *Type: guide | Category: Comments * Create Reply To create a reply to a previous comment, call the POST /comments API with the message of the new comment, as well as the ID of… # Create Reply To create a reply to a previous comment, call the [`POST /comments`](e://post_comments) API with the message of the new comment, as well as the ID of the previous comment to leave the reply on. A reply's message can also mentions users using the `@` sign. To do so, add the string `@[userid:name]` anywhere within the message. The `user_id` is the target user's ID, where the `name` can be any custom phrase. In the Box UI this name will link to the user's profile. Then, pass this string as the `tagged_message` instead of the `message`. **Reference:** https://developer.box.com/guides/comments/create-reply/ --- ## Untitled *Type: guide | Category: Comments * Comments Comments are messages generated by Box users on files, allowing users to collaborate together on a file, discussing any feedback… # Comments Comments are messages generated by Box users on files, allowing users to collaborate together on a file, discussing any feedback they might have on the content. Each comment is tied to a specific file and user, and comments can be created as independent comments or as replies to previous comments. **Reference:** https://developer.box.com/guides/comments/ --- ## Untitled *Type: guide | Category: Collections * Add Item to Collection To add an item to a collection, call the PUT endpoint for that specific type of item and pass along a list of… # Add Item to Collection To add an item to a collection, call the `PUT` endpoint for that specific type of item and pass along a list of collection IDs. The only collection that is available via the API is the "Favorites" collection. The ID of this collection is different for every user. ## Add file to collection To add a file to a collection, call the `PUT /files/:id` API and pass along a list of collection IDs. ## Add folder to collection To add a folder to a collection, call the `PUT /folders/:id` API and pass along a list of collection IDs. ## Add web link to collection To add a web link to a collection, call the `PUT /web_links/:id` API and pass along a list of collection IDs. **Reference:** https://developer.box.com/guides/collections/add/ --- ## Untitled *Type: guide | Category: Collections * Collections Collections in Box are a way to group files, folders, and web links without putting them all into a folder together. The only… # Collections Collections in Box are a way to group files, folders, and web links without putting them all into a folder together. The only collection that is available via the API is the "Favorites" collection. The ID of this collection is different for every user. **Reference:** https://developer.box.com/guides/collections/ --- ## Untitled *Type: guide | Category: Collections * List Items in Collections To list all files, folders and web links in a folder call the GET /collections/:id/items API. The only collection… # List Items in Collections To list all files, folders and web links in a folder call the [`GET /collections/:id/items`](e://get_collections_id_items) API. The only collection that is available via the API is the "Favorites" collection. The ID of this collection is different for every user. **Reference:** https://developer.box.com/guides/collections/list-items/ --- ## Untitled *Type: guide | Category: Collections * List User's Collections To list all collections for a user, call the GET /collections API. The only collection that is available via the API… # List User's Collections To list all collections for a user, call the [`GET /collections`](e://get_collections) API. The only collection that is available via the API is the "Favorites" collection. The ID of this collection is different for every user. ## Favorites Collection The only collection that can items can currently be added and removed to via the API is the "Favorites" collection. The ID of the favorites collection is different for every user. To find the user's collection ID for their favorites, list all the user's collections and then find the collection with a `collection_type` of `favorites`. ``` { "entries": [ { "collection_type": "favorites", "id": "12345678", "name": "Favorites", "type": "collection" } ], "limit": 100, "offset": 0, "total_count": 1 } ``` **Reference:** https://developer.box.com/guides/collections/list/ --- ## Untitled *Type: guide | Category: Collections * Remove Item from Collection To remove an item from a collection, call the PUT endpoint for that specific type of item and pass along a list… # Remove Item from Collection To remove an item from a collection, call the `PUT` endpoint for that specific type of item and pass along a list of collection IDs that does not include the ID of the collection that needs to be removed. The only collection that is available via the API is the "Favorites" collection and therefore to remove an item from this collection can be achieved by passing the API an empty array of collections. ## Remove file from collection To remove a file from a collection, call the `PUT /files/:id` API and pass an empty array of collection IDs. ## Remove folder from collection To remove a folder from a collection, call the `PUT /folders/:id` API and pass an empty array of collection IDs. ## Remove web link from collection To remove a web link from a collection, call the `PUT /web_links/:id` API and pass an empty array of collection IDs. **Reference:** https://developer.box.com/guides/collections/remove/ --- ## Untitled *Type: guide | Category: Box Doc Gen * Get started with Box Doc Gen To start generating documents with Box Doc Gen API you will need a platform application and a developer token… # Get started with Box Doc Gen To start generating documents with Box Doc Gen API you will need a platform application and a developer token to authenticate your calls. You also need a Doc Gen template that will serve as an input source for your document. ## Enable Box Doc Gen To use Box Doc Gen, make sure it is enabled by an admin in the Admin Console. If you are a Box Admin, you will find the necessary information in [Enterprise Settings: Content & Sharing Tab](https://support.box.com/hc/en-us/articles/4404822772755-Enterprise-Settings-Content-Sharing-Tab#h_01FYQGK5RW42T07GV985MQ9E9A) documentation. ## Create and upload a Box Doc Gen template To use Box Doc Gen API to generate documents, a Box Doc Gen template must already exist in Box. You have the following options to create a template: - Install the [Box Doc Gen Template Creator add-in for Microsoft Word](https://support.box.com/hc/en-us/articles/36587535449747-Installing-Box-Doc-Gen-Add-in). - Create a Box Doc Gen template [using a JSON file](https://support.box.com/hc/en-us/articles/36148012877843-Creating-a-Box-Doc-Gen-Template-using-JSON-data) or manually create [template tags](https://support.box.com/hc/en-us/articles/36151895655059-Creating-A-Box-Doc-Gen-Template-Manually). ## Create a platform application First you need to create a platform application you will use to make calls. To create an application, follow the guide on [creating platform apps](g://applications/app-types/platform-apps). ## Generate a developer token You need a developer token to authenticate your app when sending requests. To generate a token: 1. Go to **Developer Console** > **My Platform Apps**. 2. Click the **Options menu** button (…) on the right. 3. Select **Generate Developer Token**. The token will be automatically generated and saved to clipboard. You can also open your app, go to **Configuration** > **Developer Token** and generate the token. A developer token is only valid for one hour. For additional details, see [developer token](g://authentication/tokens/developer-tokens). After you generate the token, you can use it in cURL or other clients, such as [Postman](g://tooling/postman), to make calls. ## Use webhooks You can create webhooks to monitor Doc Gen events and automate your business process or workflow. Follow the instructions for [adding webhooks](g://webhooks/v2/create-v2/). Your content type is your Doc Gen template file or folder. The supported [events](g://webhooks/triggers) are: - `DOCGEN_DOCUMENT_GENERATION_STARTED` - `DOCGEN_DOCUMENT_GENERATION_SUCCEEDED` - `DOCGEN_DOCUMENT_GENERATION_FAILED` Information that is posted in a notification: - Trigger name. - Webhook trigger timestamp. - Template file ID. - Template file version ID. - Template file name. - Destination folder. - Generated file ID (if the document generation process succeeds). - Output type (DOCX or PDF). - Reason (if the document generation process fails). **Reference:** https://developer.box.com/guides/docgen/docgen-getting-started/ --- ## Untitled *Type: guide | Category: Box Doc Gen * Box Doc Gen jobs A Box Doc Gen job runs when you make a request to generate a document. The document_generation_data parameter in the POST… # Box Doc Gen jobs A Box Doc Gen job runs when you make a request to generate a document. The `document_generation_data` parameter in the `POST` request is an array of entries that represent Box Doc Gen jobs run to generate a document. Box Doc Gen API allows you to get information about the Box Doc Gen jobs. ## Prerequisites Before you start using Box Doc Gen API, follow the steps listed in the [get started with Box Doc Gen](g://docgen/docgen-getting-started) guide to create a platform app and a Box Doc Gen template. ## List all Box Doc Gen jobs To get a list of all Box Doc Gen jobs that were run, use the `GET /2.0/docgen_jobs` endpoint. You don't have to provide any additional parameters. ## Get a Box Doc Gen job by ID To get a specific Box Doc Gen job, use the `GET /2.0/docgen_jobs_id` endpoint and provide the `job_id`. ## Get Box Doc Gen jobs in batch with a specific ID A single request can generate several documents. In such a case, a separate generation job is run for each document and all these jobs are included in one "batch" meaning a request. To get all jobs performed within one request, use the `GET /2.0/docgen_batch_jobs_id` endpoint and provide the `batch_id`. **Reference:** https://developer.box.com/guides/docgen/docgen-jobs/ --- ## Untitled *Type: guide | Category: Box Doc Gen * Box Doc Gen templates Box Doc Gen API allows you to retrieve information related to Box Doc Gen templates. Prerequisites Before you start… # Box Doc Gen templates Box Doc Gen API allows you to retrieve information related to Box Doc Gen templates. ## Prerequisites Before you start using Box Doc Gen API, follow the steps listed in the [get started with Box Doc Gen](g://docgen/docgen-getting-started) guide to create a platform app and a Box Doc Gen template. ## List Box Doc Gen templates To get a list of all created Box Doc Gen templates, use the `GET /2.0/docgen_templates` endpoint. You don't have to provide any additional parameters. The response will contain an `entries` array listing the already created Box Doc Gen templates. ## Get a Box Doc Gen template by ID To get a specific Box Doc Gen template, use the `GET /2.0/docgen_templates_id` endpoint and provide the `template_id`. The response will contain details of a file that was used as a Box Doc Gen template. ## List all document generation jobs for a template To get a list of all created Box Doc Gen templates, use the `GET /2.0/docgen_template_jobs_id` endpoint and provide the `template_id`. The response will contain a list of Box Doc Gen jobs that were run to generate documents. **Reference:** https://developer.box.com/guides/docgen/docgen-templates/ --- ## Untitled *Type: guide | Category: Box Doc Gen * Generate documents The POST /2.0/docgen_batches endpoint allows you to generate a document using Box Doc Gen template as input… # Generate documents The `POST /2.0/docgen_batches` endpoint allows you to generate a document using Box Doc Gen template as input. ## Prerequisites Before you start using Box Doc Gen API, follow the steps listed in the [get started with Box Doc Gen](g://docgen/docgen-getting-started) guide to create a platform app and a Box Doc Gen template. ## Send a request To generate a document or a set of documents, use the `POST /2.0/docgen_batches` endpoint. ### Parameters To make a call, you need to pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Example | | --- | --- | --- | | file.id | ID of the file to be marked as Box Doc Gen template. | 12345678 | | file.type | The type of provided input. The value is always file. | file | | file_version | The file version of a template. | 12345 | | input_source | The input source for generated document. The value has to be api for all the API-based document generation requests. | api | | output_type | The output file type. | docx, pdf | | destination_folder.id | The ID of the folder where the generated document will be stored. | 12345678 | | destination_folder.type | The type of the destination item. Since the generated files are stored in folders, the value is always folder. | file | | document_generation_data.generated_file_name | The name of the generated file. | New_Template | | document_generation_data.user_input | The JSON data to be used to generate document. | {"id": 2, "name": "Ink Cartridge", "type": "non-fragile"} | ## Use case When your Box Doc Gen template and JSON data is ready, you can make a request to Box Doc Gen API to generate documents. A sample call looks as follows: When the request is being processed, each entry in the `document_generation_data` array is treated as a separate document generation job that Box Doc Gen adds to the document generation queue. Generated documents will be saved in the designated folder. **Reference:** https://developer.box.com/guides/docgen/generate-document/ --- ## Untitled *Type: guide | Category: Box Doc Gen * Box Doc Gen Box Doc Gen allows you to generate business documents such as offer letters, sales contracts, invoices or agreements. You can… # Box Doc Gen Box Doc Gen allows you to generate business documents such as offer letters, sales contracts, invoices or agreements. You can generate documents based on Box Doc Gen templates uploaded to Box, with data fields that can be dynamically filled using Box Doc Gen API. Box Doc Gen only supports the ability to leverage English template tags when using Box Doc Gen templates. We recommend that customers test and review that Box Doc Gen supports their desired language requirements. ## Prerequisites - access to Microsoft Word To use Box Doc Gen, you must have access to Microsoft Word, as it is required for creating and authoring your document templates. You can utilize the Box Doc Gen Add-in for a code-free experience or apply tagging scripts within Word to prepare your documents. Box Doc Gen is designed to facilitate the dynamic generation of business documents, but it is important to note that Box does not have control over users’ access to Microsoft Word. Users must ensure they have the necessary permissions and access to Microsoft Word to create and author document templates effectively. ## Box Doc Gen API capabilities Box Doc Gen API allows you to: - mark documents as Box Doc Gen templates, - generate documents based on Box Doc Gen templates you store in Box, - examine the details of Box Doc Gen templates and document generation jobs. ## Box Doc Gen API version Box Doc Gen API was released in Box API version `2025.0`. All API requests to Box Doc Gen API endpoints must specify a valid API version by setting the `box-version` header to `2025.0`. For more details, see [Box API versioning](g://api-calls/api-versioning-strategy). ## Box Doc Gen workflow 1. Author your Doc Gen Template - Use [Doc Gen Add-in for Microsoft Word](https://support.box.com/hc/en-us/articles/36587535449747-Installing-Box-Doc-Gen-Add-in) to create a template without any code. - You can also leverage [Doc Gen's tagging script](https://support.box.com/hc/en-us/articles/36149723736723-Template-tags-reference) to author the template. 1. [Add the template to Box](https://support.box.com/hc/en-us/articles/36587432368275-Managing-Box-Doc-Gen-Templates-in-Relay) using the Box Doc Gen UI. At this point, you can: - Mark an existing file In Box as Doc Gen template. - Create or Upload a document and mark it as a Box Doc Gen template. 1. [Generate the document](g://docgen/generate-document) using Box Doc Gen API. **Reference:** https://developer.box.com/guides/docgen/ --- ## Untitled *Type: guide | Category: Box Doc Gen * Mark file as Box Doc Gen template You can mark an existing document as a Box Doc Gen template and use it to generate documents. Before you… # Mark file as Box Doc Gen template You can mark an existing document as a Box Doc Gen template and use it to generate documents. ## Before you start Before you start using Box Doc Gen API, follow the steps listed in the [get started with Box Doc Gen](g://docgen/docgen-getting-started) guide to create a platform app and a Box Doc Gen template. ## Send a request To send a request containing your question, use the `POST /2.0/docgen_templates` endpoint and provide the mandatory parameters. ### Parameters To make a call you need to pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Example | | --- | --- | --- | | file.id | ID of the file to be marked as the Box Doc Gen template. | 12345678 | | file.type | The type of provided input. The value is always file. | file | ## Use cases ### Mark a file as Box Doc Gen template The following sample show you how to mark a file to ensure it is recognized as a Box Doc Gen template. The file must be in `.docx` format. ### Remove Box Doc Gen template marking from a file To make sure a file is no longer marked as a Box Doc Gen template, use the `DELETE 2.0/docgen_templates/:template_id` request. **Reference:** https://developer.box.com/guides/docgen/mark-template/ --- ## Untitled *Type: guide | Category: Downloads * Download File To download a file, pass the GET /files/:id/content the ID of the file to get the content for. Download URL When not using the… # Download File To download a file, pass the [`GET /files/:id/content`](e://get_files_id_content) the ID of the file to get the content for. ## Download URL When not using the SDKs, this API call will return a `HTTP 302 Found` status code, with a `location` header containing a link to the download URL, which looks something like this. ``` https://dl.boxcloud.com/d/1/[long-random-string]/download ``` By using the `-L` flag in cURL we are able to automatically follow this redirect. In our SDKs this will result in the binary data to be downloaded. In the API this will result in a download URL being returned via the `location` header. It is possible to [get the download URL](g://downloads/get-url) via the SDKs as well. ## Download URL expiry Although this download URL can be passed to a user's browser to allow them to download the file, the URL does expire and should be requested again for any further downloads. ## File not ready If the file is not ready to be downloaded yet a `retry-after` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. **Reference:** https://developer.box.com/guides/downloads/file/ --- ## Untitled *Type: guide | Category: Downloads * Download File Version To download a specific file version, pass the GET /files/:id/content the ID of the file to get the content for, as… # Download File Version To download a specific file version, pass the [`GET /files/:id/content`](e://get_files_id_content) the ID of the file to get the content for, as well as its version ID. ## Download URL When not using the SDKs, this API call will return a `HTTP 302 Found` status code, with a `location` header containing a link to the download URL, which looks something like this. ``` https://dl.boxcloud.com/d/1/[long-random-string]/download ``` By using the `-L` flag in cURL we are able to automatically follow this redirect. In our SDKs this will result in the binary data to be downloaded. In the API this will result in a download URL being returned via the `location` header. It is possible to [get the download URL](g://downloads/get-url) via the SDKs as well. ## Download URL expiry Although this download URL can be passed to a user's browser to allow them to download the file, the URL does expire and should be requested again for any further downloads. ## File not ready If the file is not ready to be downloaded yet a `retry-after` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. **Reference:** https://developer.box.com/guides/downloads/file-version/ --- ## Untitled *Type: guide | Category: Downloads * Download All Files in Folder using SDKs Sometimes an application might want to download all files for a folder. To do so with the SDKs and… # Download All Files in Folder using SDKs Sometimes an application might want to download all files for a folder. To do so with the SDKs and the CLI requires traversing the folder tree, finding every file and downloading it accordingly. To download a ZIP archive, follow [this](g://downloads/zip-archive) guide. ``` using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Box.V2.Config; using Box.V2.JWTAuth; namespace BoxDownloadAllFiles { class Program { static void Main (string[] args) { ExecuteMainAsync ().Wait (); } private static async Task ExecuteMainAsync () { using (FileStream fs = new FileStream ($"./config.json", FileMode.Open)) { var session = new BoxJWTAuth (BoxConfig.CreateFromJsonFile (fs)); var client = session.AdminClient (session.AdminToken ()); var folderId = "987654321"; var folder = await client.FoldersManager.GetInformationAsync (folderId); var folderName = folder.Name; var localFolderPath = Path.Combine (Directory.GetCurrentDirectory (), folderName); ResetLocalFolder (localFolderPath); var items = await client.FoldersManager.GetFolderItemsAsync (folderId, 1000, autoPaginate : true); var fileDownloadTasks = new List<Task> (); var files = items.Entries.Where (i => i.Type == "file"); foreach (var file in files) { fileDownloadTasks.Add (client.FilesManager.DownloadStreamAsync (file.Id).ContinueWith ((t) => { var localFile = File.Create (Path.Combine (localFolderPath, file.Name)); return t.Result.CopyToAsync (localFile); })); } await Task.WhenAll (fileDownloadTasks); } } private static void ResetLocalFolder (string localFolderPath) { if (!Directory.Exists (localFolderPath)) { Directory.CreateDirectory (localFolderPath); } else { foreach (var file in Directory.EnumerateFiles (localFolderPath)) { File.Delete (Path.Combine (localFolderPath, file)); } Directory.Delete (localFolderPath); Directory.CreateDirectory (localFolderPath); } } } } ``` ``` package com.box; import com.box.sdk.BoxConfig; import com.box.sdk.BoxDeveloperEditionAPIConnection; import com.box.sdk.BoxFile; import com.box.sdk.BoxFolder; import com.box.sdk.BoxItem; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Playground { public static void main(String[] args) throws Exception { Path configPath = Paths.get("config.json"); Path currentDir = Paths.get("").toAbsolutePath(); try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) { BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection client = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig); String folderId = "987654321"; BoxFolder folder = new BoxFolder(client, folderId); String folderName = folder.getInfo().getName(); Path localFolderPath = currentDir.resolve(Paths.get(folderName)); if (!Files.exists(localFolderPath)) { localFolderPath = Files.createDirectory(localFolderPath); } else { localFolderPath = resetLocalFolder(localFolderPath); } for (BoxItem.Info itemInfo: folder) { if (itemInfo instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; BoxFile file = new BoxFile(client, fileInfo.getID()); String localFilePath = localFolderPath.resolve(Paths.get(fileInfo.getName())).toAbsolutePath().toString(); FileOutputStream stream = new FileOutputStream(localFilePath); file.download(stream); stream.close(); } } } } static Path resetLocalFolder(Path localFolderPath) throws IOException { Files.list(localFolderPath).forEach(file -> { System.out.println(file.getFileName()); try { Files.delete(file.toAbsolutePath()); } catch (IOException e) {} }); Files.delete(localFolderPath); localFolderPath = Files.createDirectory(localFolderPath); return localFolderPath; } } ``` ``` "use strict"; const box = require("box-node-sdk"); const fs = require("fs"); const util = require("util"); const path = require("path"); let configFile = fs.readFileSync("config.json"); configFile = JSON.parse(configFile); let session = box.getPreconfiguredInstance(configFile); let client = session.getAppAuthClient("enterprise"); client._useIterators = true; let folderId = "987654321"; let folderName; let localFolderPath; client.folders .get(folderId, null) .then(folderInfo => { folderName = folderInfo.name; return client.folders.getItems(folderId, { limit: 1000 }); }) .then(folderItemsIterator => { return autoPage(folderItemsIterator); }) .then(folderItems => { console.log(folderName); console.log(folderItems.length); let files = folderItems.filter(item => { return item.type === "file"; }); console.log(files); localFolderPath = createLocalFolder(folderName); let downloadPromises = []; files.forEach(file => { downloadPromises.push( client.files.getReadStream(file.id, null).then(stream => { let output = fs.createWriteStream( path.join(localFolderPath, file.name) ); stream.pipe(output); }) ); }); return Promise.all(downloadPromises); }) .then(() => { console.log("Downloaded all files..."); console.log(fs.readdirSync(localFolderPath)); }); function createLocalFolder(folderName) { let localFolderName = path.join(__dirname, folderName); try { fs.mkdirSync(localFolderName); } catch (e) { if (e.code === "EEXIST") { resetLocalFolder(localFolderName); fs.mkdirSync(localFolderName); } else { throw e; } } return localFolderName; } function resetLocalFolder(localFolderName) { if (fs.existsSync(localFolderName)) { fs.readdirSync(localFolderName).forEach(localFileName => { console.log(localFileName); fs.unlinkSync(path.join(localFolderName, localFileName)); }); fs.rmdirSync(localFolderName); } } function autoPage(iterator) { let collection = []; let moveToNextItem = () => { return iterator.next().then(item => { if (item.value) { collection.push(item.value); } if (item.done !== true) { return moveToNextItem(); } else { return collection; } }); }; return moveToNextItem(); } ``` It is important to remember that an application needs to have the permissions to access and download the files and folders in question. When the authenticated user does not have access to any of the files or folders, a `HTTP 404 Not Found` error will occur. Lear more about [User Types](page://platform/user-types) in our guides on authentication. **Reference:** https://developer.box.com/guides/downloads/folder/ --- ## Untitled *Type: guide | Category: Downloads * Get Download URL The official Box SDKs return the binary data when downloading a file. To get the download URL for the data instead, use the… # Get Download URL The official Box SDKs return the binary data when downloading a file. To get the download URL for the data instead, use the following SDK methods. # Redirects If you are not using one of our SDKs its important to make sure your HTTP client does not automatically follow HTTP redirects. When redirects are automatically followed, your code will detect the `location` header returned by the API and follow it to get the binary data. ## Download URL expiry Although this download URL can be passed to a user's browser to allow them to download the file, the URL does expire and should be requested again for any further downloads. In most cases the download URL is valid for 15 minutes, after which a new URL needs to be requested. This expiration time may be subject to change without any prior notification. **Reference:** https://developer.box.com/guides/downloads/get-url/ --- ## Untitled *Type: guide | Category: Downloads * Download in Browser Sometimes an application wants to embed a file into a page as a HTML element. An example would be when working with an… # Download in Browser Sometimes an application wants to embed a file into a page as a HTML element. An example would be when working with an audio player. ``` <audio controls> <source src="..." type="audio/mp3"> </audio> ``` In this case, using the regular [download URL](g://downloads/get-url) does not work because the `dl.boxcloud.com` domain does not support [Cross Origin Resource Sharing](g://security/cors). Instead an application can use the following format. ``` https://api.box.com/2.0/files/[FILE_ID]/content?access_token=[ACCESS_TOKEN] ``` # CORS For this to work the application needs to have the domain of the web site hosting this file added to the list of allowed domains in the CORS settings. # Downscope Token Using this method would expose the Access Token to the end user, allowing them to potentially use this token to do more than intended. For this reason we recommend [downscoping](g://authentication/tokens/downscope) this token accordingly. **Reference:** https://developer.box.com/guides/downloads/in-browser/ --- ## Untitled *Type: guide | Category: Downloads * Downloads The Box API allows for downloading files to the application's server, or directly by the end user in a browser. When not to… # Downloads The Box API allows for downloading files to the application's server, or directly by the end user in a browser. ## When not to download Downloading a file is not always the desired solution, especially if the file is only being downloaded for the user to preview, comment, or annotate. In those cases we recommend using one of the ways to embed the Box experience straight into your application. Learn more about embedding Box ## Access Errors It is important to realize that the application needs to have access to the file that is to be downloaded. When the application is a authenticated through JWT or App Tokens, the user is authenticated as a Service Account. This service account does not have access to files besides their own. If this user does not have access to the file the application will receive a `404 Not Found` error. Learn more about different User Types **Reference:** https://developer.box.com/guides/downloads/ --- ## Untitled *Type: guide | Category: Downloads * Download Shared Link To download the file for a Shared Link, first determine the file for the link. You cannot use the shared link to… # Download Shared Link To download the file for a [Shared Link](g://shared-links), first determine the file for the link. You cannot use the shared link to download folders. Create and download the ZIP archive instead. Once the file ID has been determined, the file can be downloaded by passing the `BoxAPI` header to the API. To get the Shared Link for an item the user must have at least viewer-level access to the item. **Reference:** https://developer.box.com/guides/downloads/shared-link/ --- ## Untitled *Type: guide | Category: Downloads * Download ZIP Archive To download all files in a folder or an entire folder structure, you have to create and download a ZIP archive. Create… # Download ZIP Archive To download all files in a folder or an entire folder structure, you have to create and download a ZIP archive. ## Create a ZIP Archive First, you need to create a ZIP archive containing the files or the folder structure. You can include up to 10,000 file and folder IDs unless you reach the account’s upload limit. The response will look similar to the following: ``` { "download_url": "https://dl.boxcloud.com/2.0/zip_downloads/25gvaXcIE4QJlinNiw2oHAQ==ZFs3Q2Xpd7pKBz7OyzXNrUaoW3aJxQRN5znAvyM-KpdEEPdWcQDKU-Dl85Ew/content", "status_url": "https://api.box.com/2.0/zip_downloads/25gvaXcIE4QJlinNiw2oHAQ==ZFs3Q2Xpd7pKBz7OyzXNrUaoW3aJxQRN5znAvyM-KpdEEPdWcQDKU-Dl85Ew/status", "expires_at": "2023-02-28T10:23:54Z", "name_conflicts": [] } ``` ## Extract the ZIP download ID To download the ZIP archive, you need the ZIP download ID. You can find it in the response you got when you created the archive. Go to `status_url` and copy the ID located between`zip_downloads` and `content`: ``` 25gvaXcIE4QJlinNiw2oHAQ==ZFs3Q2Xpd7pKBz7OyzXNrUaoW3aJxQRN5znAvyM-KpdEEPdWcQDKU-Dl85Ew ``` Download URL is valid only for a the time specified in `expires_at` parameter. ## Download files Place the download ID in the file location URL as in the sample below to point to the right files. For downloads that take longer, you can monitor the download status using the [status endpoint](e://get-zip-downloads-id-status). This allows you to inspect the progress of the download as well as the number of items that might have been skipped. If you want to use SDKs to download the contents of the folder, follow [this](g://downloads/folder) guide. **Reference:** https://developer.box.com/guides/downloads/zip-archive/ --- ## Untitled *Type: guide | Category: Events * Events The event feed provides a way for an application to subscribe to any actions performed by any user, users, or service in an… # Events The event feed provides a way for an application to subscribe to any actions performed by any user, users, or service in an enterprise. ## User vs Enterprise events Depending upon the `stream_type`, the [`GET /events`](e://get_events) API enables subscribing to live events across the enterprise or for a particular user, or querying historical events across the enterprise. ### User events User events provides a low latency stream of events relevant to the currently authenticated user. This event stream is how Box keeps [Box Drive](https://www.box.com/drive) up to date, but is also made available for developer use. The emphasis of this feed is to return the complete results quickly, which means that Box may return events more than once or out of chronological order. Duplicate events can be identified by their event IDs. Unlike the enterprise events streams, the user events stream does not support filtering for specific events. The three user events stream_types return slightly different subsets of the user events dataset for different purposes. | Stream Type | | | --- | --- | | all | Returns everything for a user (default) | | changes | Returns events that may cause file tree changes such as file updates or collaborations | | sync | Is similar to changes but only applies to synced folders | ### Enterprise events Enterprise events provide an event feed for all users and content in an enterprise Box instance. Depending upon the `stream_type` your application can either subscribe to live events or query historical events. Access to these stream types is limited to users with admin permissions to **Run new reports and access existing reports**. Unlike the user events stream, the enterprise events stream supports filtering based on event type but does not support long polling. Across the two stream types the dataset is exactly the same. Events can be deduplicated across the two stream types using their event IDs. | Stream Type | | | --- | --- | | admin_logs | Enables querying historical events up to one year | | admin_logs_streaming | Enables subscribing to live events in near real time | #### Live Monitoring To monitor recent events that have been generated within Box across the enterprise, set the `stream_type` to `admin_logs_streaming`. This is also known as the Enterprise Event Stream API. The emphasis for this feed is on low latency rather than chronological accuracy, which means that Box may return events more than once and out of chronological order. Events are returned via the API in near real time after they are processed by Box. A small delay/buffer ensures that new events are not written after your cursor position. Only two weeks of events are available via this `stream_type`. #### Historical Querying To query historical events across the enterprise up to one year old, set the `stream_type` to `admin_logs`. This is also known as the Enterprise Event History API. The emphasis for this feed is on completeness over latency, which means that Box will deliver admin events in chronological order and without duplicates, but with higher latency than the user or `admin_logs_streaming` feed. Consuming events in near real time may lead to missed events as events can arrive later than your filtering window. **Reference:** https://developer.box.com/guides/events/ --- ## Untitled *Type: guide | Category: Embed Box * Box Embed Box Embed is a HTML-based framework that allows embedding the entire Box Web App experience in a custom-made application. Box… # Box Embed Box Embed is a HTML-based framework that allows embedding the entire Box Web App experience in a custom-made application. Box Embed provides the ability to upload, search, comment, share, tag, and edit files using Box Edit. ## Before you start To create a widget, you need to: - Set an embeddable element, such as a **folder**, **file**, **Hub**, **note**, or **app** for sharing. - Have at least **Viewer** [permissions](https://support.box.com/hc/en-us/articles/360044196413-Understanding-Collaborator-Permission-Levels). ## Using web app To fetch the Box Embed widget code from the Box web app, perform the following steps. ### Files and folders 1. Navigate to the chosen file or folder. 2. Click on the ellipsis next to the folder. 3. Go to **More Actions** > **Embed Widget**. ### Hubs 1. Navigate to the chosen Hub. 2. Click on the ellipsis menu in the top right corner. 3. Click **Embed Hub**. ### Notes 1. Navigate to the chosen Box Note. 2. Click on the ellipsis menu. 3. Click **Embed Box Note**. ### Apps 1. Navigate to the chosen Box App or Box App View. 2. Click on the ellipsis menu. 3. Click **Embed**. In the next step, configure the parameters of an embeddable element. | Files | Folders | Hubs | Notes | Apps | | --- | --- | --- | --- | --- | | Size of the widget. | Size of the widget, sorting of the files in a folder, hiding the navigation path and sidebar. | Size of the widget, hiding the parent navigation path and sidebar. | Size of the widget, skipping cloud game (results in note being in read only mode), hiding notes navigation. | Size of the widget. | When you are done customizing the embed widget, copy and paste the embed code into your site or web application. ## Programmatically If you want to customize Box Embed even further, you can do it programmatically. The format for an embed snippet is as follows: ``` <iframe src="https://{custom_domain}.app.box.com/embed/s/{shared link value}?view={list or icon}&sortColumn={name, date, or size}&sortDirection=ASC" width="{pixels}" height="{pixels}" frameborder="0" allowfullscreen webkitallowfullscreen msallowfullscreen ></iframe> ``` ### Finding your shared link value The first step to building an embed `iframe` programmatically is to generate or find the value for the shared link. One way to find this value is by using the Box web app. Another way is to create a shared link with API using the [`PUT /files/:file_id`](e://put-files-id--add-shared-link) or [`PUT /files/:file_id`](e://put-folders-id--add-shared-link). Then you can find this shared link value using the [`GET /files/:id`](e://get-files-id) or [`GET /folders/:id`](e://get-folders-id) endpoint and passing in the query parameter `fields=shared_link`. ``` curl https://api.box.com/2.0/folders/12345?fields=shared_link \ -H "authorization: Bearer ACCESS_TOKEN" ``` ``` "shared_link": { "url": "https://app.box.com/s/dsbJFzdO7qZxdfOHFzdO7qZxdfOH", "download_url": null, "vanity_url": null, ... } ``` You can also set the page to Root Folder/All Files page. Set the URL to `/folder/0` instead of the share link: `<iframe src=“https://app.box.com/embed/folder/0”….></iframe>` ### Parameters Next, you will want to choose your view customization options. The following is a list of optional parameters you can configure. | | | | --- | --- | | hideHubsGallery | Hide or show navigation chevron button to go back to Hubs gallery. Can be true or false (default). | | hideNavigationControls | Hide or show navigation controls in Box Notes. | | showItemFeedActions | Hide or show file comments or tasks. Can be true (default) or false. | | showParentPath | Hide or show the folder path in the header of the frame. Can be true or false (default). | | sortColumn | The order the files or folders are sorted in. Can be name, date (default), or size. | | sortDirection | The sort direction of files or folders. Can be ASC (default) or DESC. | | view | The view type for your files or folders. Can be list (default) or icon. For logged-in users the view type from user preferences takes precedence. | | uxLite | Show the limited content preview (Preview Light), with no cloud game. Works only for shared files and Box Notes. | When you use `uxLite` with Box Notes, navigation controls are not displayed, regardless of the `hideNavigationControls` setting. All custom search parameters from the first-party app URL are passed to the embed widget modal and Content Preview. ### Full screen capabilities To enable full screen capabilities for the Box Embed snippet, include one or more of the following parameters if you want the object to be viewable in full screen within an `<iframe>`: - `allowfullscreen` - `webkitallowfullscreen` - `mozallowfullscreen` - `oallowfullscreen` - `msallowfullscreen` ## Expiring embed links For files, another option is to call the [`GET /files/:id`](e://get-files-id) and request an `expiring_embed_link` using the `fields` query parameter. ``` curl https://api.box.com/2.0/files/12345?fields=expiring_embed_link \ -H "authorization: Bearer ACCESS_TOKEN" ``` ``` { "etag": "1", "expiring_embed_link": { "token": { "access_token": "1!rFppcinUwwwDmB4G60nah7z...", "expires_in": 3646, "restricted_to": [ { "object": { "etag": "1", "file_version": { "id": "34567", "sha1": "1b8cda4e52cb7b58b354d8da0068908ecfa4bd00", "type": "file_version" }, "id": "12345", "name": "Image.png", "sequence_id": "1", "sha1": "1b8cda4e52cb7b58b354d8da0068908ecfa4bd00", "type": "file" }, "scope": "base_preview" }, ... ], "token_type": "bearer" }, "url": "https://cloud.app.box.com/preview/expiring_embed/...." }, "id": "12345", "type": "file" } ``` The `url` attribute can be used in an `<iframe>` to embed an auto expiring Box Embed interface. ``` <iframe src="YOUR-GENERATED-BOX-EMBED-LINK" width="{pixels}" height="{pixels}" frameborder="0" allowfullscreen webkitallowfullscreen msallowfullscreen /> ``` ### Parameters Extra parameters can be added to this URL as well to customize the UI. To do so, add the following parameters to the `url` as query parameters. The eventual URL would look something like this. ``` https://app.box.com/preview/expiring_embed/[HASH]?[parameterName]=true ``` | | | | --- | --- | | showDownload | Shows the download button in the embedded header bar if the viewer has permissions to download the file. Document file types will also show a print button since print and download are governed by the same permissions. Defaults to false. | | showAnnotations | Enables users with permission Preview and above to annotate document and image previews. Also shows annotations that are already on the document. To learn more about the file types that annotations is available on as well as the types of annotations, you can refer to our Annotations page. Annotations are available today on web browsers only. On mobile browsers, users will be able to view annotations but not create new ones. | ## Cloud game The cloud game is a widget created to prevent [clickjacking](https://support.box.com/hc/en-us/articles/360043691034-How-Does-Box-Prevent-Clickjacking). It's shown for embedded sites that aren’t partner integrations. In cloud game, user must drag a cloud to the correct location before an interaction is allowed. It makes clickjacking difficult, as the position of the cloud and its destination are randomly generated. `postMessage()` is used on the iframe to retrieve both the embed and the `showCloudGame` status. If embedded, `document.hasStorageAccess()` shows if Box has access to cookies. If yes and the user is logged in, the cloud game is displayed. If the `showCloudGame` status is `false`, user is navigated to the login page. ## Custom logo Paid Box customers have the option to remove the Box logo in the file Preview. To do so, visit the **Admin Console**, **Enterprise Settings**, Custom Setup and toggle the **Embed widget customization** off to hide the Box logo. ## Limitations Box Embed is not optimized for mobile browsers and should not be used in web experiences designed for mobile devices. Many UI elements, like the **download** and **print** options might not show in mobile browsers. **Reference:** https://developer.box.com/guides/embed/box-embed/ --- ## Untitled *Type: guide | Category: Embed Box * Embed Box Box supports a few different ways to embed files and folders straight into your front-end application. # Embed Box Box supports a few different ways to embed files and folders straight into your front-end application. **Reference:** https://developer.box.com/guides/embed/ --- ## Untitled *Type: guide | Category: Files * Get File Information To get a file's information, not it's content, call the GET /files/:id API with the id of the file. File ID The id for… # Get File Information To get a file's information, not it's content, call the [`GET /files/:id`](e://get-files-id) API with the `id` of the file. ## File ID The `id` for any file can be determined by visiting a file in the web application and copying the `id` from the URL. For example, for the URL `https://*.app.box.com/file/123` the `file_id` is `123`. ## Additional fields To get more of the fields for a file, make sure to pass along the `fields` query parameter. Learn about requesting extra fields **Reference:** https://developer.box.com/guides/files/get/ --- ## Untitled *Type: guide | Category: Files * Files Files, together with Folders, are at the core of the Box API. Files can be uploaded and downloaded, as well as hold important metadata… # Files Files, together with [Folders](g://folders), are at the core of the Box API. Files can be [uploaded](g://uploads) and [downloaded](g://downloads), as well as hold important metadata information about the content. **Reference:** https://developer.box.com/guides/files/ --- ## Untitled *Type: guide | Category: Files * Limitations A few limitations exists when working with files. Name restrictions There are some restrictions to a file's name. Names… # Limitations A few limitations exists when working with files. ## Name restrictions There are some restrictions to a file's name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), and protected names like `.` and `..` are automatically sanitized by removing the non-allowed characters. **Reference:** https://developer.box.com/guides/files/limitations/ --- ## Untitled *Type: guide | Category: File Requests * Copy a File Request To create a copy of an existing template file request, all you need is its unique ID, and the ID of the folder to apply… # Copy a File Request To create a copy of an existing [template](g://file-requests/template) file request, all you need is its unique ID, and the ID of the folder to apply the new file request to. The ID of a folder and file request can be determined by visiting the Box web app and inspecting the URL. The folder ID is the number at the end of the URL when visiting a folder, for example `app.box.com/folder/123` is the URL for the folder with ID `123`. For a file request, please [check our guide](g://file-requests/template) on setting up a file request template to learn how to determine a file request ID. ## Updating a file request on copy It is possible to make some basic changes to a file request when copying from a template. The file request's title, description, status and a few more other settings can be updated when the file request is copied from the template. ``` curl -i -X POST "https://api.box.com/2.0/file_requests/2342235/copy" \ -H "Authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "title": "Please upload required documents", "description": "Please upload required documents", "status": "active", "is_email_required": true, "is_description_required": false, "folder": { "id": "342323423" } }' ``` For more details on the different fields that can be updated when creating a template, please see the reference documentation for the [`POST /file-requests/:id/copy`](e://post_file_requests_id_copy) API. **Reference:** https://developer.box.com/guides/file-requests/copy/ --- ## Untitled *Type: guide | Category: File Requests * Delete a File Request To delete a file request, all you need is its unique ID. The ID of a file request can be determined by visiting the… # Delete a File Request To delete a file request, all you need is its unique ID. The ID of a file request can be determined by visiting the Box web app and inspecting the URL. Please [check our guide](g://file-requests/template) on setting up a file request template to learn how to determine a file request ID. **Reference:** https://developer.box.com/guides/file-requests/delete/ --- ## Untitled *Type: guide | Category: File Requests * Get information for a File Request To get details about an existing file request, all you need is its unique ID. The ID of a file request… # Get information for a File Request To get details about an existing [file request](g://file-requests/template), all you need is its unique ID. The ID of a file request can be determined by visiting the Box web app and inspecting the URL. Please [check our guide](g://file-requests/template) on setting up a file request template to learn how to determine a file request ID. **Reference:** https://developer.box.com/guides/file-requests/get/ --- ## Untitled *Type: guide | Category: File Requests * File Requests Box File Request gives you a fast and secure way to request files and associated metadata from anyone. Using a drag-and-drop… # File Requests Box File Request gives you a fast and secure way to request files and associated metadata from anyone. Using a drag-and-drop graphic interface, you can create a web form that enables you to: - Securely request files from anyone, no matter whether they have a Box account, without adding collaborators on a folder. - Solicit additional information with metadata form fields, which you can set as required/optional. - Enable extra security and tracking with link settings. - Kick off automated workflows using Box Relay. The **File Request API** gives you the power to create new file requests based on an existing file request, update file request settings, activate and deactivate, and delete file requests programmatically. ## Use Cases The File Request API is especially useful in situations where folders are automatically created when a new case, project, or customer is created in an external system. For each of these folders a file request can be automatically generated, allowing customers and other users to upload documents to the project. For example. - **Case management** - In this situation each customer support case has its own associated folder and a new file request can be sent out to a customer, requesting them to submit case related documents to the folder. - **Project management** - In this situation each project has its own associated folder for each project defined in an external system. The API can be used to automatically create a **"Client Documents"** folder within this folder, and a link can be sent to the client to allow them to upload documents on demand. - **Employee "drop" folder** - In this situation every new loan advisor in a bank has a personal folder in Box. To help them work with their clients a "drop" subfolder is automatically generated for them with an associated file request, allowing their clients to automatically upload documents to their advisor's personal folder. ## Limitations Currently, the API only allows the creation of new file requests by copying an existing file request associated to another folder. Please check our guide to create a template folder with a template file request. **Reference:** https://developer.box.com/guides/file-requests/ --- ## Untitled *Type: guide | Category: File Requests * Create a template File Request Currently, the API only allows the creation of new file requests by copying an existing file request… # Create a template File Request Currently, the API only allows the creation of new file requests by copying an existing file request associated to another folder. Please check our below guide on creating a template folder with a template file request. ## 1. Template folder First off, create a template folder that you can associate the template file request to. This can be any folder really, but we recommend using a folder that is only used for this purpose. A folder can be created through the Box web or mobile interface, or through the [`POST /folders`](e://post_folders) API. When using server-side JWT authentication, we recommend creating folder that is owned by the application's [Service Account](page://platform/user-types/#service-account). This way, the folder can't be accidentally deleted by a regular Box user. ## 2. Template file request To create a file request, navigate to the template folder in the web app an d click the 3 dots at the top of the page. Then, select **File Request** from the menu. In the next configuration panel, click the **Edit** button to visit the file request configuration page. On the configuration page, you can set configure the title and description, before saving the page. This page will also have the ID of the file request in the URL. Make a note of the URL as the number at the end is the file request's ID, which you will need when working with the API. ``` https://*.app.box.com/filerequest/2338423584 ``` If your template folder belongs to a JWT user, you will need to [invite](e://post-collaborations) a managed Box user to the folder before it can be seen in the web app. Invite yourself to the folder to allow yourself to add a file request to the folder via the app. ## 3. Using a template A template file request can be used to create new copies using the [`POST /file-requests/:id/copy`](e://post_file_requests_id_copy) API. With the ID of a new folder in hand, you can copy the existing request, including its title, description and form-configuration to a new folder [with one API call](g://file-requests/copy). **Reference:** https://developer.box.com/guides/file-requests/template/ --- ## Untitled *Type: guide | Category: Folders * Folders Folders, together with Files, are at the core of the Box API. Folders can be uploaded and downloaded, as well as hold important… # Folders Folders, together with [Files](g://files), are at the core of the Box API. Folders can be uploaded and downloaded, as well as hold important metadata information about the content. **Reference:** https://developer.box.com/guides/folders/ --- ## Untitled *Type: guide | Category: Start Here * Create your first application Once you have your Developer Enterprise set up, you can start creating applications. Click the Dev Console… # Create your first application Once you have your Developer Enterprise set up, you can start creating applications. Click the [Dev Console](https://cloud.app.box.com/developers/console) button once you're logged in to your Developer Enterprise. If this is your first application, you will be prompted to get started. ## Choose application type The first step is to select the application type you want to create. In this guide we use the **Platform App** option, as most of our partners use this type for their integrations. ## Choose the authentication method After you choose the **Platform App**, you need to select an authentication method that your app will use. In this guide we use the [**User Authentication (OAuth 2.0)**](g://authentication/oauth2) option, as most of our partners use this type for their integrations. ## Name the app Choose an app name. It can be changed later on and it is not publicly visible until you publish your app. We recommend choosing a name that is recognizable, as the admins and customers will see the name of the app when it's published. Click the **Create App** button to finish creating your app. Next, configure the application settings. ## General settings Begin with the most basic settings. Open the **General Settings** tab and check or fill in below fields: - **App Name** - the name you set up during the app creation, you can change it here if needed; - **Contact Email** - this is set to the developer of the application by default. Keep in mind that once you publish your app, this email is publicly visible to Box users who view your app in the [Integrations](g://applications/integrations). We recommend to change it to a support email address, so that users can reach out to support in case of any issues with the integration; - **Collaborators** - add other developers that can work on this integration, so that they can access the developer interface in case they need to adjust any settings. The developers you add here need to be Box users already. If they don't have Box account, you can [create them](https://support.box.com/hc/en-us/articles/360043694594-Add-Users) in your Developer Enterprise. ## Advanced settings Go to the **Configuration** tab. Here you can specify the app details, generate a developer token, check your OAuth 2.0 credentials, add and edit OAuth 2.0 redirect URI, choose the application scopes, set app advanced features, and add CORS domains. In the next tabs you can create webhooks, web app integrations, submit app for enablement for access to the Enterprise, submit your app to the [Box Integrations](g://applications/integrations), and generate a report to view this application’s activity. ## Test your app You can now make some API calls to test your app and get to know the response format in Box. Use the [developer token](g://authentication/tokens/developer-tokens/#create-developer-token) authenticated to your current developer account. This token is valid for an hour from being generated. Start with the [Postman collection](g://tooling/postman) to check specific calls and see what responses they return. To see example API calls, browse our [API reference documentation](page://reference). You can also use [Box CLI tool](https://github.com/box/boxcli) if you prefer to use the terminal. **Reference:** https://developer.box.com/guides/getting-started/first-application/ --- ## Untitled *Type: guide | Category: File Requests * Update a File Request To update some of the basic details for an existing file request, all you need is its unique ID. For more details on… # Update a File Request To update some of the basic details for an existing file request, all you need is its unique ID. For more details on the different fields that can be updated when creating a template, please see the reference documentation for the [`POST /file-requests/:id/update`](e://put_file_requests_id) API. The ID of a file request can be determined by visiting the Box web app and inspecting the URL. Please [check our guide](g://file-requests/template) on setting up a file request template to learn how to determine a file request ID. **Reference:** https://developer.box.com/guides/file-requests/update/ --- ## Untitled *Type: guide | Category: Start Here * Start Here Our documentation is divided into five main sections: Learn Box Platform: A getting started walk through of all things Platform… # Start Here Our documentation is divided into five main sections: - **Learn Box Platform**: A getting started walk through of all things Platform. - **Developer Guides**: In-depth documentation on developer portal, API working, usage of Box functionalities. - **API Reference**: A list of API endpoints and resources, with request and response examples. - **SDK and Tools**: A list of official Box SDKs and tools. - **Sample Code Catalog**: Consolidated list of several code repositories. If you are new to development with the Box API, first familiarize yourself with the content in the [Learn Box Platform](page://platform) section. In this section, you will: - learn the [Box Platform concepts](page://platform/box-platform-101), - evaluate if your [use case](page://platform/use-cases) is a good fit for Box, - understand the different [types of Box users](page://platform/user-types), - select the applicable [application type](page://platform/application-types), - check the available [authentication methods](page://platform/authentication-methods) and choose the best one for your use case, - find out where you can get [support](page://platform/support), - check the [tools](page://platform/tools) needed for developing applications in Box. After learning the basics, we recommend you to follow the steps below. 1. Create your first [Box application](g://getting-started/first-application). 2. Configure your application. 3. Explore [endpoints](page://reference) and make API calls using [common values](page://platform/appendix/locating-values). 4. [Publish](g://getting-started/publish-app) your application. If you have any questions, checkout our [forum](https://forum.box.com). **Reference:** https://developer.box.com/guides/getting-started/ --- ## Untitled *Type: guide | Category: Start Here * Publish your app When you finish the platform app configuration and testing, you can publish it in the Box Integrations. It allows customers… # Publish your app When you finish the platform app configuration and testing, you can publish it in the [Box Integrations](https://cloud.app.box.com/integrations). It allows customers to find your app and add it to their Box accounts. Only apps that use the OAuth 2.0 authentication have a built-in publication option. In case you use a different auth type for your integration, you can still create and publish an OAuth 2.0 platform app that will serve as a marketing listing in the **Integrations** and redirect customers to your website. To publish your platform app: Open the **Dev Console**. Select the platform app you want to publish. Go to the **Publishing** tab. Read through the submission checklist and check the confirmation checkbox if your app meets all the requirements. The next step is the marketing section of the app, where you need to add the following app information: - **General Info** - choose correct categories and platforms for your app to make it easier to find in the Integrations, **Description** - make sure it contains all information about your app that the customers may find useful, - **Short Description** appears next to your app logo, together with your app name; - **Long Description** is what the users see after they select your app to view its details. You can add clickable links to the long description. 1. **Screenshots** and **Icon** - provide the screenshots to allow the users see how the app looks like and how it integrates with Box. The icon is needed to represent your app in the list of Integrations. 2. **Support Resources** - A list of links and supplementary information that will help the users to work with your app. Before submitting your app, preview it to see if you included all the necessary information. Submit your app for approval. Box will review your app and publish it under **Integrations**. If you have any questions or issues, contact the **Partners** team: [`integrate@box.com`](mailto:integrate@box.com). **Reference:** https://developer.box.com/guides/getting-started/publish-app/ --- ## Untitled *Type: guide | Category: Start Here * Sandboxes in Box Platform Developer sandboxes in Box provide a secure, controlled environment where developers can build, test, and… # Sandboxes in Box Platform Developer sandboxes in Box provide a secure, controlled environment where developers can build, test, and collaborate on applications without affecting the actual data of your enterprise. They offer a safe space to experiment with Box APIs, test settings, try new integrations, and work alongside external partners. ## What is a developer sandbox A developer sandbox is an environment isolated from your production (live) enterprise setup that keeps development activities separate from real business data. ## Why use a sandbox Using a sandbox allows you to: - Safely build apps within an enterprise-linked environment instead of a free standalone account. - Collaborate securely with both internal teams and external collaborators. Contractors, partners, and other external users can join the sandbox without accessing live systems and compromising security. - Test apps under realistic testing conditions, as sandboxes inherit your enterprise's plan and add-ons at creation time. If there are any changes to the plan or add-ons, they can be [manually synced](https://support.box.com/hc/en-us/articles/360043697274-Managing-developer-sandboxes-for-Box-admins#:~:text=in%20a%20sandbox.-,Synchronizing,-sandbox%20with%20production) by an enterprise admin. ## Accessing your sandbox Sandboxes in Box are created by enterprise admins. See [this document](https://support.box.com/hc/en-us/articles/360043697274-Managing-developer-sandboxes-for-Box-admins) to learn how to create a sandbox. When you are assigned as a primary admin of a sandbox, you receive a log-in email from Box with your sandbox user ID. To access the [Dev Console](https://cloud.app.box.com/developers/console) inside the sandbox environment and set up a password, click the link in the email. You can also access your sandbox by logging in with your sandbox credentials on [developer.box.com](https://developer.box.com). The sandbox's primary admin can create individual sandbox accounts, giving developers access to a new Box environment that matches the plan of their parent Box enterprise. ### Accessing multiple sandboxes As a primary admin, you can log into multiple sandboxes. If you want to use this functionality for existing sandboxes, you can remove the unique email address and get a system generated email. **Reference:** https://developer.box.com/guides/getting-started/sandbox/ --- ## Untitled *Type: guide | Category: Integration Mappings * Integration Mappings With Integration Mappings, you can manage where content from partner apps is stored in Box. # Integration Mappings With [Integration Mappings](r://integration-mappings), you can manage where content from partner apps is stored in Box. **Reference:** https://developer.box.com/guides/integration-mappings/ --- ## Untitled *Type: guide | Category: Legal Holds * Get Legal Hold Policy To get the information for a specific Legal Hold policy that has been created in an enterprise, call the GET /legal… # Get Legal Hold Policy To get the information for a specific Legal Hold policy that has been created in an enterprise, call the [`GET /legal_hold_policies/:id`](e://get_legal_hold_policies_id) API endpoint with the `id` of the policy. ## Required Scopes Before using any of the Legal Hold APIs, an application must have the right scopes enabled. See [Required Scopes](g://legal-holds#required-scopes) for more details. **Reference:** https://developer.box.com/guides/legal-holds/get/ --- ## Untitled *Type: guide | Category: Legal Holds * Legal Holds A legal hold is a process that an enterprise can use to preserve all forms of potentially relevant information when litigation… # Legal Holds A legal hold is a process that an enterprise can use to preserve all forms of potentially relevant information when litigation is pending or reasonably anticipated. Applying a hold to items prevents any user from deleting them from Box. Legal Holds can be managed and assigned to folders and files through the Box APIs. Legal Holds are a feature of the [Box Governance](https://www.box.com/security/governance-and-compliance) package, which can be added on to any Business Plus, Enterprise Advanced or Enterprise account. ## Policies, Assignments, and Holds Working with Legal Hold Policies requires a developer to work with three distinct resources. - **Policies:** A [Legal Hold Policy](r://legal_hold_policy) describes the general behavior of the hold. It determines which files should be affected, based on the date and time the files were created or updated. - **Assignments:** A [Legal Hold Policy Assignment](r://legal-hold-policy-assignment) is a relation between a policy and custodian. In this case, as custodian can be a user, folder, file, or file version. Creating an assignment puts a hold on all the file versions that belong to the custodian. For example, if an assignment is created on a folder the policy is applied to all file versions within that folder. - **Holds**: A [File Version Legal Hold](r://file_version_legal_hold) represents all the policies that are assigned to a specific file version. Note that every file version can have a maximum of one file version legal hold and this hold contains a list of every assigned policy. ## Example Use Case If an order of discovery is received or the customer is part of an ongoing litigation, a legal hold policy can be created to keep track of everything that needs to be held. The actual holding is done by assigning a policy to a specific files or folder. When the holds are no longer needed, the policy can be released by deleting the assignment. ## Required Scopes Before using any of the Legal Hold APIs, an application must have the GCM and Manage Legal Hold scopes enabled. These are not available in the Developer Console and need to instead be enabled by contacting customer support. **Reference:** https://developer.box.com/guides/legal-holds/ --- ## Untitled *Type: guide | Category: Legal Holds * List All Legal Hold Policies To list all Legal Hold Policies that have been created in an enterprise, call the GET /legal_hold_policies API… # List All Legal Hold Policies To list all Legal Hold Policies that have been created in an enterprise, call the [`GET /legal_hold_policies`](e://get_legal_hold_policies) API endpoint. ## Required Scopes Before using any of the Legal Hold APIs, an application must have the right scopes enabled. See [Required Scopes](g://legal-holds#required-scopes) for more details. **Reference:** https://developer.box.com/guides/legal-holds/list/ --- ## Untitled *Type: guide | Category: Metadata * Classifications Box enables users and applications to apply a security classification label to files, and cascade a classification label to… # Classifications Box enables users and applications to apply a security classification label to files, and cascade a classification label to folders and their contents. Classifications help protect shared sensitive content from negligent access through Box's Governance and Shield products. The Classification API can be used to create new classification labels and to assign classifications to files and folders. Classifications use the [Metadata APIs](g://metadata) to create classification labels, and to assign classifications to files and folders. For more details on metadata templates and instances, please explore our guides on [Metadata](g://metadata). ## Classifications & Metadata Working with classifications requires a developer to work with metadata templates and instances. - **The Classification Template:** to work with classifications, an enterprise needs to have a classification metadata template with at least one classification. This template needs to have a `scope`/`templateKey` of `enterprise.securityClassification-6VMVochwUWo`. This template will hold the possible classification levels, their label names, descriptions, and `colorID` values. - **Template Instances**: to apply a classification to a file or folder, a developer applies an instance of the `enterprise.securityClassification-6VMVochwUWo` template to the item. When the template is applied, one of the classifications is selected from the list of classifications on the template. **Reference:** https://developer.box.com/guides/metadata/classifications/ --- ## Untitled *Type: guide | Category: Metadata * Metadata Metadata allows users and applications to define and store custom data associated with files and folders. Metadata consists of key… # Metadata Metadata allows users and applications to define and store custom data associated with files and folders. Metadata consists of key/value pairs that are assigned to a file or a folder. For example, an important contract may have the key/value pairs of `clientNumber: 820183` and `clientName: bioMedicalCorp`. ## Metadata terminology Working with metadata requires a developer to work with a few distinct types of resources. - **Templates:** A [metadata template](g://metadata/templates) describes a re-usable set of key/value pairs that can be assigned to a file. For example, an `invoiceData` template might hold data about an invoice, having a field for the invoice ID as well as the customer ID. - **Fields:** A [metadata template field](g://metadata/fields) describes a specific piece of data within a metadata template. For example, the ID of an invoice might be represented as an `id` field on an `invoiceData` template. - **Instances:** A [metadata instance](g://metadata/instances) describes the relation between a template and a file or folder, including the values that are assigned for every field. For example, a user might have assigned an `invoiceData` metadata template to a file and provided 2 values, one for the invoice ID and one for the customer ID. You can assign up to 100 templates to specific file or folder. - **Cascade Policies**: A [metadata cascade policy](g://metadata/cascades) describes how metadata instances applied to a folder should be applied to any item within that folder. For example, a user might assign the same `invoiceData` metadata template to a project folder (including the 2 values), allowing them to automatically apply to all the files and folders within that project folder. - **Queries:** A [metadata query](g://metadata/queries) provides a way to find files and folders by searching for the metadata attached to them. For example, to find all the files for an invoice with a certain ID, the query would look for all files and folders with the `invoiceData` template attached to it and a value of `id = :id`, where `:id` would be the value of the invoice. ## The purpose of metadata Metadata can be used for many purposes. Enterprises may want to have a better way to organize their digital assets for their marketing teams, or developers may want to provide advanced content functionality such as facilitating workflows or approvals. For example, a `marketingCollateral` template may define where and when specific marketing content should be used. Users can see a representation of the template in the Box web application while navigating to a file preview. To learn more, please visit [Box community articles](https://support.box.com/hc/en-us/articles/360044196173-Using-Metadata). **Reference:** https://developer.box.com/guides/metadata/ --- ## Untitled *Type: guide | Category: Metadata * Metadata template scopes Metadata templates are grouped into two distinct groups, or scopes. global: a group of templates that is available… # Metadata template scopes Metadata templates are grouped into two distinct groups, or **scopes**. - **`global`**: a group of templates that is available to everyone using Box, regardless of the enterprise they are in. An example is the `global.properties` template that serves as a place to put free-form key/value `string` pairs without any additional schema associated with it. - **`enterprise`** or **`enterprise_*`**: a group of templates defined by a user within an enterprise. These templates are either created by admin's in the web application, or by applications using the API. When accessing or creating templates within the authenticated user's enterprise a short-hand of `enterprise` can be used. When accessing templates that belong to another enterprise - for example when accessing metadata on files belonging to other enterprises - the scope `enterprise_*` is used where `*` is the ID of the enterprise the template belongs to. # Permissions It is important to note that no metadata templates can be created within the `global` scope, and that metadata templates made within the user's enterprise can only be accessed by users with access to that enterprise. **Reference:** https://developer.box.com/guides/metadata/scopes/ --- ## Untitled *Type: guide | Category: Mobile * Mobile The Box mobile SDKs provide native access to the Box API from within your iOS and Android projects. # Mobile The Box mobile SDKs provide native access to the Box API from within your iOS and Android projects. **Reference:** https://developer.box.com/guides/mobile/ --- ## Untitled *Type: guide | Category: Mobile * Deep Linking Box’s mobile applications support deep linking into folder and file objects. From a web page or native app it is possible to… # Deep Linking Box’s mobile applications support deep linking into folder and file objects. From a web page or native app it is possible to deep link to open an object directly in Box. The following URLs are supported in Box’s mobile applications: | Application | Object Type | Deep Link URL | iOS & Android | | --- | --- | --- | --- | | Box | Folder | boxapp://folder?id=[folderid] | Version 3.7+ | | | File | boxapp://file?id=[fileid] | | | | Shared Link | boxapp://sharedlink?url=[sharedlink] | | | | | | | | Box for EMM | Folder | boxemm://folder?id=[folderid] | Version 3.7+ | | | File | boxemm://file?id=[fileid] | | | | Shared Link | boxemm://sharedlink?url=[sharedlink] | | **Reference:** https://developer.box.com/guides/mobile/mobile-deep-linking/ --- ## Untitled *Type: guide | Category: Representations * Download File Representation Use theurl_template that was received when selecting the representation to download the representation. Replace… # Download File Representation Use the`url_template` that was received when [selecting the representation](guide://representations/request-a-representation) to download the representation. Replace the `{+asset_path}` depending on the type of representation. ## Paginated representations For paged representations like PDFs replace `{+asset_path}` with the desired page number and the file extension, for example `1.pdf`. ``` curl https://dl.boxcloud.com/api/2.0/internal_files/123/versions/345/representations/pdf/content/3.pdf \ -H "authorization: Bearer ACCESS_TOKEN" ``` ## Non-paginated representations For non-paged representations, replace the `{+asset_path}` with an empty string. ``` curl https://dl.boxcloud.com/api/2.0/internal_files/123/versions/345/representations/jpg_32x32/content/ \ -H "authorization: Bearer ACCESS_TOKEN" ``` ## Optional query parameters When fetching the representation the following optional headers are supported. | Parameter | Options | Default | | --- | --- | --- | | set_content_disposition_type | inline / attachment | null | Sets the `content-disposition` header in the API response with the specified value. A disposition type of `attachment` causes most web browsers to prompt the user to save the response to their device, where the type `inline` will open the file in the browser. If not supplied, the `content-disposition` header is not included in the response. | Parameter | Options | Default | | --- | --- | --- | | set_content_disposition_filename | Filename without extension | null | Allows the application to define the downloaded representation's file name. If not defined, the file name is derived from the source file name in Box, replacing the extension with the representation's file type. **Reference:** https://developer.box.com/guides/representations/download-a-representation/ --- ## Untitled *Type: guide | Category: Representations * Representations A representation is an alternative asset for a file stored in Box. These assets can be PDFs, thumbnails, or text extractions… # Representations A representation is an alternative asset for a file stored in Box. These assets can be PDFs, thumbnails, or text extractions. Representations are automatically generated for the supported file types, either when uploading to Box or when requesting the asset. These representations are exposed through the `GET /files/:id` endpoint by using the `fields=representations` query parameter and the `x-rep-hints` header. **Reference:** https://developer.box.com/guides/representations/ --- ## Untitled *Type: guide | Category: Representations * List All Representations for File To see what representations are available for a file you can call the GET /files/:id endpoint while… # List All Representations for File To see what representations are available for a file you can call the [`GET /files/:id`](endpoint://get-files-id) endpoint while requesting the [`representations`](resource://file#param-representations) field. ``` curl https://api.box.com/2.0/files/123?fields=representations \ -H "authorization: Bearer ACCESS_TOKEN" ``` The response will include a list of representations in the following format ``` ... { "info": { "url": "https://api.box.com/2.0/internal_files/123/versions/345/representations/jpg_thumb_32x32" }, "properties": { "dimensions": "32x32", "paged": "false", "thumb": "true" }, "representation": "jpg" } ... ``` ## Response fields Every representation will include a set of properties and the type of representation. The optional `dimensions` field represents the file's dimensions in pixels as width by height. The optional `paged` field specifies if this representation is a paged document. Some images and PDFs will often be paged documents. The optional `thumb` field specifies if this representation is suitable as a file thumbnail. **Reference:** https://developer.box.com/guides/representations/list-all-representations/ --- ## Untitled *Type: guide | Category: Representations * Get PDF Representation A PDF representation provides a predictable way to embed documents in mobile and web applications. PDF… # Get PDF Representation A PDF representation provides a predictable way to embed documents in mobile and web applications. PDF representations support watermarks if the original file has been watermarked. PDF representations are generated upon uploading the source file to Box, though a watermarked PDF is generated upon fetching the watermarked file for the first time. ## The process To get a PDF representation follow the following steps - [List all representations](guide://representations/list-all-representations) - [Request a PDF](guide://representations/request-a-representation) by passing the `x-rep-hints`-header for the desired file type `[pdf]`. - [Download the PDF](guide://representations/download-a-representation) by calling the `url_template`, replacing the `{+asset_path}` with an the page of the PDF to request, for example `1.pdf`. ## Watermarked PDFs To retrieve a watermarked PDF the underlying file itself needs to be watermarked in Box. You can watermark a file either via the Box web application or using the [`PUT /files/:id/watermark/`](endpoint://put-files-id-watermark) API. Once watermarked, a watermarked PDF representation of the file is generated. **Reference:** https://developer.box.com/guides/representations/pdf/ --- ## Untitled *Type: guide | Category: Representations * Request Desired Representation To select a specific representation call the GET /files/:id endpoint with a x-rep-hints-header defining the… # Request Desired Representation To select a specific representation call the [`GET /files/:id`](endpoint://get-files-id) endpoint with a [`x-rep-hints`](endpoint://get-files-id#param-x-rep-hints)-header defining the required representation format. ``` curl https://api.box.com/2.0/files/123?fields=representations \ -H "x-rep-hints: [pdf]" \ -H "authorization: Bearer ACCESS_TOKEN" ``` ## Multiple dimensions Some formats will require the `dimensions` to be passed in to select a specific size. This can be achieved by appending the `dimensions` to the header. ``` curl https://api.box.com/2.0/files/123?fields=representations \ -H "x-rep-hints: [jpg?dimensions=94x94]" \ -H "authorization: Bearer ACCESS_TOKEN" ``` ## Multiple representations Multiple representations can be fetched by chaining the different types in the `x-rep-hints`-header. ``` curl https://api.box.com/2.0/files/123?fields=representations \ -H "x-rep-hints: [pdf][jpg?dimensions=94x94]" \ -H "authorization: Bearer ACCESS_TOKEN" ``` ## API Response This API call will result in one or more representations with a `url_template` value that includes a `{+asset_path}` value. ``` { "etag": "1", "id": "123", "representations": { "entries": [ { "content": { "url_template": "https://dl.boxcloud.com/api/2.0/internal_files/123/versions/345/representations/pdf/content/{+asset_path}" }, "info": { "url": "https://api.box.com/2.0/internal_files/123/versions/345/representations/pdf" }, "properties": {}, "representation": "pdf", "status": { "state": "success" } } ] }, "type": "file" } ``` The `url_template` in this response is an **opaque** URL. This URL format might change over time and no assumptions should be made about its format except for the presence of the `{+asset_path}` variable. **Reference:** https://developer.box.com/guides/representations/request-a-representation/ --- ## Untitled *Type: guide | Category: Representations * Supported File Types The following file types are supported by the representation API. 3D Graphics and Modeling Files File Type PDF Support… # Supported File Types The following file types are supported by the representation API. ## 3D Graphics and Modeling Files | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .3ds | No | No | No | | .box3d | No | No | No | | .dae | No | No | No | | .fbx | No | No | No | | .mtl | No | No | No | | .obj | No | No | No | | .ply | No | No | No | | .stl | No | No | No | ## Audio | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .aac | No | No | No | | .aif | No | No | No | | .aifc | No | No | No | | .aiff | No | No | No | | .amr | No | No | No | | .au | No | No | No | | .flac | No | No | No | | .m4a | No | No | No | | .mp3 | No | No | No | | .ogg | No | Yes | No | | .ra | No | No | No | | .wav | No | No | No | | .wma | No | No | No | ## CAD | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .dwg | Yes | Yes | No | ## Documents | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .boxnote | No | No | Yes | | .doc | Yes | Yes | Yes | | .docx | Yes | Yes | Yes | | .gdoc | Yes | Yes | Yes | | .html | Yes | No | Yes | | .msg | Yes | No | Yes | | .odt | Yes | Yes | Yes | | .pages | Yes | Yes | No | | .pdf | Yes | Yes | Yes | | .rtf | Yes | Yes | Yes | | .wpd | Yes | Yes | Yes | | .xhtml | Yes | No | Yes | | .xml | Yes | No | Yes | | .xsd | Yes | No | Yes | | .xsl | Yes | No | Yes | | .xbd | Yes | Yes | Yes | | .xdw | Yes | Yes | Yes | ## Drawing | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .ai | No | Yes | No | | .boxcanvas | No | No | Yes | | .indd | Yes | Yes | No | | .psd | No | Yes | No | | .svg | No | Yes | No | ## Image | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .bmp | No | Yes | No | | .cr2 | No | Yes | No | | .crw | No | Yes | No | | .dcm | No | Yes | No | | .dicm | No | Yes | No | | .dicom | No | Yes | No | | .dng | No | Yes | No | | .eps | No | Yes | No | | .gif | No | Yes | No | | .heic | No | Yes | No | | .indd | Yes | Yes | No | | .idml | Yes | Yes | No | | .indt | Yes | Yes | No | | .inx | Yes | Yes | No | | .jpeg | No | Yes | No | | .jpg | No | Yes | No | | .nef | No | Yes | No | | .png | No | Yes | No | | .ps | No | Yes | No | | .psd | No | Yes | No | | .raf | No | Yes | No | | .raw | No | Yes | No | | .svg | No | Yes | No | | .svs | No | Yes | No | | .tif | No | Yes | No | | .tiff | No | Yes | No | | .tga | No | Yes | No | | .webp | No | Yes | No | ## Presentation | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .gslide | Yes | Yes | Yes | | .gslides | Yes | Yes | Yes | | .key | Yes | Yes | No | | .odp | Yes | Yes | Yes | | .otp | Yes | Yes | Yes | | .ppt | Yes | Yes | Yes | | .pptx | Yes | Yes | Yes | ## Spreadsheet | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .csv | Yes | Yes | Yes | | .gsheet | Yes | Yes | Yes | | .numbers | Yes | Yes | No | | .ods | Yes | Yes | Yes | | .tsv | Yes | Yes | Yes | | .xls | Yes | Yes | Yes | | .xlsm | Yes | Yes | Yes | | .xlsx | Yes | Yes | Yes | | .xlsb | Yes | Yes | Yes | ## Text-Based Files | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .as | Yes | No | Yes | | .as3 | Yes | No | Yes | | .asm | Yes | No | Yes | | .bat | Yes | No | Yes | | .c | Yes | No | Yes | | .cc | Yes | No | Yes | | .cmake | Yes | No | Yes | | .cpp | Yes | No | Yes | | .cs | Yes | No | Yes | | .css | Yes | No | Yes | | .cxx | Yes | No | Yes | | .diff | Yes | No | Yes | | .erb | Yes | No | Yes | | .fdx | Yes | No | Yes | | .groovy | Yes | No | Yes | | .h | Yes | No | Yes | | .haml | Yes | No | Yes | | .hh | Yes | No | Yes | | .java | Yes | No | Yes | | .js | Yes | No | Yes | | .json | Yes | No | Yes | | .less | Yes | No | Yes | | .log | Yes | No | Yes | | .m | Yes | No | Yes | | .make | Yes | No | Yes | | .md | Yes | No | Yes | | .ml | Yes | No | Yes | | .mm | Yes | No | Yes | | .php | Yes | No | Yes | | .pl | Yes | No | Yes | | .plist | Yes | No | Yes | | .properties | Yes | No | Yes | | .py | Yes | No | Yes | | .rb | Yes | No | Yes | | .rst | Yes | No | Yes | | .sass | Yes | No | Yes | | .scala | Yes | No | Yes | | .scm | Yes | No | Yes | | .script | Yes | No | Yes | | .sh | Yes | No | Yes | | .sml | Yes | No | Yes | | .sql | Yes | No | Yes | | .txt | Yes | No | Yes | | .vi | Yes | No | Yes | | .vim | Yes | No | Yes | | .vtt | Yes | No | Yes | | .webdoc | Yes | No | Yes | | .yaml | Yes | No | Yes | ## Video | File Type | PDF Support? | Thumbnails? | Text? | | --- | --- | --- | --- | | .3g2 | No | Yes | No | | .3gp | No | Yes | No | | .avi | No | Yes | No | | .flv | No | Yes | No | | .m2v | No | Yes | No | | .m2ts | No | Yes | No | | .m4v | No | Yes | No | | .mkv | No | Yes | No | | .mov | No | Yes | No | | .mp4 | No | Yes | No | | .mpeg | No | Yes | No | | .mpg | No | Yes | No | | .mts | No | Yes | No | | .ogg | No | Yes | No | | .qt | No | Yes | No | | .ts | No | Yes | No | | .swf | No | Yes | No | | .wmv | No | Yes | No | **Reference:** https://developer.box.com/guides/representations/supported-file-types/ --- ## Untitled *Type: guide | Category: Representations * Get Text Representation A text representation provides a way to extract plain text from a document. Text is generated for all document file… # Get Text Representation A text representation provides a way to extract plain text from a document. Text is generated for all document file types including plain text and code files supported by Box. This does not include image files as these do not have a text layer. Text representations are generated upon upload of the file, similarly to PDFs and thumbnails. They are not generated for files larger than 500 megabytes. ## The process To get a text representation follow the following steps - [List all representations](guide://representations/list-all-representations) - [Request a text representation](guide://representations/request-a-representation) by passing the `x-rep-hints`-header with the value `[extracted_text]`. - [Download the text](guide://representations/download-a-representation) by calling the `url_template`, replacing the `{+asset_path}` with an empty string. **Reference:** https://developer.box.com/guides/representations/text/ --- ## Untitled *Type: guide | Category: Representations * Get Basic Thumbnail A thumbnail is a small image, either as .png or as .jpg that can be used in an application as a representation of the… # Get Basic Thumbnail A thumbnail is a small image, either as `.png` or as `.jpg` that can be used in an application as a representation of the file, for example as a placeholder for a link that downloads or previews the file. The preferred way to get a thumbnail for a file is using the [representations API](guide://representations/thumbnail-representation). ## Requesting To request a file thumbnail use the [`GET /files/:id/thumbnail.:extension`](endpoint://get_files_id_thumbnail_id) endpoint. When a thumbnail was successfully created, this will return the thumbnail in the body of the response as binary data. ## Asynchronous thumbnail creation Sometimes the thumbnail can not be created directly. Instead, the API will return a `HTTP 202` with a `location` response header. The location is for a temporary image that can be used while the thumbnail is being generated. A `retry-after` response header is also provided to present you with an estimated amount of seconds before retrying this endpoint. ## Supported file sizes The following formats and sizes of thumbnails are available. | File Type | Dimensions | | --- | --- | | JPG | 32x32, 94x94, 160x160, 320x320, 1024x1024, 2048x2048* | | PNG | 1024x1024*, 2048x2048* | Some restrictions apply to the sizes marked as `*`. ## File size restrictions ### Original file size Thumbnails are not scaled up. If the original file size of the file uploaded to Box is smaller than the representation dimensions, the resulting thumbnail is capped at the size of the original file. ## Supported file types At this time the following file types are supported. | File Type | File Extensions | | --- | --- | | Documents | doc, docx, gdoc, gsheet, gslide, gslides, odp, ods, odt, pdf, ppt, pptx, rtf, wpd, xls, xlsm, xlsx, key, pages, numbers | | Images | ai, bmp, dcm, dicm, eps, gif, idml, indd, indt, inx, jpeg, jpg, png, ps, psd, svg, svs, tif, tiff, tga | | Audio | aac, aifc, aiff, amr, au, flac, m4a, mp3, ogg, ra, wav, wma | | Video | 3g2, 3gp, avi, m2v, m2ts, m4v, mkv, mov, mp4, mpeg, mpg, mts, ogg, qt, wmv | **Reference:** https://developer.box.com/guides/representations/thumbnail/ --- ## Untitled *Type: guide | Category: Representations * Get Thumbnail Representation A thumbnail is a small image, either as .png or as .jpg that can be used in an application as a representation… # Get Thumbnail Representation A thumbnail is a small image, either as `.png` or as `.jpg` that can be used in an application as a representation of the file, for example as a placeholder for a link that downloads or previews the file. All thumbnail representations except `1024x1024` and `2048x2048` PNGs are generated upon uploading the source file to Box. An deprecated way to get a thumbnail for a file is using the [thumbnail API](guide://representations/thumbnail). ## The process To get a thumbnail representation follow the following steps - [List all representations](guide://representations/list-all-representations) - [Request a thumbnail](guide://representations/request-a-representation) by passing the `x-rep-hints`-header for the desired thumbnail format and size, for example `[jpg?dimensions=32x32]`. - [Download the thumbnail](guide://representations/download-a-representation) by calling the `url_template`, replacing the `{+asset_path}` with an empty string. Sometimes the thumbnail can not be created directly. Instead, the API will return a `HTTP 202` with a `location` response header. The location is for a temporary image that can be used while the thumbnail is being generated. A retry-after response header is also provided to present you with an estimated amount of seconds before retrying this endpoint. ## Examples The following a some example `x-rep-hints`-header values | x-rep-hints: [jpg?dimensions=32x32] | | --- | | Returns a 32x32 JPEG thumbnail | | x-rep-hints: [jpg?dimensions=32x32][jpg?dimensions=1024x1024] | | --- | | Returns 32x32 and 1024x1024 JPEG thumbnails | | x-rep-hints: [jpg?dimensions=32x32][png?dimensions=2048x2048] | | --- | | Returns a 32x32 JPEG and a 2048x2048 PNG thumbnail | | x-rep-hints: [jpg?dimensions=2048x2048,png?dimensions=2048x2048] | | --- | | Returns a 2048x2048 JPEG or a 2048x2048 PNG thumbnail, returning the first representation that is available. If neither is available it returns no representations | ## Supported file sizes The following formats and sizes of thumbnails are available. | File Type | Dimensions | | --- | --- | | JPG | 32x32, 94x94, 160x160, 320x320, 1024x1024, 2048x2048* | | PNG | 1024x1024*, 2048x2048* | Some restrictions apply to the sizes marked as `*`. ## File size restrictions ### JPEG 2048x2048 The JPEG `2048x2048` size is only available when the original file is a JPEG. We recommend either requesting a PNG or both a PNG and a JPEG for this dimension. ### Video files JPEG `2048x2048`, PNG `2048x20148` and PNG `1024x1024` representations are not available for video files. ### Original file size Thumbnails are not scaled up. If the original file size of the file uploaded to Box is smaller than the representation dimensions, the resulting thumbnail is capped at the size of the original file. ## Supported file types At this time the following file types are supported. | File Type | File Extensions | | --- | --- | | Documents | doc, docx, gdoc, gsheet, gslide, gslides, odp, ods, odt, pdf, ppt, pptx, rtf, wpd, xls, xlsm, xlsx, key, pages, numbers | | Images | ai, bmp, dcm, dicm, eps, gif, idml, indd, indt, inx, jpeg, jpg, png, ps, psd, svg, svs, tif, tiff, tga | | Audio | aac, aifc, aiff, amr, au, flac, m4a, mp3, ogg, ra, wav, wma | | Video | 3g2, 3gp, avi, m2v, m2ts, m4v, mkv, mov, mp4, mpeg, mpg, ogg, mts, qt, wmv | For **document** file types the representation returned will be a placeholder icon and not an actual thumbnail. **Reference:** https://developer.box.com/guides/representations/thumbnail-representation/ --- ## Untitled *Type: guide | Category: Retention Policies * Get Retention Policy To get the information for a specific Retention Policy that has been created in an enterprise, call the GET /retention… # Get Retention Policy To get the information for a specific Retention Policy that has been created in an enterprise, call the [`GET /retention_policies/:id`](e://get_retention_policies_id) API endpoint with the `id` of the policy. ## Required Scopes Before using any of the Retention Policy APIs, an application must have the right scopes enabled. See [Required Scopes](g://retention-policies#required-scopes) for more details. **Reference:** https://developer.box.com/guides/retention-policies/get/ --- ## Untitled *Type: guide | Category: Retention Policies * Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention… # Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then assign them to specific folders or their entire enterprise. Retention policies can be used to keep data for as long as is needed, and then automatically delete the content permanently when the data can no longer be legally held. Retention Policies are a feature of the [Box Governance](https://www.box.com/security/governance-and-compliance) package, which can be added on to any Business Plus or Enterprise account. ## Policies, Assignments, and Retentions Working with Retention Policies requires a developer to work with three distinct resources. - **Policies:** A [Retention Policy](r://retention_policy) describes the general behavior of the retention policy. It determines how long a retention should stay in place, if it can be extended, and what happens when the retention policy ends. - **Assignments:** A [Retention Policy Assignment](r://retention_policy_assignment) is a relation between a policy and folder or enterprise. Creating an assignment puts a retention on all the file versions that belong to that folder or enterprise. For example, if an assignment is created on a folder the policy is applied to all file versions within that folder. - **Retentions**: A [File Version Retention](r://file_version_retention) represents all the policies that are assigned to a specific file version. Note that every file version can have a maximum of one file version retention and that this resource contains a list of every assigned policy. The [file version retention](r://file_version_retention) section of the Box API is now deprecated. Instead, you can use [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. ## File Deletion with Retention Policies Files under retention can be deleted from folders, but they will be retained in the trash until the retention expires. When the retention expires, you can choose to have the content automatically deleted or for the policy to be removed. ## Extend Retention for a File Files under retention can have their retention date extended by [updating](e://put-files-id/#param-disposition_at) the `disposition_at` field's value with a future date. Once the date has been extended, it cannot be reverted or changed to be prior to the new date. ## Required Scopes Before using any of the Retention Policy APIs, an application must have the GCM and Manage Retention Policies scopes enabled. These are not available in the Developer Console and need to instead be enabled by contacting customer support. **Reference:** https://developer.box.com/guides/retention-policies/ --- ## Untitled *Type: guide | Category: Retention Policies * List All Retention Policies To list all Retention Policies that have been created in an enterprise, call the GET /retention_policies API… # List All Retention Policies To list all Retention Policies that have been created in an enterprise, call the [`GET /retention_policies`](e://get_retention_policies) API endpoint. ## Required Scopes Before using any of the Retention Policy APIs, an application must have the right scopes enabled. See [Required Scopes](g://retention-policies#required-scopes) for more details. **Reference:** https://developer.box.com/guides/retention-policies/list/ --- ## Untitled *Type: guide | Category: Search * Enterprise-wide search By default, a search is only performed against the content that the authenticated user has access to. In some cases… # Enterprise-wide search By default, a search is only performed against the content that the authenticated user has access to. In some cases, administrators might want to search against all content owned by all users. For this use-case the `scope` query parameter can be set to a value of `enterprise_content`. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&scope=enterprise_content" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); searchParams.setScope("enterprise_content"); PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", mdFilters: filters, scope: "enterprise_content"); ``` ``` client.search().query("sales", metadata_filters=metadata_search_filters, scope="enterprise_content") ``` ``` client.search.query( 'sales', { scope: "enterprise_content" }) .then(results => { // ... }); ``` The `enterprise_content` scope can be requested by an admin through our [support channels](p://support). Once this scope has been enabled for a user, it will allow that user to query for content across the entire enterprise and not only the content that they have access to. **Reference:** https://developer.box.com/guides/search/enterprise/ --- ## Untitled *Type: guide | Category: Search * Requesting extra fields By default, the search API returns the standard format of a File, Folder, or Web Link. Each of these resources… # Requesting extra fields By default, the search API returns the **standard** format of a [File](r://file), [Folder](r://folder), or [Web Link](r://web_link). Each of these resources supports additional fields that can be requested through the `fields` query parameter. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&fields=name,tags" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); final List<String> fields = new ArrayList<String>(); fields.add("name"); fields.add("tags"); searchParams.setFields(fields) PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` IEnumerable<string> fields = new List<string>() { "name", "tags"}; BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", fields: fields); ``` ``` client.search().query("sales", metadata_filters=metadata_search_filters, fields=["name", "tags"]) ``` ``` client.search.query( 'sales', { fields: "name,tags" }) .then(results => { // ... }); ``` For more details on these fields, please check out the [full File](r://file--full), [full Folder](r://folder--full), and [full Web Link](r://web_link) resources. When the `fields` parameter is used to query additional information about the items, only those fields and a few **base** fields (`id`, `type`, `name`, etc) are returned. Any fields that were originally in the response would now have to be requested explicitly. **Reference:** https://developer.box.com/guides/search/fields/ --- ## Untitled *Type: guide | Category: Search * Filter search results The GET /search API supports a variety of different ways to filter the results returned by the API. Filter by content… # Filter search results The [`GET /search`](e://get_search) API supports a variety of different ways to filter the results returned by the API. ## Filter by content type By default, a search returns items for which either the name, description, file content, tags, or comments match the query provided. By setting the `content_types` parameter the search can be narrowed down to only the items that match the query for the content type defined. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&content_types=name,tags" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); final List<String> contentTypes = new ArrayList<String>(); contentTypes.add("name"); contentTypes.add("tags"); searchParams.setContentTypes(contentTypes) PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` var contentTypes = new List<string>(); contentTypes.Add("name"); contentTypes.Add("tags"); BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", contentTypes: contentTypes); ``` ``` client.search().query("sales", content_types=["name", "tags"]) ``` ``` client.search.query( 'sales', { content_types: [ "name", "tags" ] }) .then(results => { // ... }); ``` | Content type | | | --- | --- | | name | The name of the item, as defined by its name field. | | description | The description of the item, as defined by its description field. | | file_content | The actual content of the file. | | comments | The content of any of the comments on a file or folder. | | tags | Any tags that are applied to an item, as defined by its tags field. | ## Filter by date By default, search returns files created at any time, and updated at any time. It is possible to filter results by both the date the file or folder was last updated or when it was created. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&created_at_range=2014-05-15T13:35:01Z,2015-05-15T13:35:01&updated_at_range=2014-05-15T13:35:01," \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); String createdFromDateString = "2014-05-15T13:35:01Z"; String createdToDateString = "2015-05-15T13:35:01Z"; Date createdFromDate = sdf.parse(createdFromDateString); Date createdToDate = sdf.parse(createdToDateString); DateRange createdRange = new DateRange(createdFromDate, createdToDate); searchParams.setCreatedRange(createdRange) String updatedFromDateString = "2014-05-15T13:35:01Z"; Date updatedFromDate = sdf.parse(updatedFromDateString); DateRange updatedRange = new DateRange(updatedFromDate, null); searchParams.setUpdatedRange(updatedRange) PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` var createdAtRangeFromDate = new DateTime(1988, 11, 18, 9, 30, 0, DateTimeKind.Utc); var createdAtRangeToDate = new DateTime(2018, 11, 18, 9, 30, 0, DateTimeKind.Utc); var updatedAtRangeFromDate = new DateTime(1988, 11, 18, 9, 30, 0, DateTimeKind.Utc); BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", contentTypes: contentTypes, createdAtRangeFromDate: createdAtRangeFromDate, createdAtRangeToDate: createdAtRangeToDate, updatedAtRangeFromDate: updatedAtRangeFromDate); ``` ``` client.search().query("sales", created_at_range=["2014-05-15T13:35:01Z", "2015-05-15T13:35:01Z"], updated_at_range=["2014-05-15T13:35:01Z", null]) ``` ``` client.search.query( 'sales', { created_at_range: "2014-05-15T13:35:01Z,2015-05-15T13:35:01Z", updated_at_range: "2014-05-15T13:35:01Z," }) .then(results => { // ... }); ``` | Query parameter | | | --- | --- | | created_at_range | Defines a range of created_at dates for which to return results. The upper or lower bound can be left empty to create an open-ended range. | | updated_at_range | Defines a range of updated_at dates for which to return results. The upper or lower bound can be left empty to create an open-ended range. | ## Filter by file extension By default, a search returns items with any kind of file extension. It is possible to filter search results to only files with one or more specific file extensions using the `file_extensions` query parameter. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&file_extensions=pdf,txt" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); final List<String> fileExtensions = new ArrayList<String>(); fileExtensions.add("pdf"); fileExtensions.add("txt"); searchParams.setFileExtensions(fileExtensions) PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` var fileExtensions = new List<string>(); fileExtensions.Add("pdf"); fileExtensions.Add("txt"); BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", fileExtensions: fileExtensions); ``` ``` client.search().query("sales", file_extensions=["pdf", "txt"]) ``` ``` client.search.query( 'sales', { file_extensions: [ "pdf", "txt" ] }) .then(results => { // ... }); ``` ## Filter by file size By default, a search returns items of any file size. It is possible to filter search results to only files within a specific file size using the `size_range` query parameter. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&size_range=10000,20000" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); SizeRange sizeRange = new SizeRange(10000, 20000); searchParams.setSizeRange(sizeRange); PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", sizeRangeLowerBoundBytes: 10000, sizeRangeUpperBoundBytes: 20000); ``` ``` client.search().query("sales", size_range=[10000,20000]) ``` ``` client.search.query( 'sales', { size_range: '10000,20000' }) .then(results => { // ... }); ``` ## Filter by file type By default, a search returns both files, folders, and web links. To narrow down the results to only one of these, a `type` query parameter can be set to either `file`, `folder` or `web_link`. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&type=file" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); searchParams.setType("file"); PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", type: "file"); ``` ``` client.search().query("sales", type="file") ``` ``` client.search.query( 'sales', { type: "file" }) .then(results => { // ... }); ``` ## Filter by metadata It is possible to filter search results by their associated metadata, or even perform entire searches based on only the metadata, all using the `mdfilters` query parameter. Learn more about metadata filters ## Filter by owner By default, a search returns all the items the authenticated user has access to, regardless of who owns the items. To narrow down to only items owned by specific users, use the `owner_user_ids` query parameter. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&owner_user_ids=34446362,462281242" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); final List<String> userIds = new ArrayList<String>(); userIds.add("34446362"); userIds.add("462281242"); searchParams.setOwnerUserIds(userIds) PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` var userIds = new List<string>(); userIds.Add("34446362"); userIds.Add("462281242"); BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", ownerUserIds: userIds); ``` ``` client.search().query("sales", owner_user_ids=["34446362", "462281242"]) ``` ``` client.search.query( 'sales', { owner_user_ids: "34446362,462281242" }) .then(results => { // ... }); ``` ## Filter by parent folder By default, a search returns all the items in any folder the user has access to. To narrow down the results to only items in specific folders, use the `ancestor_folder_ids` query parameter. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&ancestor_folder_ids=45235463,73445321" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); final List<String> folderIds = new ArrayList<String>(); folderIds.add("45235463"); folderIds.add("73445321"); searchParams.setAncestorFolderIds(folderIds) PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` var folderIds = new List<string>(); folderIds.Add("45235463"); folderIds.Add("73445321"); BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", ancestorFolderIds: folderIds); ``` ``` client.search().query("sales", ancestor_folder_ids=["45235463", "73445321"]) ``` ``` client.search.query( 'sales', { ancestor_folder_ids: "45235463,73445321" }) .then(results => { // ... }); ``` **Reference:** https://developer.box.com/guides/search/filtering/ --- ## Untitled *Type: guide | Category: Search * Search The Box API provides a way to find content in Box using full-text search queries. Support for the Box search API is available in all… # Search The Box API provides a way to find content in Box using full-text search queries. Support for the Box search API is available in all our supported SDKs and the CLI. Explore the [reference documentation](e://get_search) to learn more about all the different features available to the search API. ## Query operators The search API supports a few different [search operators](g://search/query-operators), including `AND`, `OR`, `NOT` and `""`. These operators can be used to refine the search results to only return items that match a more complicated combination of search terms. ``` curl -i -X GET "https://api.box.com/2.0/search?query=box%20AND%20sales" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` Learn more about using logical operators ## Search Indexing Box keeps a search index for any files or folder stored in Box. Every time a file or folder is changed, those words are added to the index. When a search is performed, the API looks in the search index for files and folders that match the query. When content is added, updated, or deleted in Box, the search index is updated accordingly. Learn more about the Box search index In some cases an index might not be updated even after 10 minutes. In those cases we recommend reaching out to [Box Support](page://support) to get the issue resolved. If your enterprise has full text search turned off (e.g. [Keysafe](https://www.box.com/security/keysafe) customers), characters within a document cannot be searched. If you need to find out if full text search is turned off, reach out to your account team. ## Comparison to Metadata Queries At the surface the search API seems very similar to the [Metadata Query API](g://metadata/queries), but there are several important differences in how they operate. At a high level the Metadata Queries are optimized for exactness and throughput, while regular search is optimized for relevance to a human user. | | Metadata Query API | Search API | | --- | --- | --- | | What is indexed? | This API only return files/folders based on the values in the metadata templates that are searched | This API returns files, folders and web links based on values in the item names, descriptions, contents (up to the first 10,000 bytes) as well as the associated metadata template instances | | Indexing time | This API will return accurate results as soon as metadata has been added, removed, updated or deleted for a file or folder | This API is subject to a search indexing delay, which is typically 10 minutes yet may be longer in some cases. This means that items may not be returned for more than 10 minutes after metadata has been updated | | Matching | This API uses exact matching based on SQL conventions. Results are returned based on a specified sort order | This API uses fuzzy matching and may return results that vary based on string tokenization, removal of special characters, and other search concepts. Result order is based on either relevance or the updated date of the item | | Conditional logic | This API supports multi-part boolean expressions with comparison operators | This API has limited support for querying by metadata. It only supports querying 1 metadata template at a time and only allows simple query operations. | | Response type | This API returns both the matched file/folder and the associated metadata matched by the query | This API only returns the matched item. A subsequent API call is needed to return each item's metadata | | Throughput | This API is currently subject to per-user rate limits and to a 10 requests per second per enterprise limit | This API supports 6 searches per second per user, up to 60 searches per minute and 12 searches per second per enterprise | | Scale | This API has no limit on the number of items with the specified metadata template that can be returned. It is recommended to only send queries which match no more than 2,000 results. | This API has no limit on number of items with the specified metadata template that can be returned, yet the response time increases significantly as the number of items matching the search grows. This API does have a limit of up to 10 million results for a query. It is recommended to only send queries which match no more than 50,000 results. | | Scope | This API is always limited to the content to which the user has access | This API may be either limited to the content to which the user has access (​user_content​) or to all content in the enterprise (​enterprise_content​). | Learn more about the metadata query API **Reference:** https://developer.box.com/guides/search/ --- ## Untitled *Type: guide | Category: Search * Search indexing Box keeps a search index for any files or folders stored in Box. Every time a file or folder is changed, those words are… # Search indexing Box keeps a search index for any files or folders stored in Box. Every time a file or folder is changed, those words are added to the index. When a search is performed, the API looks in the search index for files and folders that match the query. When content is added, updated, or deleted in Box, the search index is updated accordingly. ## Search Availability It can take time between uploading or modifying a file for it to be fully indexed and ready to be searched. In most cases, newly added or changed files can be expected to be available via Box search in 10 minutes. The current service load determines the index time and it may take more than 10 minutes in some cases. In some cases an index might not be updated even after 10 minutes. In those cases we recommend reaching out to [Box Support](page://support) to get the issue resolved. ## Search Access Only content that the authenticated user has access to (items they can preview and/or view) will be returned in the search results. In other words, a user needs to either own an item or be a collaborated in on an item for it to show up in the search results. If a user doesn't have access to an item, or if they have been shared the item via a shared link, then the item will also not appear in the search results. One exception is that items that have been recently accessed via a shared link can be requested in the search results by setting the `include_recent_shared_links` query parameter to `true`. ## Prefix Matching and Wildcard Search Trailing wildcards (also known as prefix matching) are implicitly included in search results because of the way text is indexed. Searching for `Bo` results in items with titles containing `Box` or `Boat` or `Boxer`. It is the equivalent of searching for `Bo*` or `Bo%` in traditional search engines. Traditional wildcard notation is not supported by Box, such as `%ox%`. While we support prefix matching on titles, we do not support prefix matching on body content, suffix matching in the title or body content, or infix (middle of the word) matching in the title or body content. For example, a search on `cal` would match results for a file named `California` but not `decal` or `recall`. It would not match results with **file body contents** of prefixes, infixes, or suffixes including `California`, `recall`, or `decal`. ## Stemming Box Search uses stemming to match terms from the query to terms in the index. Because of this, words that include the same stem may be included in the result set, even if the words do not contain the exact form in the query. For example, `run` and `running` map to the same stem, so a search on `running` may return a document containing `run` in the title. ## File Content Searching The content within files is also stored within the Box search index. The following file types allow searching for their content: | | | | | | | --- | --- | --- | --- | --- | | boxnote | csv | doc | docx | gdoc | | gsheet | gslide | gslides | htm | html | | msg | odp | odt | ods | pdf | | ppt | pptx | rtf | tsv | wpd | | xhtml | xls | xlsm | xlsx | xml | | xsd | xsl | as | as3 | asm | | bat | c | cc | cmake | cpp | | cs | css | cxx | diff | erb | | groovy | h | haml | hh | java | | js | json | less | log | m | | make | md | ml | mm | php | | pl | plist | properties | py | rb | | rst | sass | scala | script | scm | | sml | sql | sh | txt | vi | | vim | webdoc | yaml | | | ## Indexed Text per Document The Box search index stores up to 10,000 bytes (~10,000 characters in English) per document for accounts from Business level and above. This amount can vary from document to document because of language, Box’s indexing method, and document type. If your enterprise has full text search turned off (e.g. [Keysafe](https://www.box.com/security/keysafe) customers), characters within a document cannot be searched. If you need to find out if full text search is turned off, reach out to your account team. ## OCR Support Box does not currently perform OCR on its documents. ## Document Versions Search only indexes content from the current version of a document, so that you do not have to sift through hundreds of irrelevant search results of outdated documents. You cannot use search to query non-current versions of a document. ## Language Support Box search supports the following languages: Chinese, English, French, German, Italian, Japanese, and Spanish. Box does not support indexing of multiple languages within a single document. ## Trash Searching the trash is available via the API by using the `trash_content` query parameter. Check our community article with the latest details on Search in Box **Reference:** https://developer.box.com/guides/search/indexing/ --- ## Untitled *Type: guide | Category: Search * Metadata Query Filters The GET /search API allows for filtering search results by their associated metadata. A mdfilters query parameter… # Metadata Query Filters The [`GET /search`](e://get_search) API allows for filtering search results by their associated metadata. A `mdfilters` query parameter allows a developer to specify a metadata template and the desired values to query. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&mdfilters=%5B%7B%22scope%22%3A%22enterprise%22%2C%22templateKey%22%3A%22contract%22%2C%22filters%22%3A%7B%22category%22%3A%22online%22%7D%7D%5D" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); BoxMetadataFilter bmf = new BoxMetadataFilter(); bmf.setScope("enterprise"); bmf.setTemplateKey("contract"); bmf.setFilter("category", "online") searchParams.setMetadataFilter(bmf) PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` var filter = new { category = "online" }; var filters = new List<BoxMetadataFilterRequest>() { new BoxMetadataFilterRequest() { Scope = "enterprise", TemplateKey = "contract", Filters: filter } }; BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", mdFilters: filters); ``` ``` from boxsdk.object.search import MetadataSearchFilter, MetadataSearchFilters metadata_search_filter = MetadataSearchFilter(scope='enterprise', template_key='contract') metadata_search_filter.add_value_based_filter(field_key='category', value='online') metadata_search_filters = MetadataSearchFilters() metadata_search_filters.add_filter(metadata_search_filter) client.search().query("sales", metadata_filters=metadata_search_filters) ``` ``` client.search.query( 'sales', { mdfilters: [ { scope: 'enterprise', templateKey: 'contract', filters: { category: 'online' } } ] }) .then(results => { // ... }); ``` This example filters a search for any content that matches the query `sales` by any item that has `enterprise.contract` metadata attached to it and where the `category` field is set to `online`. ## Introduction to Metadata Metadata allows users and applications to define and store custom data associated with files and folders. Metadata consists of key/value pairs that are assigned to a file or a folder. For example, an important contract may have the key/value pairs of `clientNumber: 820183` and `category: online`. The `mdfilters` query parameter allows developers to find files and folders that have a specific piece of metadata attached to them. Learn more about metadata templates and instances ## Metadata Filter Syntax The `mdfilters` parameter can currently only contain one filter, although this may be expanded in the future. Each filter defines the `scope` and `templateKey` of the metadata template to filter on. ``` [ { "scope": "enterprise", "templateKey": "contract", "filters": {} } ] ``` To get the `scope` and `templateKey` for a template, either [list all metadata templates](g://metadata/templates/list) for an enterprise, or [list all metadata instances on an item](g://metadata/instances/list). With the template defined, the `filters` field accepts a few different filter formats. The format of the filter very much depends on the type of field being filtered by. ### Filter by string field To filter by a field of type `string` a filter will need to define the `key` of the field and the desired value to find items for. ``` [ { "scope": "enterprise", "templateKey": "contract", "filters": { "category": "online" } } ] ``` This example will find all files and folders that have an instance of the `enterprise.contract` template applied to it, and for which the field with the key `category` is set to the value `online`. ### Filter by float field To filter by a field of type `float`, you will need to define define a range by specifying a `gt` (greater-than) and/or `lt` (lower-than) value. To find an exact value, you can input the same value for both `gt` and `lt`. ``` [ { "scope": "enterprise", "templateKey": "contract", "filters": { "amount": { "gt": 10000, "lt": 20000 } } } ] ``` This example will find all files and folders that have an instance of the `enterprise.contract` template applied to it, and for which the field with the key `amount` is set to a value equal or higher than `10000` and equal or lower than `2000`. Note that `gt` and `lt` are inclusive and do not need to both be set. If you create a query based on numbers, do not exceed the range of -16777215 and +16777215. For metadata search using number attributes the index value is stored as FLOAT32. As a result, integers between -16777215 and +16777215 can be precisely represented. Any operation with numbers beyond the range can lose its precision. ### Filter by date field To filter by a field of type `date` a filter will need to define the `key` of the field and the desired range to find items by specifying a `gt` (greater-than) and `lt` (lower-than) value. Please note that `gt` and `lt` are inclusive. ``` [ { "scope": "enterprise", "templateKey": "contract", "filters": { "expirationDate": { "gt": "2016-08-01T00:00:00Z", "lt": "2017-08-01T00:00:00Z" } } } ] ``` This example will find all files and folders that have an instance of the `enterprise.contract` template applied and have an `expirationDate` set to a date after or exactly `2016-08-01T00:00:00Z` and before or exactly `2017-08-01T00:00:00Z`. ### Filter by enum field To filter by a field of type `enum` a filter will need to define the `key` of the field and the desired value to find items for. ``` [ { "scope": "enterprise", "templateKey": "contract", "filters": { "category": "online" } } ] ``` This example will find all files and folders that have an instance of the `enterprise.contract` template applied to it, and for which the field with the key `category` is set to the value `online`. ### Filter by multiSelect field To filter by a field of type `multiSelect` a filter will need to define the `key` of the field and any of the potential desired values to find items for. When performing a search, the query will essentially perform an `OR` operation to match any template where any of the provided values match this field. ``` [ { "scope": "enterprise", "templateKey": "contract", "filters": { "category": [ "online", "enterprise" ] } } ] ``` This example will find all files and folders that have an instance of the `enterprise.contract` template applied to it, and for which the field with the key `category` is set to the value `online` or `enterprise`. **Reference:** https://developer.box.com/guides/search/metadata-filters/ --- ## Untitled *Type: guide | Category: Search * Pagination The search API supports offset-based pagination using the offset and limit query parameters. Marker-based pagination is not… # Pagination The search API supports offset-based pagination using the `offset` and `limit` query parameters. Marker-based pagination is not supported. ## API Pagination To fetch the first page of search results, the API needs to be called either without the `offset` parameter, or with the `offset` set to `0`. The `limit` field is optional. ``` curl https://api.box.com/2.0/search?query=sales&offset=0&limit=100 \ -H "authorization: Bearer ACCESS_TOKEN" ``` To fetch the next page of entries the API needs to be called with an `offset` parameter that's equals the sum of the previous `offset` value and limit returned in the previous result, `previous_offset + previous_limit`. ``` curl https://api.box.com/2.0/search?query=sales&offset=100&limit=100 \ -H "authorization: Bearer ACCESS_TOKEN" ``` Note that the `offset` should be increased by the previous `limit` and not by the size of the entries in the response array, as this may be less than the limit. Generally we advise using the value of the `limit` in the response object to increase the `offset` value. The final page of items has been requested when the next `offset` value exceeds the `total_count` value in the response object. At this point there are no more items to fetch. Learn more about offset-based pagination ## SDK Pagination Each of our SDKs has built-in support for API pagination. The following code samples show how to use pagination in the search API. ``` long offsetValue = 0; long limitValue = 50; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); PartialCollection<BoxItem.Info> page1 = boxSearch.searchRange(offsetValue, limitValue, searchParams); offsetValue += 50; PartialCollection<BoxItem.Info> page2 = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` BoxCollection<BoxItem> page1 = await client.SearchManager .QueryAsync("sales", limit: 50); BoxCollection<BoxItem> page2 = await client.SearchManager .QueryAsync("sales", limit: 50, offset: 50); ``` ``` page1 = client.search().query(query='sales', limit=50) page2 = client.search().query(query='sales', limit=50, offset=50) ``` ``` const page1 = await client.search.query('sales', { limit: 50 }) const page2 = await client.search.query('sales'. { limit: 50, offset: 50 }) ``` **Reference:** https://developer.box.com/guides/search/pagination/ --- ## Untitled *Type: guide | Category: Search * Query operators The GET /search API supports a variety of different query operators to help refining the results returned by the API. All of… # Query operators The [`GET /search`](e://get_search) API supports a variety of different query operators to help refining the results returned by the API. All of these operations are passed into the `query` parameter when creating the search. ## Exact matches with "" By wrapping a query in double quotes (`""`) only exact matches are returned by the API. Exact searches do not return search matches based on specific character sequences. Instead, they return matches based on phrases, that is, word sequences. For example, a search for `"Blue-Box"` may return search results including the sequence `"blue.box"`, `"Blue Box"`, and `"Blue-Box"`; any item containing the words `Blue` and `Box` consecutively, in the order specified. ## Matching multiple terms with AND When the `AND` operator is used, the search returns items that contain both the search terms on the left and right of the operator. For example, a search for `marketing AND BoxWorks` returns items that have both `marketing` and `BoxWorks` within its text in any order. It does not return a result that only has `BoxWorks` in its text. ## Matching either search term with OR When the `OR` operator is used, the search returns items that contain either the search terms on the left or right of the operator. For example, a search for `marketing OR BoxWorks` returns a result that has either `marketing` or `BoxWorks` within its text. Using this operator is not necessary as we implicitly interpret multi-word queries as `OR` unless another supported boolean term is used. ## Excluding search terms with NOT When the `NOT` operator is used, the search returns items that do not contain the term that follows the operator. For example, a search for `marketing AND NOT BoxWorks` returns a result that has only `marketing` within its text. Results containing `BoxWorks` are omitted. Please note that we do not support lower case (that is, `and`, `or`, and `not`) or mixed case (that is, `And`, `Or`, and `Not`) operators. Check our community article with the latest details on Search in Box **Reference:** https://developer.box.com/guides/search/query-operators/ --- ## Untitled *Type: guide | Category: Search * Finding recent shared links By default, the search API only returns items that are either owned by the user or items that the user has been… # Finding recent shared links By default, the search API only returns items that are either owned by the user or items that the user has been explicitly collaborated on. These search results do not include any items that a user might have accessed recently through a shared link. To enable shared links in the API, the `include_recent_shared_links` query parameter can be set to `true`. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&include_recent_shared_links=true" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` client.search().query("sales", metadata_filters=metadata_search_filters, include_recent_shared_links=True) ``` ``` client.search.query( 'sales', { include_recent_shared_links: true }) .then(results => { // ... }); ``` Please be aware that this parameter is relatively new and therefore support for it in our Java and Windows SDKs is still a work in progress. Please be very aware that when this parameter has been set to true, the format of the response of this API changes to return a list of [Search Results with Shared Links](r://search-results-with-shared-links) **Reference:** https://developer.box.com/guides/search/shared-links/ --- ## Untitled *Type: guide | Category: Search * Searching trash By default, any content in the user's trash is ignored in the search results. To search the user's trash, the trash_content… # Searching trash By default, any content in the user's trash is ignored in the search results. To search the user's trash, the `trash_content` query parameter can be set to `trashed_only`. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales&trash_content=trashed_only" \ -H "Authorization: Bearer <ACCESS_TOKEN>" ``` ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("sales"); searchParams.setTrashContent("trashed_only"); PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ``` BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("sales", mdFilters: filters, trashContent: "trashed_only"); ``` ``` client.search().query("sales", metadata_filters=metadata_search_filters, trash_content="trashed_only") ``` ``` client.search.query( 'sales', { trash_content: "trashed_only" }) .then(results => { // ... }); ``` Currently the API only supports searching for content not in the trash (`non_trashed_only`, default) or in the user's trash (`trashed_only`). It is currently not possible to search for items in both locations at once. **Reference:** https://developer.box.com/guides/search/trash/ --- ## Untitled *Type: guide | Category: Security * Cross-Origin Resource Sharing (CORS) Cross-Origin Resource Sharing (CORS) is a security mechanism used by web browsers to prevent malicious… # Cross-Origin Resource Sharing (CORS) [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is a security mechanism used by web browsers to prevent malicious websites from accessing data on other sites (like the Box API) without explicit permission. CORS only applies to Box API requests made by a web page using a web browser, and it relies on the `HTTP Origin` header being passed along by the browser. It does not come in to play in a server-side environment. Visit the MDN Web Docs for more generic information about CORS. ## How CORS works When a browser on one domain (for example `company.com`) tries to fetch images, files, or even API resources from another domain (`box.com`), the web browser will prevent access to any of those assets unless the right CORS headers are present. When the browser makes a cross-origin request, an `Origin` request header is passed along with it that contains the domain of the site making that request. This header can not be changed and is part of your web browser's essential security. By default, a browser will not accept any asset loaded from another domain if there is no `Access-Control-Allow-Origin` response header present. Servers like Box can explicitly list the domains allowed to access resources on this server, or they can return a `*` value to allow any domain to access the API. ## How Box uses CORS Box uses the `Origin` request header and `Access-Control-Allow-Origin` response header to enforce CORS rules defined by the developer. ### Origin-header validation The Box API validates the `Origin` request header against the list of allowed domains set by the application developer. Multiple allowed origins can be set and any origin not on the list will return in a `HTTP 403` error. ``` { "type": "error", "status": 403, "code": "cors_origin_not_whitelisted", "context_info": { "origin": "https://company.com" }, "help_url": "https://developer.box.com/guides/api-calls/permissions-and-errors/common-errors/", "message": "Access denied - Did you forget to safelist your origin in the CORS config of your app?", "request_id": "4dsdfsa832213" } ``` If no origin is set, all requests to the Box API for this application return an error. ### Access-Control-Allow-Origin response header After the Box API has validated the `Origin` header, it will return the data requested as well as a `Access-Control-Allow-Origin` response header with the value `*`. ``` HTTP/1.1 200 OK Date: Wed, 23 Sep 2020 14:07:29 GMT Content-Type: application/json Transfer-Encoding: chunked Connection: keep-alive Strict-Transport-Security: max-age=31536000 Cache-Control: no-cache, no-store Access-Control-Allow-Origin: * Vary: Origin BOX-REQUEST-ID: 032cfb446dae4fd0b4c2bff80a1a97ba7 ``` By returning this header, the Box API informs the web browser that the response can be used in the site that requested the data. ## Enabling CORS for your domain To enable CORS for the domain your application runs on, head over to the developer console, select your application, and scroll down to the bottom of the **Configuration** panel to find the **CORS Domains** setting. Add a comma separated list of all the origins that you expect your application to be making Box API requests from. Domains require the schema (`http` or `https`) and can include wildcards for subdomains, for example `*.example.com`. If your site runs on a non-standard port, it will also need to include that. This is especially relevant for a site running on `localhost` or `127.0.0.1`. An example list of origins would be as follows. ``` https://company.com,https://*.internal.company.com,http://localhost:3000 ``` ## Debugging CORS There are a few different kind of CORS errors that might occur when making API calls to the Box API. ### HTTP 403 - No allowed origins defined You might get this error even after you provided a list of origins. Often, this is because of a typo in the provided origins. 1. **Check your origins** - Head back to the developer console and make sure your origins map the site your are making the API call from. Keep in mind that an origin includes the scheme (`http(s)`) but no path or trailing `/`. We recommend inspecting the page using your browser's debug console and checking the `Origin` request header value. This value should match one of the provided values in the developer console. 2. **Check your credentials** - Another reason for this error might be that you are authenticating as a different application than the one you have set the origin up for. Check that the credentials match the ones of the application you are intending to use. We recommend trying to make a call from a server-side script to validate that the API call works. ### Cross-Origin Request Blocked In some cases, you might get a Javascript error that mentions CORS. ``` Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.box.com/2.0/users/me. (Reason: CORS request did not succeed). ``` In many cases this has little to do with CORS. Instead we recommend checking the following. 1. **Check your authentication headers** - If the authorization header is not provided or malformed, then the API will return a generic error without the necessary `Access-Control-Allow-Origin` header. This in turn will cause the previously mentioned error to be raised by your browser. Make sure to pass in an access token using the `Authorization: Bearer ...` header. 2. **Check for requests blocked by VPN, Proxies, etc** - In some cases, the Box API might be blocked by your VPN, corporate proxy, a browser extension, your DNS provider, or any other service that can intercept network traffic. Any of these can intercept the request and return a whole new request that does not include the necessary `Access-Control-Allow-Origin` header. To test for this case, try to make the same API call from a non-browser environment, from an incognito window, or from a whole other (not company owned) device. ### Access-Control-Allow-Origin header issues If you encounter issues with the `Access-Control-Allow-Origin` header, do the following: 1. **Check if your domain is on the list of allowed origins** - Go to the developer console and open your application. Click on the **Configuration** tab and scroll down. You can add your domain to the list in section **CORS domains**. 1. **Check if your server is set up correctly** - Configure your server to handle cross-domain requests or use non-cross-domain requests if you receive a warning **No 'access-control-allow-origin' header is present on the requested resource**. **Reference:** https://developer.box.com/guides/security/cors/ --- ## Untitled *Type: guide | Category: Security * FedRAMP Overview FedRAMP is a certification program that allows federal agencies to use cloud providers for increasingly secure/sensitive… # FedRAMP ## Overview FedRAMP is a certification program that allows federal agencies to use cloud providers for increasingly secure/sensitive government or government-adjacent data. FedRAMP defines three categories regarding levels of security, Low, Moderate, and High. The higher the security level the more restrictions are in place. Box is currently certified as [FedRAMP High](https://marketplace.fedramp.gov/products/F1212191840A). ## Considerations In order to be FedRAMP compliant, your administrator must setup Box in very a very specific way. It is possible that the administrator has further restricted access to Box functionalities. Consult with your administrator to identify security restrictions in place that might affect the usage of the API. ## API usage in FedRAMP For FedRAMP compliance, you may use the below URLs for API entry points. | FedRAMP | | --- | | account.box.com | | api.box.com | | upload.box.com | | dl.boxcloud.com | | realtime.services.box.net | **Reference:** https://developer.box.com/guides/security/fedramp/ --- ## Untitled *Type: guide | Category: Security * Security Whether your are a developer getting started with the Box API or a Box Admin tasked with authorizing applications, it is critical… # Security Whether your are a developer getting started with the Box API or a Box Admin tasked with [authorizing](g://authorization/custom-app-approval) applications, it is critical you understand the security mechanisms in place to protect content stored in Box. The Box API follows the same security principals and restrictions as the Box web app. This means that you will not be able to bypass content [permissions](https://support.box.com/hc/en-us/articles/360044196413-Understanding-Collaborator-Permission-Levels), the [waterfall folder structure](https://support.box.com/hc/en-us/articles/360043697254-Understanding-Folder-Permissions), or Admin-only requirements by leveraging the Box API. ## Access Tokens At the core of every Box API call is an [Access Token](g://authentication/tokens). Because a username and password cannot be used, the Box servers need a way of validating user identity. The full capability of an Access Token encompasses user permissions, token permissions, and application settings. Access Tokens represent the authenticated user and determine what content a user can successfully call. Similar to using the Box Web App, you will only be able to successfully interact with content the user, associated with the Access Token, either owns or is a collaborator on. This can be further restricted by [downscoping](g://authentication/tokens/downscope) a token. [Access Tokens](g://authentication/tokens) are only valid for 60 minutes, but can be [revoked](e://post-oauth2-revoke) earlier if needed. Once an Access Token expires, when using an OAuth 2.0 application, a [Refresh Token](g://authentication/tokens/refresh) can be [exchanged](e://post-oauth2-token--refresh) for another Access Token. Refresh tokens are valid for 60 days or one use. Alternatively, when using a server authentication application, the [request Access Token endpoint](e://post-oauth2-token) must be called for a new Access Token. For security reasons we do not allow long-lived access tokens. Unsure why you are receiving a 404 error? A great place to start is checking to see what user is associated with your Access Token by using the get current user endpoint. ## Scopes [Scopes](g://api-calls/permissions-and-errors/scopes) are configured in the [Developer Console](https://app.box.com/developers/console) upon application creation. They determine which of the 150+ endpoints Access Tokens of an application can successfully call. Because scopes work in conjunction with user permissions, granting the write scope does not automatically provide a user with API access to all content in a Box enterprise. Instead, it means that the authenticated user can receive successful API responses when making write calls to content they have access to. For example, take an application with only the manage users and manage groups scopes enabled. If an Access Token of this application tried to make an API call to get information about a folder, even if the associated user owned it, it would receive a 403 error. This is because the read scope is required to preform this action. Access Tokens of this application could only receive successful responses on API calls related to users and groups. ## Restricted endpoints There are some API endpoints that only Admins or Co-Admins, granted the appropriate [permissions](https://support.box.com/hc/en-us/articles/360044194393-Granting-And-Modifying-Co-Admin-Permissions), can successfully use. As a general rule of thumb, if only an Admin or Co-Admin can perform an action via the Box Admin Console, an Access Token associated with one of these users is required to complete an API call for the same action. This is called out in our API [reference](page://reference) documentation for a given endpoint if it is required. Some Admin-restricted endpoints include: - Creating, deleting, or getting information about [users](e://resources/user) - Creating, deleting, or modifying [groups](e://resources/group) - Viewing user or enterprise [events](e://resources/event) Other endpoints can only be used by an Admin user's Access Token if the enterprise has purchased add-on products such as Box Governance or Box Shield. Some of these endpoints include: - Interacting with [security classifications](e://resources/classification) - Interacting with [legal hold policies](e://resources/legal-hold-policy) and [assignments](e://resources/legal-hold-policy-assignment) - Interacting with [retention policies](e://resources/retention-policies) and [assignments](e://resources/retention-policy-assignment) ## Application Access Application access is only configured in the [Developer Console](https://app.box.com/developers/console) for applications leveraging Server Authentication with [JWT)](g://authentication/jwt) or [Client Credentials Grant](g://authentication/client-credentials). This setting determines the [types of users](page://platform/user-types) that can be used with the application. The two options are **app access only** or **app + enterprise access**. Upon [authorizing](g://authorization/custom-app-approval) one of these applications in the Box Admin Console, a [Service Account](page://platform/user-types/#service-account) (`AutomationUser_xxxx_@boxdevedition.com`) representing the application is automatically generated. This account is an Admin-like user that can only be accessed via the API and can then be used to create user’s of the application called [App Users](page://platform/user-types/#app-user). If an application only needs to interact with the Service Account and App Users, **app only access** must be selected. If an application needs to interact with [managed users](page://platform/user-types/#managed-users) and their existing Box content, app + enterprise access must be selected. As an example, take a JWT application that has the read/write scopes, app only access, and is properly [authorized](g://authorization/custom-app-approval) in the Admin console. If a managed user obtains an Access Token and makes an API call to a folder they own, that call would receive a 400 error with the message “Cannot obtain token based on the enterprise configuration for your app”. Even though the user has access to the content, the correct scopes are enabled and the app is authorized, the selected application access only allows the application to interact with the Service Account and App Users. ## Enterprise settings and authorization There are a few enterprise settings to be aware of when it comes to the Box API. Platform applications fall into two categories: published and unpublished. Published applications are found in the [Box Integrations](https://app.box.com/services). Box Admins decide whether published and unpublished application are enabled by default and therefore can be used without approval. The status of these settings determines what actions are necessary to successfully [authorize](g://authorization/custom-app-approval) an application for use. Regardless of the settings above, in order for an application leveraging [JWT](g://authentication/jwt) or [Client Credentials Grant](g://authentication/client-credentials) to be used by an enterprise, an Admin must explicitly [authorize](g://authorization/custom-app-approval) it via the Box Admin console. The authorization is a snapshot in time. This means that if a developer revisits the Developer Console and changes the configuration, the Admin must re-authorize the application in order for generated Access Tokens to reflect the changes. If the setting **Disable unpublished apps by default** is turned on, an Admin must also explicitly [enable](g://authorization/custom-app-approval) any application leveraging [OAuth 2.0](g://authentication/oauth2) as the authentication method. Additionally, if this setting is turned on, Server Authenticated apps will also require enablement. **Reference:** https://developer.box.com/guides/security/ --- ## Untitled *Type: guide | Category: Security * Device Pinners Building on the login tracking feature – which allows admins to set limits on the number of devices a user can access Box… # Device Pinners Building on the login tracking feature – which allows admins to set limits on the number of devices a user can access Box from and sends alerts to them and the user whenever a new device is used to access that Box account – Box has additional device management functionality to increase security when accessing Box on mobile or desktop devices: device pinning. To learn more about device pinning, please see our community documentation. ## APIs The Box API allows for device pins to be inspected and removed. - [`GET /enterprise/:id/device_pinners`](e://get-enterprises-id-device-pinners): Retrieves all the device pins within an enterprise. - [`GET /device_pinners/:id`](e://get-device-pinners-id): Retrieves information about an individual device pin. - [`DELETE /device_pinners/:id`](e://delete-device-pinners-id): Deletes an individual device pin. **Reference:** https://developer.box.com/guides/security/device-pinners/ --- ## Untitled *Type: guide | Category: Shared Links * Create or Update Shared Link Shared links may be created or directly for file, folder, or web link resources to generate a read-only URL to… # Create or Update Shared Link Shared links may be created or directly for file, folder, or web link resources to generate a read-only URL to permit users with the appropriate access level to view the content. You may only have one active shared link for a file, folder, or web link at any time. At minimum the information needed to create a shared link will be: - The type of resource, either a file, folder, or web link. - The ID of that resource. Optionally when creating a shared link the following may be specified: The access level, which may be one of: - open: A public shared link. Anyone with the link may access the link. - company: Anyone within your enterprise may access the link. - collaborators: Anyone collaborated on the content may access the link. An expiration time when the shared link will automatically disable. A password required to access the resource. If an access level is not specified when creating a shared link it will use the default access level specified by the enterprise admin. ## Create or Update Shared Link for File To create a shared link on a file, specify the ID of the file with any optional shared link parameters. ## Create or Update Shared Link for Folder To create a shared link on a folder, specify the ID of the folder with any optional shared link parameters. ## Create or Update Shared Link for Web Link To create a shared link on a web link, specify the ID of the web link with any optional shared link parameters. **Reference:** https://developer.box.com/guides/shared-links/create-or-update/ --- ## Untitled *Type: guide | Category: Shared Links * Find Item from Shared Link The find item for shared link API is designed to accept a shared link as an input using a BoxApi header and… # Find Item from Shared Link The [find item for shared link](endpoint://get_shared_items) API is designed to accept a shared link as an input using a `BoxApi` header and return the file or folder object that the shared link is set for. To get the file or folder object associated with a shared link, supply the full shared link URL in the request. Please note that when the shared link is for a folder, the response of this API does not include the list of nested items within that folder. To further traverse the items in the folder, use the same `BoxApi` header to [get a nested folder's information](e://get-folders-id), list the items in those folders, get a nested file's information, or [download a file](e://get-files-id-content) **Reference:** https://developer.box.com/guides/shared-links/find-for-item/ --- ## Untitled *Type: guide | Category: Shared Links * Shared Links Shared links are URLs that are generated for files, folders, web links stored in Box, which provide direct, read-only access to… # Shared Links Shared links are URLs that are generated for files, folders, web links stored in Box, which provide direct, read-only access to the resource. Shared links which are set to an open access level allow anyone with the URL to access the item, while shared links with company or collaborators access levels may only be accessed by appropriate authenticated Box users. See [here](https://community.box.com/t5/Using-Shared-Links/Creating-Shared-Links/ta-p/19523) for all of the options and admin settings related to shared links. Users can access shared items by entering the shared link URL in a browser. Applications can also access shared items using the [Shared Item API](endpoint://get_shared_items). **Reference:** https://developer.box.com/guides/shared-links/ --- ## Untitled *Type: guide | Category: Shared Links * Shared Link Permissions The shared link resource has three permissions that can be updated using the permissions field: can_preview, can… # Shared Link Permissions The shared link resource has three permissions that can be updated using the `permissions` field: `can_preview`, `can_download`, `can_edit`. The `can_edit` option can only be `true` for files. Also, if the admin has restricted shared links from having edit access in the admin console, you will not be able to set `can_edit` to `true`. ``` curl -i -X PUT 'https://api.box.com/2.0/files/123456789?fields=shared_link' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer [ACCESS TOKEN]' \ -d '{ "shared_link": { "permissions": { "can_preview": true, "can_download": true, "can_edit": true } } }' ``` **Reference:** https://developer.box.com/guides/shared-links/permissions/ --- ## Untitled *Type: guide | Category: Shared Links * Remove Shared Link A shared link may be removed from a resource by calling the update file or update folder or update weblink endpoint and… # Remove Shared Link A shared link may be removed from a resource by calling the [update file](endpoint://put_files_id) or [update folder](endpoint://put_folders_id) or [update weblink](endpoint://put_web_links_id) endpoint and setting the `shared_link` value to `null`. If you delete the shared link and create a new one, the new shared link will have a different URL and users with the old URL will not be able to access the resource. ## Remove Shared Link on File To remove a shared link on a file, specify the ID of file to set the `shared_link` field to `null`. ## Remove Shared Link on Folder To remove a shared link on a folder, specify the ID of folder to set the `shared_link` field to `null`. ## Remove Shared Link on Web Link To remove a shared link on a web link, specify the ID of web link to set the `shared_link` field to `null`. **Reference:** https://developer.box.com/guides/shared-links/remove/ --- ## Untitled *Type: guide | Category: Box Skills * Box Skills Box Skills are designed to allow custom processing of files uploaded to Box, with the intent of enhancing the underlying metadata… # Box Skills Box Skills are designed to allow custom processing of files uploaded to Box, with the intent of enhancing the underlying metadata of the file. The benefit towards this system is that it permits the storage of rich information about any files, which may then be used to automated tasks and future processes. The end-to-end process of a Skills application is as follows. 1. [Setup up an app](guide://skills/handle/setup) - Create a **Custom Skills** Box application that listens for files being uploaded within the entire enterprise or one or more folders. 2. [Configure the `invocation_url`](guide://skills/invocation-url) - After creating the **Custom Skills** app, an `invocation_url` will need to be configured. This URL will be called every time a new file is uploaded to Box. 3. [Parse the event payload](guide://skills/handle/payload) - When a file is uploaded, copied, or moved into a folder that the Box Skill listens to, an event payload is sent to the `invocation_url`. This payload contains two **Access Tokens** that can be used to access the uploaded file in Box and store metadata back onto the file. 4. [Verify Key Signatures](guide://webhooks/v2/signatures-v2) - Before the service that handles the Skill payload does other actions, it should verify the `invocation_url` was called by Box. See the link for examples of doing this manually or using the SDKs. 5. [Send the file for processing](https://github.com/box-community/Box-Custom-Skills-Starter) - The service that handles the Skill payload sends the file URL or file content to an external service for processing. This service can be a third party machine learning system, or an in-house service. 6. [Store the metadata on the file](guide://skills/handle/metadata) - Once the processing service has extracted the metadata for the file, those insights can be stored back on the uploaded file as custom metadata. To simplify your integration with Box Skills, a Skills Kit has been made available to obfuscate many complexities of the above steps. The Skills Kit is currently only available in Node. **Reference:** https://developer.box.com/guides/skills/ --- ## Untitled *Type: guide | Category: Box Skills * Invocation URL When creating a new Box Skills application you will be asked to supply an invocation_url. This URL is the public web address… # Invocation URL When creating a new [Box Skills application](guide://applications/app-types/custom-skills) you will be asked to supply an `invocation_url`. This URL is the public web address where Box will send the [event notification payload](guide://skills/handle/payload) when a file is uploaded, copied, or moved within a folder monitored by the Skills app. The website or application that is listening for those notifications functions as a bridge between the file on Box and the system that is being employed to garner insight from the file, such as the machine learning system. ## Requirements - The invocation URL should be publicly available. Notifications cannot be sent to `localhost` or `127.0.0.1` as this address is not accessible by Box's servers. - The server behind the invocation URL should be listening to HTTP `POST` requests. Box Skills will send the event notification via a `POST` request using a `JSON` body. ## Hosting Tips & Tricks There are a number of ways to quickly expose a an application on a public URL so that Box's servers can use this as the `invocation_url`. - **A local tunnel** - One of the quickest ways to expose a web application on a developer's machine to a public address is by using a local tunnel. Popular tunneling tools include [`ngrok`](https://ngrok.com) and [`localtunnel`](https://www.npmjs.com/package/localtunnel). - **Serverless functions** - A great way to set up a server that can handle a Box Skill is as a **serverless function**. Box Skills can generate a varied amount of invocations depending on the (lack of) activity in the folders being observed. Serverless functions such as [AWS Lambda](https://aws.amazon.com/lambda/), [Google Cloud Functions](https://cloud.google.com/functions/), or [Microsoft Azure Functions](https://azure.microsoft.com/en-us/services/functions/) are a natural fit for these kind of sporadic events. The serverless functions will only run and be billed when the event is being processed. - **Traditional application hosting** - Traditional application hosting solutions, such as [Heroku](https://www.heroku.com/), [Firebase](https://firebase.google.com/), [AWS](https://aws.amazon.com/) or [GCP](https://cloud.google.com/functions/) are other viable options if serverless technology is not preferred. These applications will be hosted on their respective services and have an publicly exposed URL for the app that will be used as the invocation URL. ## Application Server details Typically the application behind the invocation URL will need to perform the following tasks. 1. Capture the event notification from Box. 2. Send the binary data for the Box file (or its URL) to a processing service 3. Listen for the response from the processing service. 4. Format the response from the processing service into a Box metadata format. 5. Apply the new metadata back to the file stored on Box. **Reference:** https://developer.box.com/guides/skills/invocation-url/ --- ## Untitled *Type: guide | Category: SSO & App users * Connect SSO identities to app users Your SSO service will have a unique user record for each person using it within your company. When… # Connect SSO identities to app users Your SSO service will have a unique user record for each person using it within your company. When accessing a Box application through this SSO service, if we're creating a Box user for each SSO user, then we need to create an association between the SSO user and Box user records. When a user logs in to Box through the SSO service we will first search for the user by the association. If a Box user record is found we can begin making calls as that user to Box APIs. If there is no Box user found will then create a new Box user with the association to the unique SSO user account. Exploring the top level of a Box [user object](r://user) we can see the available options for adding the unique identifier from the SSO service user object into the Box user object to bind the two together. ``` { "address": "900 Jefferson Ave, Redwood City, CA 94063", "avatar_url": "https://www.box.com/api/avatar/large/181216415", "can_see_managed_users": true, "created_at": "2012-12-12T10:53:43-08:00", "enterprise": { .. }, "external_app_user_id": "my-user-1234", "hostname": "https://example.app.box.com/", "id": 11446498, "is_exempt_from_device_limits": true, "is_exempt_from_login_verification": true, "is_external_collab_restricted": true, "is_platform_access_only": true, "is_sync_enabled": true, "job_title": "CEO", "language": "en", "login": "ceo@example.com", "max_upload_size": 2147483648, "modified_at": "2012-12-12T10:53:43-08:00", "my_tags": [ .. ], "name": "Aaron Levie", "notification_email": { ... }, "phone": 6509241374, "role": "admin", "space_amount": 11345156112, "space_used": 1237009912, "status": "active", "timezone": "Africa/Bujumbura", "tracking_codes": [{ .. }], "type": "user" } ``` There are two recommended methods for creating a binding between a unique user within the SSO service and a Box user, placing the unique SSO user ID within the Box user `external_app_user_id` field, or using the unique SSO email address as the login email for the new user. ## Using external_app_user_id (recommended method) The `external_app_user_id` field was designed to hold a string identifier to associate a Box user record with an external service, such as an SSO provider user record. You can retrieve app users for a specific application only if such app users were created by this application. If you use one application to search for users created by a different one, no data will be returned. Using the `external_app_user_id` field for associating the unique SSO user account with a Box user account is the preferred method of connecting the two accounts over email, for a number of reasons: - Email association is only viable for [managed users](page://platform/user-types/#managed-users). [App users](page://platform/user-types/#app-user) are automatically assigned an email address by Box, meaning that you cannot assign the `login` to be the email from the SSO service. - Emails have to be unique in Box. This means that if your SSO service user signed up for Box using the same email address, which is not within your Box enterprise, then you will not be able to create a user with that email and won't be able to connect to that existing user. - The `external_app_user_id` field was designed for this purpose. ## Using login (alternative method) Using the `login` field of a user object to create an account association is viable under a few conditions: - Only the [managed users](page://platform/user-types/#managed-users) type is being used, not [app users](page://platform/user-types/#app-user). - All email addresses and Box account creation requests are managed by your enterprise, meaning that users cannot independently create Box accounts with those email addresses. Email addresses used for users in Box, under the `login` field, must be unique. Making a request to create a user with an email that already exists for another account will result in a `409 Conflict` error, stating that `user_login_already_used` **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/connect-identities/ --- ## Untitled *Type: guide | Category: Box Skills * Box Skills Kit The Box Skills Kit is a Node wrapper that is designed to abstract many of the common complex operations required during the… # Box Skills Kit The Box Skills Kit is a Node wrapper that is designed to abstract many of the common complex operations required during the Box Skills development process. Visit the Skills Kit on GitHub **Reference:** https://developer.box.com/guides/skills/kit/ --- ## Untitled *Type: guide | Category: SSO & App users * Create connection between SSO identity and app user When a user signs in to a custom Box application for the first time using their SSO… # Create connection between SSO identity and app user When a user signs in to a custom Box application for the first time using their SSO provider credentials a new Box user will need to be created and associated with their SSO user record using some piece of unique information from that SSO user record. Typically the data that is used to make the association between those two accounts is either a unique ID or an email address. To make that association, a Box account may be created in a few ways: - Using the `external_app_user_id` field of a Box user to store the unique ID from the SSO provider. - Using the `login` field of a Box user to store the unique email from the SSO provider (managed users only). ## Create association with external_app_user_id Using the `external_app_user_id` field of a Box user record is a viable option for both app users and managed users, and is the recommended method when associating a user record from an SSO provider with a Box user account. ### App user To create a new Box app user with an `external_app_user_id` association to a SSO user record you will need two pieces of information from the SSO provider: - UID (required): The unique identifier from the SSO user record. - Name (optional): To maintain uniformity between the records, the SSO user name may be extracted to associate with the Box user record. Once available, make a request to create a new app user, supplying the optional `external_app_user_id` definition in the user parameters. ``` const ssoName = 'SSO User Name'; const ssoUID = 'SSO User Unique ID'; const spaceAmount = 1073741824; // Create app user client.enterprise.addAppUser( ssoName, { space_amount: spaceAmount, external_app_user_id: ssoUID } ).then(appUser => { console.log(`New user created: ${appUser.name}`); }); ``` ``` String ssoName = "SSO User Name"; String ssoUID = "SSO User Unique ID"; // Create app user CreateUserParams params = new CreateUserParams(); params.setExternalAppUserId(ssoUID); BoxUser.Info createdUserInfo = BoxUser.createAppUser(client, ssoName, params); outputString = "New user created: " + createdUserInfo.getName(); ``` ``` sso_name = 'SSO User Name' sso_uid = 'SSO User Unique ID' space = 1073741824 # Create app user user = box_client.create_user(sso_name, None, space_amount=space, external_app_user_id=sso_uid) print('New user created: {name}') ``` ### Managed user To create a new Box managed user with an `external_app_user_id` association to a SSO user record you will need two pieces of information from the SSO provider: - Email (required): The unique email from the SSO user record. - Name (optional): To maintain uniformity between the records, the SSO user may be extracted to associate with the Box user record. Once available, make a request to create a new managed user, supplying the SSO user record email address for the login. ``` const ssoName = 'SSO User Name'; const ssoEmail = 'ssouser@email.com'; const spaceAmount = 1073741824; // Create app user client.enterprise.addUser( ssoEmail, ssoName, { space_amount: spaceAmount } ).then(managedUser => { console.log(`New user created: ${managedUser.name}`); }); ``` ``` String ssoName = "SSO User Name"; String ssoEmail = "ssouser@email.com"; // Create managed user BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(client, ssoEmail, ssoName); outputString = "New user created: " + createdUserInfo.getName(); ``` ``` sso_name = 'SSO User Name' sso_email = 'ssouser@email.com' space = 1073741824 # Create managed user user = box_client.create_user(sso_name, sso_email, space_amount=space) print('New user created: {name}') ``` ## Create association by email Creating a new [managed user](page://platform/user-types/#managed-users) that is associated by the SSO user email address is the same process as creating a standard managed user. After the user logs in via your SSO provider, if the user doesn't already exist as a Box user, extract the email address from the SSO user record and make a request to create a new Box managed user. **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/create-app-user/ --- ## Untitled *Type: guide | Category: SSO & App users * Find app user for SSO identity When a user logs into a Box platform application with their SSO provider, the first step that should be taken… # Find app user for SSO identity When a user logs into a Box platform application with their SSO provider, the first step that should be taken is to see if that user already exists from a previous login attempt where a Box user record was already created. If a Box user is found you should [create a user access token](guide://authentication/jwt/user-access-tokens), or make [as user calls](guide://authentication/jwt/as-user), to access Box APIs as that user. If a Box user is not found you should create a new user with an association to the SSO user record. To search for existing users the [List Enterprise Users](e://get-users) endpoint may be used. Depending on whether you're using the `external_app_user_id` or `login` method your query will look slightly different. ## Find user by external_app_user_id To search for enterprise users by the stored `external_app_user_id` value you will need one piece of information from the SSO provider: - UID (required): The unique identifier from the SSO user record. Once available, make a request to the list enterprise users endpoint, supplying the `external_app_user_id` definition in the parameters. You can retrieve app users for a specific application only if such app users were created by this application. If you use one application to search for users created by a different one, no data will be returned. ``` const ssoUID = 'SSO User Unique ID'; // Check enterprise users for matching external_app_user_id against SSO UID client.enterprise.getUsers({ "external_app_user_id": ssoUID }) .then((users) => { if (users.total_count > 0) { // User found, fetch user ID const userId = users.entries[0].id; } else { // User not found - create new user record } }); ``` ``` String ssoUID = "SSO User Unique ID"; // Check enterprise users for matching external_app_user_id against SSO UID URL url = new URL("https://api.box.com/2.0/users?external_app_user_id=" + ssoUID); BoxAPIRequest request = new BoxAPIRequest(client, url, "GET"); BoxJSONResponse jsonResponse = (BoxJSONResponse) request.send(); JsonObject jsonObj = jsonResponse.getJsonObject(); JsonValue totalCount = jsonObj.get("total_count"); if (totalCount.asInt() > 0) { // User found, fetch // Fetch user ID JsonArray entries = (JsonArray) jsonObj.get("entries"); JsonObject userRecord = (JsonObject) entries.get(0); JsonValue userId = userRecord.get("id"); } else { // User not found - create new user record } ``` ``` sso_uid = 'SSO User Unique ID' # Validate is user exists url = f'https://api.box.com/2.0/users?external_app_user_id={sso_uid}' headers = {'Authorization': 'Bearer ' + access_token} response = requests.get(url, headers=headers) user_info = response.json() if (user_info['total_count'] == 0): # User not found - create new user record else: # User found, fetch user ID user = user_info['entries'][0] user_id = user['id'] ``` ## Find user by email address To search for enterprise users by their `login` email you will need one piece of information from the SSO provider: - Email (required): The unique email from the SSO user record. Once available, make a request to the list enterprise users endpoint, supplying the email address as the `filter_term`, which is made available to search by email or name. ``` const ssoEmail = 'ssouser@email.com'; client.enterprise.getUsers({filter_term: ssoEmail}) .then(users => { if (users.total_count > 0) { // User found, fetch user ID const userId = users.entries[0].id; } else { // User not found - create new user record } }); ``` ``` String ssoEmail = "ssouser@email.com"; Iterable<BoxUser.Info> users = BoxUser.getAllEnterpriseUsers(client, ssoEmail); ``` ``` sso_email = 'ssouser@email.com' users = client.users(user_type='all', filter_term=ssoEmail) if (users['total_count'] == 0): # User not found - create new user record else: # User found, fetch user ID user = users['entries'][0] user_id = user['id'] ``` **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/find-app-user/ --- ## Untitled *Type: guide | Category: SSO & App users * SSO & App users Single Sign-On (SSO) services are often used as part of a company's Identity and Access Management (IAM) solution. When… # SSO & App users Single Sign-On (SSO) services are often used as part of a company's Identity and Access Management (IAM) solution. When deployed, these services grant users the ability to securely authenticate multiple applications by logging in once, with only one set of credentials (username and password). Box is one of the applications that can be connected to the SSO service of a company. Integrating these applications into your platform apps will allow you to provision Box users on the fly for any of your end users, without those users knowing they have a Box account. Popular SSO services include `Okta`, `Auth0`, `Microsoft Azure AD`, `OneLogin`, `G Suite`, and `Ping Identity`, but there are many others that may be deployed. ## Connecting SSO to apps When integrating SSO services into a Box application programmatically, we are referring to the following flow. 1. A user accesses your web or mobile application in a logged out state. 2. The user is redirected to your SSO provider to log in, typically via `OAuth 2` and `OpenID Connect`. 3. After login, the user is redirected back to your application along with their SSO identity credentials. 4. Your application does a check to see if an associated Box account already exists for this user. 5. If an existing Box account already exists for this user, the application uses the SSO identity to make API calls on behalf of that user in Box. 6. If there is not already an associated Box account for this user, a new Box user account is created based on the SSO identity. The unique user ID from the SSO service is then linked to the new Box user, creating an association between the two accounts. This new Box user is then API calls on behalf of that user in Box. # Box web app and SSO If you wish to connect your SSO service to the Box website instead of a Box application, Box provides a number of [integration options](https://support.box.com/hc/en-us/articles/360043696514-Setting-Up-Single-Sign-On-SSO-for-your-Enterprise) for supporting SSO integrations of the [Box web application](https://www.box.com) via SAML 2.0. **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/ --- ## Untitled *Type: guide | Category: Tasks * Create a task To create a task, you will need to provide the POST /tasks API with the action for the task, as well as an item to represent… # Create a task To create a task, you will need to provide the [`POST /tasks`](e://post_tasks) API with the `action` for the task, as well as an `item` to represent the file to add the task to. ## Task actions Box currently supports two types of tasks defined by the `action` value: `review` tasks and `complete` tasks. The type of task determines the possible resolution states a task can be in and the interface shown to a user in the web and mobile apps. | Task action | Possible resolution states | | --- | --- | | review | incomplete, approved, rejected | | complete | incomplete, complete | A `review` task starts out in an `incomplete` state and can be marked as `incomplete`, `approved`, or `rejected`. In the user interface a user is provided with a text box and an pair of buttons to approve or reject the task. A `complete` task starts out in an `incomplete` state and can be marked `incomplete` or `completed`. Once a this task is marked completed, no further changes can be made to the task's state. In the user interface a user is provided with a text box and an button to mark the task as completed. ## Completion rules A task on a file can be assigned to more than one collaborator on the file, and a task has a `completion_rule` that can be used to define if all users who've been assigned the task (`all_assignees`) or only one assignee (`any_assignee`) need to complete the task. **Reference:** https://developer.box.com/guides/tasks/create/ --- ## Untitled *Type: guide | Category: Tasks * Delete a task To remove a task, call the DELETE /tasks/:task_id API with the id of the task. # Delete a task To remove a task, call the [`DELETE /tasks/:task_id`](e://delete_tasks_id) API with the `id` of the task. **Reference:** https://developer.box.com/guides/tasks/delete/ --- ## Untitled *Type: guide | Category: Tasks * Lists all tasks for a file To list all of the tasks for a specific file, call the GET /files/:id/tasks with the id of the file. # Lists all tasks for a file To list all of the tasks for a specific file, call the [`GET /files/:id/tasks`](e://get_files_id_tasks) with the `id` of the file. **Reference:** https://developer.box.com/guides/tasks/for-file/ --- ## Untitled *Type: guide | Category: Tasks * Get information about a task To get information about an assigned task, call the GET /tasks/:task_id API with the id of the task. # Get information about a task To get information about an assigned task, call the [`GET /tasks/:task_id`](e://get_tasks_id) API with the `id` of the task. **Reference:** https://developer.box.com/guides/tasks/get/ --- ## Untitled *Type: guide | Category: Tasks * Make changes to an existing task To update a task in Box you will need to call the PUT /tasks/:task_id API with the ID of the task. This API… # Make changes to an existing task To update a task in Box you will need to call the [`PUT /tasks/:task_id`](e://put_tasks_id) API with the ID of the task. This API can be used to change the `action` type of the task, add a `message`, or change the due date. ## Task actions Box currently supports two types of tasks defined by the `action` value: `review` tasks and `complete` tasks. The type of task determines the possible resolution states a task can be in and the interface shown to a user in the web and mobile apps. | Task action | Possible resolution states | | --- | --- | | review | incomplete, approved, rejected | | complete | incomplete, complete | A `review` task starts out in an `incomplete` state and can be marked as `incomplete`, `approved`, or `rejected`. In the user interface a user is provided with a text box and an pair of buttons to approve or reject the task. A `complete` task starts out in an `incomplete` state and can be marked `incomplete` or `completed`. Once a this task is marked completed, no further changes can be made to the task's state. In the user interface a user is provided with a text box and an button to mark the task as completed. ## Completion rules A task on a file can be assigned to more than one collaborator on the file, and a task has a `completion_rule` that can be used to define if all users who've been assigned the task (`all_assignees`) or only one assignee (`any_assignee`) need to complete the task. **Reference:** https://developer.box.com/guides/tasks/update/ --- ## Untitled *Type: guide | Category: Tasks * Tasks Tasks allow users to request collaborators on a file to review a file or complete a piece of work. Tasks can be used by developers to… # Tasks Tasks allow users to request collaborators on a file to review a file or complete a piece of work. Tasks can be used by developers to create file-centric workflows. Learn more about tasks from the Adding Comments and Tasks article on our support site. ## Task actions Box currently supports two types of tasks defined by the `action` value: `review` tasks and `complete` tasks. The type of task determines the possible resolution states a task can be in and the interface shown to a user in the web and mobile apps. | Task action | Possible resolution states | | --- | --- | | review | incomplete, approved, rejected | | complete | incomplete, complete | A `review` task starts out in an `incomplete` state and can be marked as `incomplete`, `approved`, or `rejected`. In the user interface a user is provided with a text box and an pair of buttons to approve or reject the task. A `complete` task starts out in an `incomplete` state and can be marked `incomplete` or `completed`. Once a this task is marked completed, no further changes can be made to the task's state. In the user interface a user is provided with a text box and an button to mark the task as completed. ## Completion rules A task on a file can be assigned to more than one collaborator on the file, and a task has a `completion_rule` that can be used to define if all users who've been assigned the task (`all_assignees`) or only one assignee (`any_assignee`) need to complete the task. **Reference:** https://developer.box.com/guides/tasks/ --- ## Untitled *Type: guide | Category: Tooling * Tooling Box offers several options for using our APIs, including the Box CLI, Postman, Salesforce Developer Toolkit, and various SDKs. # Tooling Box offers several options for using our APIs, including the [Box CLI](g://cli), [Postman](g://tooling/postman), [Salesforce Developer Toolkit](g://tooling/salesforce-toolkit), and [various SDKs](g://tooling/sdks). **Reference:** https://developer.box.com/guides/tooling/ --- ## Untitled *Type: guide | Category: Trash * Trash Before items are deleted they might end up in a user's trash. The trash can be managed by a user through any of the Box apps, and by… # Trash Before items are deleted they might end up in a user's trash. The trash can be managed by a user through any of the Box apps, and by an application via the API. ## Two-stage Deletion Process Box uses a two-stage process to remove or **trash** [files](e://delete_files_id), [folders](e://delete_folders_id), and [web links](e://delete_web_links_id) before permanently deleting them. By default, items can be restored after they are **trashed** within a 30 day time frame before they are **purged**. The purge window can be modified by an enterprise administrator. More details can be found in the Box community article on [Managing Trash](https://support.box.com/hc/en-us/articles/360044196093-Manage-Trash) **Reference:** https://developer.box.com/guides/trash/ --- ## Untitled *Type: guide | Category: Trash * Permanently Delete File Once a file has been moved to the trash, it will stay in the trash for 30 days by default before being purged… # Permanently Delete File Once a file has been moved to the trash, it will stay in the trash for 30 days by default before being purged. Administrators of Business or Enterprise accounts can alter the purge window. If you wish to permanently delete the file from the trash before the purge window expires, make a `DELETE` request to `/files/:file_id/trash` using the trashed file's `ID`. **Reference:** https://developer.box.com/guides/trash/permanently-delete-file/ --- ## Untitled *Type: guide | Category: Trash * Permanently Delete Web Link Once a web link has been moved to the trash, it will stay in the trash for 30 days by default before being… # Permanently Delete Web Link Once a web link has been moved to the trash, it will stay in the trash for 30 days by default before being purged. Administrators of Business or Enterprise accounts can alter the purge window. If you wish to permanently delete the web link from the trash before the purge window expires, make a `DELETE` request to `/web_links/:web_link_id/trash` using the trashed web link's `ID`. **Reference:** https://developer.box.com/guides/trash/permanently-delete-web-link/ --- ## Untitled *Type: guide | Category: Trash * Permanently Delete Folder Once a folder has been moved to the trash, it will stay in the trash for 30 days by default before being purged… # Permanently Delete Folder Once a folder has been moved to the trash, it will stay in the trash for 30 days by default before being purged. Administrators of Business or Enterprise accounts can alter the purge window. If you wish to permanently delete the folder from the trash before the purge window expires, make a `DELETE` request to `/folders/:folder_id/trash` using the trashed folder's `ID` . **Reference:** https://developer.box.com/guides/trash/permanently-delete-folder/ --- ## Untitled *Type: guide | Category: Trash * Restore File To restore a file that has been moved to the trash, but has not yet been purged, make a POST request to the /files/:file_id… # Restore File To restore a file that has been moved to the trash, but has not yet been purged, make a `POST` request to the `/files/:file_id` endpoint. This will place the file in the original folder if it is still available, or you optionally can specify a `parent` folder. **Reference:** https://developer.box.com/guides/trash/restore-file/ --- ## Untitled *Type: guide | Category: Trash * Restore Folder To restore a folder that has been moved to the trash, but has not yet been purged, make a POST request to the /folders… # Restore Folder To restore a folder that has been moved to the trash, but has not yet been purged, make a `POST` request to the `/folders/:folder_id` endpoint. This will place the folder in the original parent folder if it is still available, or you optionally can specify a `parent` folder. During a folder restoration operation, part of the file tree will be locked, such as the source folder for the request and all of its descendants, as well as the destination folder. During the restoration of the folder, no other move, copy, delete, or restore operation can be performed on the locked folders. **Reference:** https://developer.box.com/guides/trash/restore-folder/ --- ## Untitled *Type: guide | Category: Trash * Restore Web Link To restore a web link that has been moved to the trash, but has not yet been purged, make a POST request to the /web_links… # Restore Web Link To restore a web link that has been moved to the trash, but has not yet been purged, make a `POST` request to the `/web_links/:web_link_id` endpoint. This will place the web link in the original parent folder if it is still available, you optionally can specify a `parent` folder. **Reference:** https://developer.box.com/guides/trash/restore-web-link/ --- ## Untitled *Type: guide | Category: Uploads * Preflight Check The Pre-flight check API allows an application to verify that a file will be accepted by Box before it uploads any bytes. It… # Preflight Check The Pre-flight check API allows an application to verify that a file will be accepted by Box before it uploads any bytes. It can both be used for new files, as well as uploading new versions of existing files. ## Checklist Preflight checks perform all the same checks as if the file was actually uploaded including: - The permission of the application and the user to upload to the folder - Any file name collisions - Any file size caps and limits - Any folder and file name restrictions - Any folder and account storage quotas ## Check for new file To perform a check for a new file, call the [`OPTIONS /files/content`](e://options_files_content) API with the same parameters (except for the binary content) as if uploading an actual file. ## Check for new file version To perform a check for a new version of a file, call the [`OPTIONS /files/:id/content`](e://options_files_content) API with the same parameters (except for the binary content) as if uploading an actual file. ## Checks & Chunk Uploads When performing a [chunked upload](g://uploads/chunked), performing a preflight check is not required as [creating an Upload Session](g://uploads/chunked/create-session) also performs a preflight check. ## Response codes When the API call detects any problems, a HTTP `409 Conflict` status code is returned with a message to describe the possible conflict. If no problems were discovered, it returns a HTTP `200 OK` status code and the upload can proceed. A `200 OK` response does not guarantee that the upload call will actually succeed. Pre-flight checks have show to reduce failed uploads by over 99%, yet concurrency issues still come into play when uploading a file. Highly active folders, common filenames, and accounts near their quota limits may get a `200 OK` for the preflight check, and then have a real conflict during the actual upload. ## Response body In many cases, the preflight check will return valuable data in the API response when a conflict has been detected. For example, when a name collision has been detected, the application can use the `SHA-1` that is returned in the error response to check if the existing file is identical to the one it is trying to upload. **Reference:** https://developer.box.com/guides/uploads/check/ --- ## Untitled *Type: guide | Category: Uploads * Uploads The Box API supports two distinct methods of file upload. The direct file upload API supports files up to 50MB in size and sends all… # Uploads The Box API supports two distinct methods of file upload. The direct file upload API supports files up to 50MB in size and sends all the binary data to the Box API in 1 API request. The [chunked upload APIs](g://uploads/chunked) support files from 20MB in size and allow an application to upload the file in parts, allowing for more control to catch any errors and retry parts individually. To upload files to the Archive folder, you need to first enable the Global Content Manager (GCM) scope in the Developer Console. ## Upload limits Upload limits are dictated by the type of account of the authenticated user. More information can be found [in our community article on this topic](https://support.box.com/hc/en-us/articles/360043697314-Understand-the-Maximum-File-Size-You-Can-Upload-to-Box). ## Preflight check The Pre-flight check API allows an application to verify that a file will be accepted by Box before it uploads any bytes. It can both be used for new files, as well as uploading new versions of existing files. Learn more about pre-flight checks ## Upload domain Uploads to Box happen via a different domain (`upload.box.com`) than regular API calls. This is something to keep in mind when writing your own upload code. All the Box SDKs will take care of choosing the right domain for the right API call. **Reference:** https://developer.box.com/guides/uploads/ --- ## Untitled *Type: guide | Category: Users * Create App User App Users are programmatic user accounts that may only be created by apps that are using JWT authentication. They are… # Create App User App Users are programmatic user accounts that may only be created by apps that are using [JWT authentication](g://authentication/jwt/jwt-setup). They are designed to allow for users, groups, or processes to be represented behind the scenes in an application without the need for the user to have a Box account to log in. App users can only be accessed by the Box application through the APIs and do not have credentials to log in to `box.com` directly. ## Common App User Patterns Typically app users are created for a number of different patterns: - To represent a single application user or group of users without a `box.com` account. - To represent an application process, such as having the app user monitor all events within an enterprise. - To provide the application with the ability to completely control the file and folder structure of a user account without the possibility of that content being modified through the `box.com` web app. ## Creating a New App User To generate a new app user, the minimal information that will be required will be a name for the app user. To see all available optional parameters that may be set when creating an app user, see the [create user endpoint](endpoint://post-users). Before you can make any changes to the newly created account, you need to click the link you receive in the confirmation email. Once the app user is created a user object will be returned. Within the user object is an ID for the app user, which may be used to make API requests to modify the user in the future. **Reference:** https://developer.box.com/guides/users/create-app-user/ --- ## Untitled *Type: guide | Category: Users * Create Managed User To generate a new managed user, the minimal information that will be required will be a name and an email address for… # Create Managed User To generate a new managed user, the minimal information that will be required will be a name and an email address for the managed user. The email address supplied when creating a managed user must be unique. It cannot already be associated with an existing Box user. To see all available optional parameters that may be set when creating an app user, see the [create user endpoint](endpoint://post-users). Before you can make any changes to the newly created account, you need to click the link you receive in the confirmation email. A user object will be returned from the create user request. Within the user object is an ID for the managed user, which may be used to make API requests to modify the user in the future. Once a new managed user is created the email address used will receive an email from Box asking them to create a password for the account. The account will be in a `pending` state until that action has taken place. For security reasons passwords cannot be supplied when creating a new managed user **Reference:** https://developer.box.com/guides/users/create-managed-user/ --- ## Untitled *Type: guide | Category: Users * Delete User The process for deleting both app and managed users is the same. To delete a user account, supply the user ID for the account… # Delete User The process for deleting both app and managed users is the same. To delete a user account, supply the user ID for the account that should be removed. There are also two optional parameters that may be set when deleting a user account: - force: Whether the user should be deleted even if the account still has content in it. - notify: Whether the user will receive a notification that the account was deleted. The delete user request will fail if the user account still has content in it. To resolve this, either [transfer all files or folders](g://users/deprovision/transfer-folders) to another account or use the optional `force` parameter. **Reference:** https://developer.box.com/guides/users/delete-user/ --- ## Untitled *Type: guide | Category: Users * Users The Box API supports a variety of users, ranging from real employees logging in with their Managed User account, to applications using… # Users The Box API supports a variety of users, ranging from real employees logging in with their Managed User account, to applications using App Users to drive powerful automation workflows. Learn more about user types ## (De-)Provision Users Managing the onboarding and offboarding of employees, customers, and users is a common requirement in the lifespan of a Box application. During account provisioning the main tasks that will be needed will be: - How to create new app and managed user accounts to represent the users. - How to instantiate the new user account with common or repeatable folder and file architectures. During account deprovisioning the main tasks that will be needed will be: - How to transfer files and folders from one account to another for offboarding. - How to delete user accounts. **Reference:** https://developer.box.com/guides/users/ --- ## Untitled *Type: guide | Category: Web Links * Create Web Link To create a web link in Box, you will need to provide our API with a folder id and the url you want the web link to be… # Create Web Link To create a web link in Box, you will need to provide our API with a folder `id` and the `url` you want the web link to be linked to. The `url` must start with `http://` or `https://`. **Reference:** https://developer.box.com/guides/web-links/create/ --- ## Untitled *Type: guide | Category: Web Links * Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web Links are… # Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web Links are treated similarly to file objects, which means that they have the same support for creating shared links, allow for copying, permanent deletion, and restoration. **Reference:** https://developer.box.com/guides/web-links/ --- ## Untitled *Type: guide | Category: Web Links * Delete Web Link To remove a web link in Box you will need to provide our API with the ID of the web link. # Delete Web Link To remove a web link in Box you will need to provide our API with the ID of the web link. **Reference:** https://developer.box.com/guides/web-links/delete/ --- ## Untitled *Type: guide | Category: Webhooks * Webhooks Webhooks allow you to monitor Box content for events, and receive notifications to a URL of your choice when they occur. For… # Webhooks Webhooks allow you to monitor Box content for events, and receive notifications to a URL of your choice when they occur. For example, a workflow may include waiting for a file to be downloaded to delete a shared link. A webhook can be set on the file and upon notification of the download event, a script can launch to make an API call to delete the shared link. ## Versions There are two types of webhooks: V1 and V2, which are compared below. For the ease of use, better security, more event triggers to choose from, and automatic retries we recommend to use V2 webhooks. | V1 | V2 | | --- | --- | | Created in the Developer Console. | Created in the Developer Console or with an API call. | | Set at the root level. | Set on specific files/folders, but cannot set at the root. | | Select from 14 event triggers. | Select from 30+ event triggers. | | Provides selected callback parameters. | Payload includes full object response & additional context info. | | No retry mechanism after notification delivery failure. | Retries up to 10 times after notification delivery failure. | | Does not support payload verification. | Supports payload verification. | | Notification URL can be HTTP or HTTPS. | Notification URL must be HTTPS. | | Does not scale well. | Scales well and has increased reliability. | **Reference:** https://developer.box.com/guides/webhooks/ --- ## Untitled *Type: guide | Category: Webhooks * Webhook Event Triggers V2 Files and Folders The following is a list of events that can be configured to trigger a V2 webhook. Some events… # Webhook Event Triggers ## V2 ### Files and Folders The following is a list of events that can be configured to trigger a V2 webhook. Some events are only available for files, while others are only available for folders. | Event | Triggered | File? | Folder? | | --- | --- | --- | --- | | COLLABORATION.CREATED | A collaboration is created. | No | Yes | | COLLABORATION.ACCEPTED | A collaboration is accepted. | No | Yes | | COLLABORATION.REJECTED | A collaboration is rejected. | No | Yes | | COLLABORATION.REMOVED | A collaboration is removed. | No | Yes | | COLLABORATION.UPDATED | A collaboration is updated. | No | Yes | | COMMENT.CREATED | A comment object is created. | Yes | Yes | | COMMENT.UPDATED | A comment object is edited. | Yes | Yes | | COMMENT.DELETED | A comment object is removed. | Yes | Yes | | DOCGEN_DOCUMENT_GENERATION_FAILED | Doc Gen failed to generate a document. | Yes | No | | DOCGEN_DOCUMENT_GENERATION_STARTED | Doc Gen started to create a document. | Yes | No | | DOCGEN_DOCUMENT_GENERATION_SUCCEEDED | Doc Gen succeeded to create a document. | Yes | No | | FILE.UPLOADED | A file is uploaded or moved to this folder. | No | Yes | | FILE.PREVIEWED | A file is previewed. | Yes | Yes | | FILE.DOWNLOADED | A file is downloaded. | Yes | Yes | | FILE.TRASHED | A file is moved to trash. | Yes | Yes | | FILE.DELETED | A file is permanently deleted. | Yes | Yes | | FILE.RESTORED | A file is restored from trash. | Yes | Yes | | FILE.COPIED | A file is copied. | Yes | Yes | | FILE.MOVED | A file is moved from one folder to another. | Yes | Yes | | FILE.LOCKED | A file is locked. | Yes | Yes | | FILE.UNLOCKED | A file is unlocked. | Yes | Yes | | FILE.RENAMED | A file is renamed. | Yes | Yes | | FOLDER.CREATED | A folder is created | No | Yes | | FOLDER.RENAMED | A folder is renamed. | No | Yes | | FOLDER.DOWNLOADED | A folder is downloaded. | No | Yes | | FOLDER.RESTORED | A folder is restored from trash. | No | Yes | | FOLDER.DELETED | A folder is permanently removed. | No | Yes | | FOLDER.COPIED | A folder is copied. | No | Yes | | FOLDER.MOVED | A folder is moved to a different folder. | No | Yes | | FOLDER.TRASHED | A folder is moved to trash. | No | Yes | | METADATA_INSTANCE.CREATED | A new metadata template instance is associated with a file or folder. | Yes | Yes | | METADATA_INSTANCE.UPDATED | An attribute (value) is updated/deleted for an existing metadata template instance associated with a file or folder. | Yes | Yes | | METADATA_INSTANCE.DELETED | An existing metadata template instance associated with a file or folder is deleted. | Yes | Yes | | SHARED_LINK.DELETED | A shared link is deleted. | Yes | Yes | | SHARED_LINK.CREATED | A shared link is created. | Yes | Yes | | SHARED_LINK.UPDATED | A shared link is updated. | Yes | Yes | | TASK_ASSIGNMENT.CREATED | A task is created. | Yes | Yes | | TASK_ASSIGNMENT.UPDATED | A task assignment is changed. | Yes | Yes | | SIGN_REQUEST.COMPLETED | A sign request is completed. | Yes | Yes | | SIGN_REQUEST.DECLINED | A sign request is declined. | Yes | Yes | | SIGN_REQUEST.EXPIRED | A sign request is expired. | Yes | Yes | | SIGN_REQUEST.SIGNER_EMAIL_BOUNCED | A signer's email is bounced. | Yes | Yes | | WEBHOOK.DELETED | A webhook is deleted. | No | No | ## V1 Events that can be configured to trigger a v1 webhook: - Sent, - Created, - Uploaded, - Commented, - Downloaded, - Previewed, - Moved, - Copied, - Task assigned, - Responded to task, - Locked, - Unlocked, - Deleted, - Collaborator added. **Reference:** https://developer.box.com/guides/webhooks/triggers/ --- ## Untitled *Type: guide | Category: API Calls * Pagination The Box API supports two ways to paginate collections. The most common way to paginate is through offset-based pagination which… # Pagination The Box API supports two ways to paginate collections. The most common way to paginate is through offset-based pagination which is often used where the list of items is of a fixed, predetermined length. In some cases an API endpoint supports marker-based pagination, either as an alternative to offset-based pagination or as a full replacement. Marker-based pagination is often used in cases where the length of the total set of items is either changing frequently, or where the total length might not be known upfront. **Reference:** https://developer.box.com/guides/api-calls/pagination/ --- ## Untitled *Type: guide | Category: API Calls * Marker-based Pagination APIs that use marker-based paging use the marker and limit query parameters to paginate through items in a… # Marker-based Pagination APIs that use marker-based paging use the `marker` and `limit` query parameters to paginate through items in a collection. Marker-based pagination is often used in cases where the length of the total set of items is either changing frequently, or where the total length might not be known upfront. ## Paging To fetch the first page of entries in a collection the API needs to be called either without the `marker` parameter, or with the `marker` set to `0`. The `limit` parameter is optional. ``` curl https://api.box.com/2.0/folders/0/items?limit=100&usemarker=true \ -H "authorization: Bearer ACCESS_TOKEN" ``` APIs that support both offset-based pagination and marker-based pagination require the `usemarker` query parameter to be set to `true` to ensure marker-based pagination is used. To fetch the next page of entries the API needs to be called with an `marker` parameter that equals value of the `next_marker` value that was received in the API response. ``` curl https://api.box.com/2.0/folders/0/items?marker=34332423&limit=100&usemarker=true \ -H "authorization: Bearer ACCESS_TOKEN" ``` The final page of items has been requested when the next `next_marker` value is `null` in the response object. At this point there are no more items to fetch. With marker-based paging there is no way to determine the total number of entries in a collection except by fetching them all. Applications should not retain the `next_marker` value long-term as the internal implementation of the markers may change over time. ## Marker & Limit The following query parameters are used to paginate a collection. | Query parameter | Type | Default | | | --- | --- | --- | --- | | marker | String | | The first position in the collection to return results from. This should be a value that was returned in a previous request. | | limit | Integer | Depends on API | The maximum number of entries to return. If the value exceeds the maximum, then the maximum value will be used. | | usemarker | Boolean | | An optional query parameter that can be used with API endpoints that support both types of pagination to select pagination type. Set to true to enforce marker-based pagination. | ## Collections When paginating collections, the API returns an object that contains the set of results as an array, as well as some information about the current page of results. | Field | Type | | | --- | --- | --- | | entries | Array | The page of items for this page. This will be an empty array if there are no results. | | next_marker | String | The value that can be used as the marker value to fetch the next page of results. If this value is null or an empty string there are no more results to fetch. | | limit | Integer | The limit used for this page of results. This will be the same as the limit query parameter unless it exceeded the maximum value allowed for this API endpoint. | ## Example endpoints Some endpoints that support marker-based pagination are: - [List items for a folder](e://get_folders_id_items) - [List a file's collaborations](e://get-files-id-collaborations) - [List all webhooks for a user](e://get-webhooks) - [List all users in an enterprise](e://get-users) - [List all items in the trash](e://get-folders-trash-items) **Reference:** https://developer.box.com/guides/api-calls/pagination/marker-based/ --- ## Untitled *Type: guide | Category: API Calls * Offset-based Pagination APIs that use offset-based paging use the offset and limit query parameters to paginate through items in a… # Offset-based Pagination APIs that use offset-based paging use the `offset` and `limit` query parameters to paginate through items in a collection. Offset-based pagination is often used where the list of items is of a fixed and predetermined length. ## Paging To fetch the first page of entries in a collection the API needs to be called either without the `offset` parameter, or with the `offset` set to `0`. The `limit` field is optional. ``` curl https://api.box.com/2.0/folders/0/items?offset=0&limit=100 \ -H "authorization: Bearer ACCESS_TOKEN" ``` To fetch the next page of entries the API needs to be called with an `offset` parameter that equals the sum of the previous `offset` value and limit returned in the previous result, `previous_offset + previous_limit`. ``` curl https://api.box.com/2.0/folders/0/items?offset=100&limit=100 \ -H "authorization: Bearer ACCESS_TOKEN" ``` Note that the `offset` should be increased by the previous `limit` and not by the size of the entries in the response array, as this may be less than the limit. Generally we advise using the value of the `limit` in the response object to increase the `offset` value. The final page of items has been requested when the next `offset` value exceeds the `total_count` value in the response object. At this point there are no more items to fetch. ## Offset & Limit The following query parameters are used to paginate a collection. | Query parameter | Type | Default | | | --- | --- | --- | --- | | offset | Integer | 0 | The (zero-based) offset of the first item returned in the collection. In a zero-based offset 0 is a correct value. | | limit | Integer | Depends on API | The maximum number of entries to return. If the value exceeds the maximum, then the maximum value will be used. | The maximum `offset` for offset-based pagination is `9999`. Marker-based pagination is recommended when a higher offset is needed. ## Collections When paginating collections, the API returns an object that contains the set of results as an array, as well as some information about the current page of results. | Field | Type | | | --- | --- | --- | | entries | Array | The page of items for this page. This will be an empty array if there are no results. | | offset | Integer | The offset used for this page of results | | limit | Integer | The limit used for this page of results. This will be the same as the limit query parameter unless it exceeded the maximum value allowed for this API endpoint. | | total_count | Integer | One greater than the offset of the last item in the entire collection. The total number of items in the collection may be less than total_count. | ## Example endpoints Some endpoints that support offset-based pagination are: - [List items for a folder](endpoint://get_folders_id_items) - [List a file's comments](endpoint://get-files-id-comments) - [List all items in the trash](endpoint://get-folders-trash-items) **Reference:** https://developer.box.com/guides/api-calls/pagination/offset-based/ --- ## Untitled *Type: guide | Category: API Calls * App Diagnostics Report The App Diagnostics Report provides a spreadsheet detailing each API call made by a given application during a… # App Diagnostics Report The App Diagnostics Report provides a spreadsheet detailing each API call made by a given application during a specified timeframe. The report gives you access to the `API Request ID`, which can be given to Box Support for troubleshooting purposes. This report will not include: - API calls made within the last 48 hours - Authorization and Token API calls We are working on including the above and thereby making the report suitable for real-time troubleshooting in the future. ## 1. Click on the App Diagnostics Tab To run the App Diagnostics Report, click the **App Diagnostics** option located along the top of your application's configuration section in the [Developer Console](https://app.box.com/developers/console). ## 2. Click Run App Diagnostics Report to configure your report Clicking **Run App Diagnostics Report** will display a popup to select report filters and parameters. ## 3. Select Report Parameters and Click Run You can select a date in the last two weeks, starting 48 hours prior to today. A report can be run for up to a total of 24 hours. Click **Run** to generate a report. ## 4. Access the Box Reports Folder Navigate to [All Files](https://app.box.com/folder/0) and locate the Box Reports folder. If this is your first time running a report, this folder is automatically generated. If you are an Admin, this is the same folder you access [Admin Console Reports](https://support.box.com/hc/en-us/articles/360043696534-Running-Reports). Open the folder. ## 5. Find and Open the latest Platform App Diagnostics Report Folder You will see any reports you have run in the Box Reports folder. Locate and open the most recent Platform App Diagnostics run folder. ## 6. Check the Status The report will take time to complete. You can see the status in the box at the top of the folder. ## 7. Report Completed Upon completion, the status will change, and the `.csv` file will appear in the folder. ## 8. Open the Report You can open the file in your web browser or download it to view locally. If you need help from [Box Support](https://support.box.com/hc/en-us/requests/new), you can send in the report with your ticket by attaching a downloaded copy or via shared link. The report has nine columns. | Column | Description | | | --- | --- | --- | | App Name | The name of the application | | | Client ID | The Client ID of the application | | | HTTP Status Code | The response code returned from Box | | | API Request Duration (ms) | The amount of time from API call to response | | | API Request ID | An unique identifier that can be used by Box Support | | | Resource | The primary resource accessed in the API call | | | Sub Resource | The secondary resource accessed in the API call | | | HTTP Method | The type of HTTP method used in the API call | | | API Request Timestamp | The timestamp of the API call | | **Reference:** https://developer.box.com/guides/api-calls/permissions-and-errors/app-diagnostics-report/ --- ## Untitled *Type: guide | Category: API Calls * Token & URL Expiration Across the Box API there are a few tokens, codes, and URLs that automatically expire. The following is a quick… # Token & URL Expiration Across the Box API there are a few tokens, codes, and URLs that automatically expire. The following is a quick overview of their respective expiration times. | | | | --- | --- | | Authorization Codes | Expires after 30 seconds | | Access Tokens | expires after 60 minutes | | Refresh Tokens | Expires after 60 days or 1 use | | Download URLs | Expires after 15 minutes | See each respective guide for more details. **Reference:** https://developer.box.com/guides/api-calls/permissions-and-errors/expiration/ --- ## Untitled *Type: guide | Category: API Calls * Errors The Box APIs uses HTTP status codes to communicate if a request has been successfully processed or not. Client error Most client… # Errors The Box APIs uses [HTTP status codes](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) to communicate if a request has been successfully processed or not. ## Client error Most client errors in the HTTP 4XX, and some server errors in the HTTP 5XX range returns a standard client error JSON object. ``` { "type": "error", "status": 400, "code": "bad_digest", "help_url": "https://developer.box.com/guides/api-calls/permissions-and-errors/common-errors/", "message": "The specified content-md5 did not match what we received", "request_id": "abcdef123456" } ``` See the [Client Error resource](resource://client_error) for more details. ## Common error codes Check our [Developer Troubleshooting Articles](https://support.box.com/hc/en-us/sections/360007552913-Troubleshooting-Box-Platform) for solution to common errors encountered when working with the Box APIs. ### 400 Bad Request | | | | --- | --- | | Error | bad_digest | | Message | The specified content-md5 did not match what we received. | | Solution | While uploading a file, a content-md5 header with the SHA-1 hash of the file can be supplied to ensure that the file is not corrupted in transit. The SHA-1 hash that was supplied in the request did not match what was received in the upload. Supply a valid SHA-1 hash of the uploaded file. | | | | | Error | bad_request | | Message | | | Solution | Required parameters supplied in the API request are either missing or invalid. Check the extended error message in the response body for more details. | | | | | Error | cannot_make_collaborated_subfolder_private | | Message | Cannot move a collaborated subfolder to a private folder unless the new owner is explicitly specified. | | Solution | Specify the ID of the user that the content should be transferred to by setting the owned_by.id field in the request. | | | | | Error | collaborations_not_available_on_root_folder | | Message | Root folder cannot be collaborated | | Solution | You cannot set collaborators on a user's root folder (folder ID 0). Use a different folder ID than the root folder. | | | | | Error | cyclical_folder_structure | | Message | Folder move creates cyclical folder structure | | Solution | The folder ID specified in the folder move would create a cyclical folder structure (for example moving a folder to a subfolder within itself). Change the folder ID for the folder move request. | | | | | Error | folder_not_empty | | Message | Cannot delete – folder not empty | | Solution | Delete all content from the folder before attempting to delete it. | | | | | Error | invalid_collaboration_item | | Message | Item type must be specified and set to 'folder' | | Solution | The item.type field of the collaboration item should be set to folder. | | | | | Error | invalid_grant | | Message | Verify the authorization code is set correctly in your request, or your application likely needs to get a new authorization code. | | Solution | The authorization code supplied in the API request is missing or no longer valid. Possible solutions are to verify that the access token is added correctly in the request. If correctly set, the access token may have expired. Attempt to refresh the access token or fetch a new one. | | | | | Error | invalid_grant | | Message | Current date time must be before the expiration date time listed in the 'exp' claim. | | Solution | This error occurs when the Unix time on your local machine and the Box server are out of sync. To fix this error, update the Unix time on your machine to match a synchronized time server, then try the request again. | | | | | Error | invalid_limit | | Message | Limit is not a valid number | | Solution | Add a valid numeric value for the supplied limit value. | | | | | Error | invalid_offset | | Message | Offset is not a valid number | | Solution | Add a valid numeric value for the supplied offset value. | | | | | Error | invalid_request_parameters | | Message | Invalid input parameters in request | | Solution | Invalid parameters were sent in the API request. Check the API reference documentation for the correct request parameters that should be supplied for the API operation. | | | | | Error | invalid_status | | Message | You can change the status only if the collaboration is pending | | Solution | The status of a collaboration can only be updated to accepted or rejected by the user specified in the accessible_by field when the current status is set to pending. | | | | | Error | invalid_upload_session_id | | Message | The upload session ID provided in the URL is not of a valid format. | | Solution | The session ID supplied when making a chunked upload API request was invalid. Use the same session ID from the session that was created. | | | | | Error | item_name_invalid | | Message | Item name invalid | | Solution | Verify that the file's name is valid. Box only supports file or folder names that are 255 characters or less. File names containing non-printable characters, names containing the characters /, \, <, >, :, ` | | | | | Error | item_name_too_long | | Message | Item name too long | | Solution | Shorten the length of the name that is being supplied for the item. The maximum length of a file or folder name in Box is 255 characters or less. | | | | | Error | metadata_after_file_contents | | Message | Metadata is included after file contents in a file upload request. | | Solution | Include the file metadata before the file's contents. | | Error | password_reset_required | | Message | User needs to reset password | | Solution | The user has not yet completed account setup steps. | | | | | Error | requested_page_out_of_range | | Message | Requested representation page out of range | | Solution | The range header supplied does not fit within the size of the specified item. Adjust the bounds to fit within the size of the item and try again. | | | | | Error | requested_preview_unavailable | | Message | Requested preview unavailable | | Solution | The thumbnail size requested for the file is not valid. See the reference docs for the API operation for available format sizes. | | | | | Error | sync_item_move_failure | | Message | Cannot move a synced item | | Solution | The item is set to be synced by the Box sync clients and cannot be moved. A possible solution is to set the sync_state of the item to not_synced. | | | | | Error | task_assignee_not_allowed | | Message | Assigner does not have sufficient privileges to assign task to assignee | | Solution | The user who is attempting to assign the task does not have the appropriate permissions to do so. Adjust the user permissions to allow the assignment of tasks. | | | | | Error | terms_of_service_required | | Message | User must accept custom terms of service before action can be taken | | Solution | The admin of your Box account has set custom terms of service and the user has not logged in to accept the terms yet. The user will need to accept the terms of service, or the admin will have to disable them, in order to proceed. More information is available here. | | | | | Error | user_already_collaborator | | Message | User is already a collaborator | | Solution | The user that you are attempting to collaborate in on an item is already collaborated on that item. This request is not needed. | | | | ### 401 Unauthorized | | | | --- | --- | | Error | unauthorized | | Message | Unauthorized | | Solution | Authorization token is not authorized, check extended error message in body for more details. | ### 403 Forbidden | | | | --- | --- | | Error | access_denied_insufficient_permissions | | Message | Access denied – insufficient permission | | Solution | The Access Token does not have the appropriate user permissions or scopes. See here for solution information. | | | | | Error | insufficient_scope | | Message | The request requires higher privileges than provided by the access token. | | Solution | This error is typically produced when scopes that are needed for the API operation are not enabled. Check your configured application scopes and reauthorize your application, if applicable. | | Error | access_denied_item_locked | | Message | Access denied – item locked | | Solution | You are attempting to access a locked item without appropriate permissions to access it. Unlock the item first, then try to access it again. | | | | | Error | access_from_location_blocked | | Message | | | Solution | You’re attempting to log in to Box from a location that has not been approved by your admin. Talk to your admin to resolve this issue. | | | | | Error | file_size_limit_exceeded | | Message | File size exceeds the folder owner’s file size limit | | Solution | See here for maximum file size limits based on account type. | | | | | Error | forbidden | | Message | | | Solution | Client does not have permission to upload to this session. Only the user who initiated the upload session may upload to it. | | | | | Error | forbidden_by_policy | | Message | Access denied – Blocked by Shield Access Policy | | Solution | Shield access policies applied on your enterprise have prevented this action. Contact your enterprise admin to adjust the applied Shield access policies. | | | | | Error | forbidden_by_policy | | Message | Access denied – Blocked by Shield Malware Detection Rule | | Solution | An active Shield malware detection rule prevents download or local editing of potentially malicious content, but preview and online editing remain available. Contact your enterprise admin to adjust the applied Shield policies. | | | | | Error | incorrect_shared_item_password | | Message | | | Solution | A password is required for the shared item, but it was either incorrect or not supplied. | | | | | Error | storage_limit_exceeded | | Message | Account storage limit reached | | Solution | The storage limit of the account has been reached. Either upgrade your account or permanently delete content to continue. Content that is simply moved to the trash will still count towards the account total until it is permanently deleted. | | | | | Error | user_email_confirmation_required | | Message | User needs to complete email confirmation | | Solution | The user has not yet completed steps for email confirmation. | | | | | Error | cors_origin_not_whitelisted | | Message | Access denied - Did you forget to safelist your origin in the CORS configuration of your app? | | Solution | Your application tried to access the Box API from a website. The application needs to explicitly allow Cross Origin Resource Sharing for the domain your site is hosted on. | ### 404 Not Found | | | | --- | --- | | Error | not_found | | Message | | | Solution | The resource could not be found. Check the extended error message in the response body for more details. | | | | | Error | not_trashed | | Message | Item is not trashed | | Solution | The item that is to be permanently deleted is not in the trash. Send the item to the trash first. | | | | | Error | preview_cannot_be_generated | | Message | Preview cannot be generated | | Solution | You are not able to generate a preview thumbnail for the specified file. | | | | | Error | trashed | | Message | Item is trashed | | Solution | The item that is to be accessed is in the trash and unavailable for modification. Move the item out of the trash and try again. | ### 405 Method Not Allowed | | | | --- | --- | | Error | method_not_allowed | | Message | Method Not Allowed | | Solution | The HTTP method used for the API operation is not allowed. Check the API reference documentation for the HTTP verb needed for the API operation. | ### 409 Conflict | | | | --- | --- | | Error | conflict | | Message | A resource with this value already exists | | Solution | This error may be produced when the resource to be created already exists. Check the extended error message in the response body for more details. | | | | | Error | item_name_in_use | | Message | Item with the same name already exists | | Solution | This error is produced when a resource with the same name already exists. Ensure that the resource name being added / modified is unique. | | | | | Error | name_temporarily_reserved | | Message | The item name is reserved by another processing item. Wait and then retry the request, or wait and check the parent folder to see if the name is in use. | | Solution | Two duplicate requests have been submitted at the same time. Box acknowledges the first and reserves the name, but a second duplicate request arrives before the first request has completed. Allow the first request to complete before sending the second. | | | | | Error | operation_blocked_temporary | | Message | The operation is blocked by another ongoing operation | | Solution | This error is returned when trying to access a folder that is blocked by another folder operation, such as a move or copy. Try again at a later interval. | | | | | Error | recent_similar_comment | | Message | A similar comment has been made recently | | Solution | A similar comment was recently made, and the API has flagged it as a potential duplicate. Verify that the comment was indeed made, or modify the comment content and try again. | | | | | Error | user_login_already_used | | Message | User with the specified login already exists | | Solution | A user with the same email already exists. Either refer to the existing user or specify a different email. | ### 410 Gone | | | | --- | --- | | Error | session_expired | | Message | | | Solution | The upload session associated with the given upload session ID has expired and can no longer be accessed. | | | | | Error | upload_failed | | Message | | | Solution | The upload session is in an unrecoverable state and cannot continue. This or other requests have resulted in the upload session reaching a bad state (for example parts overlapping). Possible situations where this may arise include when the maximum number of parts has been exceeded or when overlapping parts have been uploaded. | ### 411 Length Required | | | | --- | --- | | Error | length_required | | Message | content-length header was required, but not provided. | | Solution | Supply a content-length header within your API request. | ### 412 Precondition Failed | | | | --- | --- | | Error | precondition_failed | | Message | The resource has been modified. Retrieve the resource again and retry | | Solution | Check the extended error message in the response body for more details. | | | | | Error | sync_state_precondition_failed | | Message | The resource has been modified. Retrieve the resource again and retry | | Solution | Check the extended error message in the response body for more details. | ### 413 Request Entity Too Large | | | | --- | --- | | Error | request_entity_too_large | | Message | Request Entity too Large | | Solution | This error is produced when the size of the upload is more than the allowed maximum. Check the extended error message in the response body | ### 415 Unsupported Media Type | | | | --- | --- | | Error | unsupported_media_type | | Message | Previews for boxnote files are not yet supported. | | Solution | This error is produced when requested an embed preview of a Box Note. Embedded previews are currently unsupported for Box Notes. | ### 429 Too Many requests | | | | --- | --- | | Error | rate_limit_exceeded | | Message | Request rate limit exceeded, try again later. | | Solution | The client is performing operations too quickly and has been rate limited. Client is advised to retry their request after the amount of time specified by the retry-after header. There are four rate limits to be aware of. | ### 500 Internal Service Error | | | | --- | --- | | Error | internal_server_error | | Message | Internal Server Error | | Solution | Client should retry using exponential back-off strategy | ### 502 Bad Gateway | | | | --- | --- | | Error | bad_gateway | | Message | | | Solution | Client should retry using exponential back-off strategy | ### 503 Unavailable | | | | --- | --- | | Error | unavailable | | Message | Unavailable | | Solution | If a Retry-After header is provided in the response, the client should retry the request according to the header value. In rare situations, a write operation may eventually persist its changes after the 503 response is received by the client, so the client should handle this case upon retry. If the issue persists, check our Status Site for any known outage information. | **Reference:** https://developer.box.com/guides/api-calls/permissions-and-errors/common-errors/ --- ## Untitled *Type: guide | Category: API Calls * Rate Limits There are three common types of API call rate limitations that Box may use at its discretion to best protect network resources… # Rate Limits There are three common types of API call rate limitations that Box may use at its discretion to best protect network resources and preserve the quality of our customer experience. ## User based These rate limits protect our service from issues that may arise when a single user generates too much traffic. The number of API calls that a user can make in a minute is limited as described below. These limits apply to all Box user accounts and are the most common. Generally, they are initiated when a user exceeds approximately 1000 API calls/minute, but certain API endpoints may have different rate limits. ## Quality of service These rate limits are designed to protect the quality of service of our infrastructure. If there is resource contention in the infrastructure, we introduce automatic rate limits to prevent system degradation and outages. For instance, if an application happens to be accessing the same physical database server, such as the use of a file migration tool accessing related resources that access the same underlying physical resources, Box may impose temporary rate-limits when load spikes and adjust them as the system recovers. ## Licensing based All Box Business Plans come with a licensed number of permitted API calls per enterprise per month. These license based rate limits are designed to prevent excessive overages and misuse of network resources. If Box's infrastructure detects that a tool used by or on behalf of a customer has exceeded that customer's API license allocation or is intending to circumvent network controls, additional selective rate-limiting may be imposed. You can see the default API allocations licensed with a particular account level at our [pricing page](https://www.box.com/pricing), but note that some customers purchase Platform API Pricing plans that increase their allocation. ## Per API rate limits There are currently a few distinct rate limits in place within the Box API. General API calls - 1000 API requests per minute, per user Uploads - 240 file upload requests per minute, per user Search - 6 searches per second, per user, to the [search endpoint](e://get_search) Two additional limits are applied on top of the basic rate limit - 60 searches per minute, per user - 12 searches per second, per enterprise Box Sign - Create and resend sign request: 100 requests per minute, per user - Get sign request: 1000 requests per minute, per user ## Rate limit error When an application hits a rate limit, the API will return an API response with a HTTP status code of `429 Too Many Requests`. The response will include the following headers and JSON body. ``` retry-after: 100 ``` ``` { "type": "error", "status": 429, "code": "rate_limit_exceeded", "help_url": "https://developer.box.com/guides/api-calls/permissions-and-errors/common-errors/", "message": "Request rate limit exceeded, please try again later", "request_id": "abcdef123456" } ``` Please see the [Client Error resource](resource://client_error) for more details. The `retry-after` header provides guidance on the number of seconds to wait before the next API call can be retried. In general, we advise using an exponential back-off strategy for retrying API calls. **Reference:** https://developer.box.com/guides/api-calls/permissions-and-errors/rate-limits/ --- ## Untitled *Type: guide | Category: API Calls * Permissions and errors The following guides provide information on the permissions or errors related to the Box API. It includes pages on… # Permissions and errors The following guides provide information on the permissions or errors related to the Box API. It includes pages on [Common Errors](g://api-calls/permissions-and-errors/common-errors), [Rate Limits](g://api-calls/permissions-and-errors/rate-limits), [Scopes](g://api-calls/permissions-and-errors/scopes), [Token/URL Expiration](g://api-calls/permissions-and-errors/expiration), and the [App Diagnostic Report](g://api-calls/permissions-and-errors/app-diagnostics-report). **Reference:** https://developer.box.com/guides/api-calls/permissions-and-errors/ --- ## Untitled *Type: guide | Category: API Calls * Scopes When an application is created in the Developer Console, the user must configure application scopes. Similar to how users have… # Scopes When an application is created in the Developer Console, the user must configure application scopes. Similar to how users have permissions to access files and folders within Box, applications have their own set of permissions to perform certain actions on behalf of a Box user or a Box enterprise. The name for a set of permissions for an application is a "scope". In short, an application's scopes determine which [endpoints](page://reference) an application can successfully call and are reflected in the access provided by [Access Tokens](g://authentication/tokens) of the application. ## User permissions and scopes It is important to understand that even if an application has the right scopes to perform an action, the user associated with the Access Token making the call needs to have permission to perform the action as well and vice versa. For example, if your application is set up to read files, the authenticated user does need to have permission to read the file you are trying to access. To learn more about how scopes, token permissions, and user permissions work together, see our [security guide](g://security). ## Scopes & OAuth 2 authorization When sending a user through a client-side OAuth 2 flow to authorize your application it is possible to append a set of scopes to the authorization URL to further restrict the user's access token. For example, if you application has the `root_readonly` and `root_readwrite` scopes enabled, it is possible to restrict a user's access token to `root_readonly` by specifying this scope when redirecting the user. ``` GET https://account.box.com/api/oauth2/authorize?scope=root_readonly&client_id=.... ``` When the scope parameter is omitted the application will use the scopes that were set when the application was created. ## Self-service scopes These scopes are available through the Developer Console when configuring an application. Navigate to the **Application Scopes** section of the **Configuration** tab and select one or more of the following scope. ### Read all files and folders | | | | --- | --- | | OAuth Scope | root_readonly | | Application Scope | Read all files and folders stored in Box | Gives an application the ability to read all the files/folders for the authenticated user. Although this gives an application the permission to read files and folders, the user making the API call does need to have access to the items being accessed. In the case of a [JWT](g://authentication/jwt) application accessing a [Managed User's](page://platform/user-types/#managed-users) items, the Service Account's Token will need to either use the `as-user` [header](g://authentication/jwt/as-user) or create a [User Access Token](g://authentication/jwt/user-access-tokens) to directly authenticate as the user who has access to the content. ### Read and write all files and folders | | | | --- | --- | | OAuth Scope | root_readwrite | | Application Scope | Read and write all files and folders stored in Box | Gives an application write access for the authenticated user. This allows the application to upload files or new file versions, download content, create new folders, update or delete collaborations, create comments or tasks, and more. Although this gives an application read/write access to items, the user making the API call needs to have access to the content. ### Manage users The manage users scope in the Developer Console maps to two OAuth scopes. | | | | --- | --- | | OAuth Scope | manage_managed_users | | Application Scope | Manage users | Gives an application permission to manage [Managed Users](page://platform/user-types/#managed-users). It allows the app to change the user's primary login, reset their password, and change roles for managed users. Although this allows an application manage users, for client-side applications, the Access Token used must be associated with an Admin or Co-Admin with the correct permissions. Additionally, for JWT applications, the application must be configured with **App Access + Enterprise Access** [application access](g://authentication/jwt/jwt-setup/#application-access). | | | | --- | --- | | OAuth Scope | manage_app_users | | Application Scope | Manage users | Gives an application permission to manage [App Users](page://platform/user-types/#app-user), which means this scope only applies to server-side authenticated (JWT) applications. ### Manage groups | | | | --- | --- | | OAuth Scope | manage_groups | | Application Scope | Manage groups | Gives an application permission to manage an enterprise's groups. It allows the app to create, update, and delete groups, as well as manage group membership. Although this allows an application manage groups, for client-side applications, the Access Token used must be associated with an Admin Co-Admin with the correct permissions. Additionally, for JWT applications, the application must be configured with **App Access + Enterprise Access** [application access](g://authentication/jwt/jwt-setup/#application-access). ### Manage webhooks | | | | --- | --- | | OAuth Scope | manage_webhook | | Application Scope | Manage webhooks | Gives an application permission to create webhooks for a user. Please review webhook [limitations](g://webhooks/v2/limitations-v2). Most notably, there is a limit of 1000 webhooks per application, per user. ### Manage enterprise properties | | | | --- | --- | | OAuth Scope | manage_enterprise_properties | | Application Scope | Manage enterprise properties | Gives an application permission to view the enterprise event stream, as well as view and edit the enterprise's attributes and reports. It also allows the application to edit and delete device pins. Although this allows an application to enterprise properties, for client-side applications, the Access Token used must must be associated with an Admin Co-Admin with the correct permissions. ### Manage retention policies | | | | --- | --- | | OAuth Scope | manage_data_retention | | Application Scope | Manage retention policies | | Depends on | enterprise_content-scope | Gives an application permission to view and create retention policies with Box Governance. This requires the enterprise to have purchased [Box Governance](https://www.box.com/security/governance-and-compliance). This scope also requires the `enterprise_content` scope to function properly. These scopes can be requested by opening a ticket via our support channels. ### Manage signature requests | | | | --- | --- | | OAuth Scope | sign_requests.readwrite | | Application Scope | Manage signature requests | Gives an application permission to get, create, cancel, and resend sign requests. This scope requires the application to also have read/write scopes, which are automatically selected when enabled. In addition, an enterprise must have Sign enabled. ### Manage Box AI API | | | | --- | --- | | OAuth Scope | ai.readwrite | | Application Scope | Manage AI | Gives an application permission to send requests to Box AI API. ### Manage Box Relay | | | | --- | --- | | OAuth Scope | manage_triggers | | Application Scope | Manage Box Relay | Gives an application permission to get workflows and start flows of type `WORKFLOW_MANUAL_START` This scope requires the application to also have read/write scopes. ## Available on request There are some additional scopes that are only available upon request. To do so, please submit a ticket to our [support team](page://support). They will review these requests on an individual basis and only provide approval if the use case requires the scope. It is not possible to request extra scopes if your account is a free trial account. Before filing a support request for activation of the following scopes, log in to your paid enterprise account or [upgrade your free developer account](https://www.box.com/pricing/platform) to an enterprise account tier. ### Manage Legal Holds | | | | --- | --- | | OAuth Scope | manage_legal_holds | | Application Scope | Manage retention policies | | Depends on | enterprise_content-scope | Gives an application permission to view and create retention policies with Box Governance. This requires the enterprise to have purchased Box Governance. This scope depends on the `enterprise_content` scope to function properly. This scope can be requested by opening a ticket via our support channels. ### Suppress email notifications | | | | --- | --- | | Application Scope | Can suppress email notifications from API calls | Allows some types of [email notifications](g://api-calls/suppress-notifications) to be suppressed when API calls are made. ### Global Content Manager (GCM) | | | | --- | --- | | OAuth Scope | enterprise_content | | Application Scope | Global Content Manager | Allows Admins, [Co-Admins](%5Bhttps://support.box.com/hc/en-us/articles/1500005433721-Users-Groups-Settings#h_01GSE1DYJKTY9EXEWJEDKFHCNV%5D), and [Service Accounts](page://platform/user-types/#service-account) to retrieve any content they do not own or are not collaborators on within their enterprise, based on their enterprise settings. This scope is required to manage the retention policies and legal holds. # Side effects Enabling this scope on an application changes the behavior of some API calls, and most notably, makes it impossible to write content without explicitly authenticating as a user using the `as-user` header. Additionally, enabling this scope disables accessing content that is owned by users in another enterprise. For this reason, this scope will not be provisioned unless absolutely necessary. ## Scopes for downscoping In some cases an Access Token needs to be [downscoped](g://authentication/tokens/downscope) to a more strict permission level, especially when a token needs to be exposed to a client-side, public environment like a browser. The primary example for this is when using [Box UI Elements](https://github.com/box/box-ui-elements), which require an Access Token in the user's browser. The following is a list of **additional** scopes that can be used with the [`POST /oauth2/token`](endpoint://post-oauth2-token) endpoint to downscope an existing access token. | OAuth Scope | UI Element affected | Description | | --- | --- | --- | | annotation_edit | Preview | Allow user to edit & delete annotations | | annotation_view_all | Preview | Allows user to view annotations by all users | | annotation_view_self | Preview | Allows user to view their own annotations only | | base_explorer | Explorer | Allows access to content in the folder tree based on user/file/token permissions | | base_picker | Picker | Allows access to content in the folder tree based on user/file/token permissions | | base_preview | Preview | Allows the user to preview the file, nothing else | | base_sidebar | Sidebar | Allows the user to get basic file info needed for the sidebar UI element | | base_upload | Uploader | Allows upload into the folder specified under resource when downscoping the token | | item_delete | Explorer | Allows files and folders to be deleted | | item_download | Explorer, Preview | Allows files or a folder's content to be downloaded | | item_preview | Explorer | Enables preview of a file | | item_rename | Explorer | Allows files and folders to be renamed | | item_share | Explorer, Picker | Allows the item specified under resource of the token exchange to be shared | | item_upload | Picker | Allows upload in the content picker | The standard OAuth scopes are also supported when downscoping. | OAuth Scope | Description | | --- | --- | | ai.readwrite | Manage AI API | | manage_managed_users | Manage managed users | | manage_app_users | Manage app users | | manage_data_retention | Manage retention policies | | manage_enterprise_properties | Manage enterprise properties | | manage_groups | Manage groups | | manage_webhook | Manage webhooks | | sign_requests.readwrite | Manage sign requests | **Reference:** https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/ --- ## Untitled *Type: guide | Category: API Calls * Versioning errors Box provides versioning capabilities for selected API endpoints. The version control system guarantees seamless… # Versioning errors Box provides versioning capabilities for selected API endpoints. The version control system guarantees seamless functioning of existing endpoint versions, even if Box introduces new ones. API versioning empowers Box to continually enhance its platform, while also offering third-party developers a reliable avenue for feature updates and deprecations. To stay informed about the API modifications, monitor the [Changelog](page://changelog) and maintain a current email address in the **App Info** section of the Developer Console. ## Error examples When using versioned API calls, you can encounter versioning-related errors. This reference lists the most common cases when errors appear and provides you with examples of such errors. ## Calling with incorrect box-version header If you call an API using an incorrect `box-version` header, the API will respond with an `HTTP error code 400 - Bad Request` error and provide the supported versions in the response message. The response will include one of the following status messages in `message` field: | Details | Message | | --- | --- | | box-version value is an unsupported API version or was sent malformed. | Invalid API version specified in 'box-version' header. | | The request headers did not include box-version header when versioned only endpoint was called. | Missing required box-version header. | | box-version is empty. | Invalid (empty) API version specified in 'box-version' header. | | box-version contained multiple version. It requires only one version per request. | The 'box-version' header supports only one header value per request, do not use comas. | | An unsupported API version is used for an existing endpoint. | Unsupported API version specified in 'box-version' header. | An example of a response with an incorrect `box-version` header: ``` { "type": "error", "status": 400, "code": "invalid_api_version", "help_url": "https://developer.box.com/reference/error-codes/invalid-api-version", "message": "Invalid API version specified in 'box-version' header. Supported API versions: [2024.0].", "request_id": "abcdef123456" } ``` ## Calling an incorrect API version in the URL Box documentation specifies API URLs. For instance, the Sign Requests endpoints are accessed via: `https://api.box.com/2.0/sign_requests/`. If you mistakenly make a call to an incorrect version, such as `https://api.box.com/3.0/sign_requests/`, the response returns an `HTTP error code 404 - Not Found` error. ## Calling a deprecated API When you use an API version that Box has marked as deprecated, the API will respond as usual. Additionally, it will append a `Deprecation` header, stating the deprecation date. For example: ``` Deprecation: date="Fri, 11 Nov 2026 23:59:59 GMT" Box-API-Deprecated-Reason: https://developer.box.com/reference/deprecated ``` You should monitor API responses to verify if the `Deprecation` header is present to accordingly plan the transition to a new API version. ## Calling a non-existent version If you attempt to use an outdated API version, such as `2025.0` which has reached its end-of-life, the response will return an `HTTP error code 404 - Not Found`. See [Calling an incorrect API version in the URL](#calling-an-incorrect-api-version-in-the-url) for more information. **Reference:** https://developer.box.com/guides/api-calls/permissions-and-errors/versioning-errors/ --- ## Untitled *Type: guide | Category: Box AI Studio * Create agents Box AI Studio is available only for Enterprise Advanced accounts. The POST /2.0/ai_agents endpoint allows you to create a new… # Create agents Box AI Studio is available only for Enterprise Advanced accounts. The `POST /2.0/ai_agents` endpoint allows you to create a new, custom [AI agent](g://box-ai/ai-agents/index). ## Send a request To send a request, use the `POST /2.0/ai_agents` endpoint. Make sure you have generated the developer token to authorize your app. See [getting started with Box AI](g://ai-studio/getting-started-ai-studio) for details. ### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Example | | --- | --- | --- | | type | The type of agent used to handle queries. | ai_agent | | name | The name of the AI Agent. | My AI Agent | | access_state | The state of the AI Agent. Value is one of enabled disabled. | enabled | | icon_reference | The icon reference of the AI Agent. It should have format of the URL https://cdn01.boxcdn.net/app-assets/aistudio/avatars/<file_name> , where the possible values of file_name are: logo_boxAi.png,logo_stamp.png, logo_legal.png,logo_finance.png,logo_config.png,logo_handshake.png logo_analytics.png,logo_classification.png. | https://cdn01.boxcdn.net/app-assets/aistudio/avatars/logo_analytics.svg | | allowed_entities | List of allowed users or groups. | | | ask | The AI Agent to be used for ask. | ask | | extract | The AI Agent to be used for extraction. | | | text_gen | The AI agent used for generating text. | | **Reference:** https://developer.box.com/guides/ai-studio/ai-studio-agents/create-agents/ --- ## Untitled *Type: guide | Category: Box AI Studio * Delete AI agent The DELETE /2.0/ai_agents/{id} endpoint allows you to delete a custom AI agent based on its ID. Send a request To send a… # Delete AI agent The `DELETE /2.0/ai_agents/{id}` endpoint allows you to delete a custom AI agent based on its ID. ## Send a request To send a request, use the `DELETE /2.0/ai_agents/{id}` endpoint. ### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Example | | --- | --- | --- | | agent_id | The ID of the agent to delete. | 1234 | **Reference:** https://developer.box.com/guides/ai-studio/ai-studio-agents/delete-agents/ --- ## Untitled *Type: guide | Category: Box AI Studio * Get agents Box AI Studio is available only for Enterprise Advanced accounts. List all AI agents The GET /2.0/ai_agents endpoint allows you… # Get agents Box AI Studio is available only for Enterprise Advanced accounts. ## List all AI agents The `GET /2.0/ai_agents` endpoint allows you to list all AI agents based on the provided parameters. ### Send a request To send a request, use the `GET /2.0/ai_agents` endpoint. Make sure you have generated the developer token to authorize your app. See [getting started with Box AI Studio](g://ai-studio/getting-started-ai-studio) for details. #### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Example | | --- | --- | --- | | mode | The mode to filter the agent configuration to return. Possible values are: ask, text_gen, and extract. | ask | | fields | The fields to return in the response. | ask | | agent_state | The state of the agent to return. Value is one of enabled,disabled. | enabled | | fields | The fields to return in the response. Value is one of ask, text_gen, extract. | ask | | include_box_default | Whether to include the Box default agents in the response. | true | | limit | The maximum number of items to return per page. | 1000 | | marker | Defines the position marker at which to begin returning results. | JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii | **Reference:** https://developer.box.com/guides/ai-studio/ai-studio-agents/get-agents/ --- ## Untitled *Type: guide | Category: Box AI Studio * Get AI agent by ID The GET /2.0/ai_agents/{id} endpoint allows you to list a specific AI agent by the agent_id parameter. Send a request To… # Get AI agent by ID The `GET /2.0/ai_agents/{id}` endpoint allows you to list a specific AI agent by the `agent_id` parameter. ## Send a request To send a request, use the `GET /2.0/ai_agents/{id}` endpoint. ### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Example | | --- | --- | --- | | agent_id | The agent id to get. | 1234 | | fields | The fields to return in the response. | ask | **Reference:** https://developer.box.com/guides/ai-studio/ai-studio-agents/get-agent-id/ --- ## Untitled *Type: guide | Category: Box AI Studio * AI studio agents Box AI Studio is available only for Enterprise Advanced accounts. Create, list, update, and delete custom AI agents. # AI studio agents Box AI Studio is available only for Enterprise Advanced accounts. Create, list, update, and delete custom AI agents. **Reference:** https://developer.box.com/guides/ai-studio/ai-studio-agents/ --- ## Untitled *Type: guide | Category: Box AI Studio * Update AI agent The PUT /2.0/ai_agents/{id} endpoint allows you to update a custom AI agent based on its ID. Send a request To send a… # Update AI agent The `PUT /2.0/ai_agents/{id}` endpoint allows you to update a custom AI agent based on its ID. ## Send a request To send a request, use the `PUT /2.0/ai_agents/{id}` endpoint. ### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Example | | --- | --- | --- | | type | The type of agent used to handle queries. | ```` | | name | The name of the AI Agent. | My AI Agent | | access_state | The state of the AI Agent. Value is one of enabled disabled. | enabled | | icon_reference | The icon reference of the AI Agent. It should have format of the URL https://cdn01.boxcdn.net/app-assets/aistudio/avatars/<file_name>, where possible values of file_name are: logo_boxAi.png,logo_stamp.png,logo_legal.png,logo_finance.png,logo_config.png,logo_handshake.png,logo_analytics.png,logo_classification.png | https://cdn01.boxcdn.net/app-assets/aistudio/avatars/logo_analytics.svg | | allowed_entities | List of allowed users or groups. | | | ask | The AI Agent to be used for ask. | ask | | extract | The AI Agent to be used for extraction. | | | text_gen | The AI agent used for generating text. | | **Reference:** https://developer.box.com/guides/ai-studio/ai-studio-agents/update-agents/ --- ## Untitled *Type: guide | Category: Applications * Integrations Box Integrations is the first place for Box users to find out about applications they can use in combination with Box. If your… # Integrations [Box Integrations](https://app.box.com/services) is the first place for Box users to find out about applications they can use in combination with Box. If your application can be used by other enterprises, listing your service in under **Integrations** can be a great way to find new users. Integrations group apps into sections so that you can quickly find featured, most popular, or recently added apps. ## Developing a platform app or becoming a Box Partner If you need more information on developing a platform app for the Box Integrations or becoming a Box Partner, visit our [Box Partner Resources](https://support.box.com/hc/en-us/sections/21356597387539-Box-Partner-Programs) guides on our community site. ## Publishing a platform app Use the following steps to publish a platform app in Box Integrations. ### Prerequisites Your application must meet the following requirements: - The platform app is in a finished state and ready for production usage. - The platform app leverages OAuth 2.0 authentication, as Integrations do not support any other authentication methods. - You are a developer with access to the platform app in the **Developer Console**. ### Steps Navigate to the Developer Console > **My Platform Apps** and select the app you want to publish. Select the **Publishing** tab from the top menu. Read through the submission checklist and check the confirmation checkbox if your app meets all the requirements. Fill in the form by providing: - the categories your app falls under - a short and a long description - screenshots and an app icon - supplementary information that will be used to support the users Use the **Preview** button in the top right corner to see how your application will look when listed. Finally, submit the application for approval by clicking the **Submit for Approval** button. Once a request for approval is received, the Box Partner team will be notified and review your request as soon as possible. For any questions, email [`integrate@box.com`](mailto:integrate@box.com). ## Unpublishing a platform app Once approved and published, a platform app can be unpublished from the same control panel: 1. Navigate to the **Developer Console** and select your platform app. 2. Select the **Publishing** tab. 3. You can now unpublish the app. **Reference:** https://developer.box.com/guides/applications/integrations/ --- ## Untitled *Type: guide | Category: Applications * Limited Access App A Limited Access App is used when leveraging Box View or previewing Box content within another application. This type of… # Limited Access App A Limited Access App is used when leveraging [Box View](g://embed/box-view) or previewing Box content within another application. This type of application can only interact with a [limited number of endpoints](g://authentication/app-token/endpoints). ## Authentication methods Limited Access Apps only support App Token authentication. Learn more about App Tokens ## When to use A Limited Access App is best used when the application: - wants to use Box View or only Box's preview services - only needs to access a [limited number of endpoints](g://authentication/app-token/endpoints) ## Use cases - Showcasing a creative professional’s portfolio on their website - Providing user manuals and product spec documents on a support site - A custom document viewer to view e-books or annotate architectural floor plans ## Approval Limited Access Apps may require approval before use. Learn how to approve Limited Access Apps **Reference:** https://developer.box.com/guides/applications/app-types/limited-access-apps/ --- ## Untitled *Type: guide | Category: Applications * Application Types The following is an overview of the different Box Application types you can create. Application Type Authentication… # Application Types The following is an overview of the different Box Application types you can create. | Application Type | Authentication Methods | | --- | --- | | Platform App | OAuth 2.0, JWT, or Client Credentials Grant | | Limited Access App | App Token | | Custom Skill | No selection needed | Learn how to select an application type **Reference:** https://developer.box.com/guides/applications/app-types/ --- ## Untitled *Type: guide | Category: Applications * Platform App Platform Apps encompass most use cases and is the most flexible application type. A platform application typically presents Box… # Platform App Platform Apps encompass most use cases and is the most flexible application type. A platform application typically presents Box functionality to a user within a custom interface. Box offers pre-built, customizable user interface components, known as [UI Elements](g://embed/ui-elements), for functionality like browsing, searching, and previewing content. ## Authentication methods Platform Apps support [OAuth 2.0](g://authentication/oauth2), [JWT](g://authentication/jwt), and [Client Credentials Grant](g://authentication/client-credentials). Learn more about authentication methods ## When to use A Platform App is best used when the application: - Wants to use [OAuth 2.0](g://authentication/oauth2), [JWT](g://authentication/jwt) or [Client Credentials Grant](g://authentication/client-credentials) for authentication. - Wants to upload and download files - Wants the freedom to access both their own files, as well as files owned by [managed or external users](g;//getting-started/user-types/#managed-users/). - Wants the option to list the application in the Box Integrations - Wants to provide integration into the Box Web App ## Use cases Example use cases for a Platform App include: A file vault in an application that allows an end user to access files that have been shared with them, while also providing access for employees to the same files through the Box Web app. An example of this is financial advisor sharing statements and investment prospectuses with investors that can be viewed and commented on within a platform application. A file upload feature in an application that allows an end user to submit and upload files from within a custom-built application to Box. These uploads then initiate a business process with the Box Web app. An example of this is a candidate submitting a PDF of a resume to a recruiting portal then can then be routed to an appropriate employee for review. ## Approval Platform Apps may require approval before use. Learn how to approve Platform Apps **Reference:** https://developer.box.com/guides/applications/app-types/platform-apps/ --- ## Untitled *Type: guide | Category: Applications * Select App Type Upon creating a new Box application in the Developer Console, you must first select one of the following types of… # Select App Type Upon creating a new Box application in the [Developer Console](https://app.box.com/developers/console), you must first select one of the following types of applications. The type of application you select is dependent on the use case for your project and only impacts the available authentication methods when configuring your application. You cannot change this selection later on. ## Platform App | | | | --- | --- | | Authentication methods | OAuth 2.0, JWT, or Client Credentials Authentication | | Notable Features | Webhooks, Integrations, and Web App Integrations | Platform App encompasses most use cases and is the most flexible option. This application type allows for interaction with our 150+ endpoints. For example, downloading/uploading, searching, applying metadata and more. Learn more about Platform Apps ## Limited Access App | | | | --- | --- | | Authentication methods | App Token | | Notable Features | Limited API access | A Limited Access App is best for leveraging [Box View](g://embed/box-view) or previewing Box content within another application. This type of application can only interact with a limited number of endpoints. Learn more about Limited Access Apps ## Custom Skills | | | | --- | --- | | Authentication methods | Access Tokens in Skills events | | Notable Features | Limited API access | A Custom Skill, or Box Skill is a type of application that performs custom processing for files uploaded to Box. Skills are designed to make it possible to use third-party Machine Learning services to automatically extract information from files uploaded to Box. Learn more about Custom Skills **Reference:** https://developer.box.com/guides/applications/app-types/select/ --- ## Untitled *Type: guide | Category: Applications * Custom Skill A Custom Skill, or Box Skill is a type of application that performs custom processing for files uploaded to Box. Skills are… # Custom Skill A Custom Skill, or Box Skill is a type of application that performs custom processing for files uploaded to Box. Skills are designed to make it straightforward to use third-party Machine Learning services to automatically extract information from files uploaded to Box and apply the resulting data as metadata on the file. Custom Skills need to be enabled on a folder by a Box Admin. After this an event is sent to the Skill's application server every time a file is uploaded to the folder. This application can then download the file, inspect it or hand it off to a machine learning service, and write powerful metadata to the file. Start building a Custom Skill ## Authentication methods Working with Custom Skills is simplified by the pre-authorized API credentials that are provided with every Skill Event. For this reason though, Custom Skills have limited API access. You do not need to select an authentication type to work with this type of application. ## When to use A Custom Skill is best used when the application: - Wants to only add metadata to files uploaded to Box - Does not want to upload new files or perform any other API calls - Wants to have way to pass files to Machine Learning services without having to handle authentication ## Use cases Example use cases for Custom Skills include: A process that automatically extracts license plate details from images and writes the details back to the file as keywords. A process that automatically detects faces in videos, and writes the timestamps at which these faces occur back to the file as a timeline. ## Approval Before a Custom Skill can be used it needs to be assigned to a folder for which the skill should trigger. Learn how to approve Custom Skills **Reference:** https://developer.box.com/guides/applications/app-types/custom-skills/ --- ## Untitled *Type: guide | Category: Authentication * Setup with Client Credentials Grant Prerequisites To set up a Platform App using server-side authentication, you will need to ensure you… # Setup with Client Credentials Grant ## Prerequisites To set up a Platform App using server-side authentication, you will need to ensure you have access to the [Developer Console](https://app.box.com/developers/console) from your Box enterprise account. Alternatively, you may sign up for a [developer account](https://account.box.com/signup/n/developer). ## App creation steps ### Navigate to the Developer Console Log into Box and go to the [Developer Console](https://app.box.com/developers/console). Select **Create Platform App**. ### Select application type Select **Platform App** from the list of application types. A modal will appear to prompt a selection for the next step. ### Provide basic application information To describe your app, provide an app name and description. Use the drop-down list to select the app's purpose. Depending on the option chosen, you might need to specify further details. | Purpose | Details | | --- | --- | | Automation, Custom Portal | Specify if the app is built by a customer or partner. | | Integration | Specify the integration category, external system name if the app is built by a customer or partner. | | Other | Specify the app purpose and if it is built by a customer or partner. | ### Select application authentication Select **Server Authentication (with Client Credentials Grant)** if you would like to verify application identity with a client ID and client secret, and confirm with **Create App**. Once you make a selection, you will not be able to change to a different authentication method without creating a new application. ## App Authorization Before the application can be used, a Box Admin needs to authorize the application within the Box Admin Console. Navigate to the **Authorization** tab for your application within the [Developer Console](https://app.box.com/developers/console). Click **Review and Submit** to send an email to your Box enterprise Admin for approval. More information on this process is available in our [authorization guide](g://authorization). Learn how to authorize a Platform Application ## Basic configuration ### Application Access An application's access level determines which users and content your app may access. By default, an application can only successfully interact with the content of its [Service Account](page://platform/user-types/#service-account) and any [App Users](page://platform/user-types). To also access existing Managed Users of an enterprise, navigate to the **Application Access** settings accessible via the **Configuration** tab of the [Developer console](https://app.box.com/developers/console) and set to **App + Enterprise Access**. ### Application Scopes An application's scopes determine which endpoints and resources an application can successfully call. See the [scopes guide](g://api-calls/permissions-and-errors/scopes) for detailed information on each option. ### CORS Domains If your application makes API calls from front-end browser code in Javascript, the domain that these calls are made from will need to be added to an allow-list due to [Cross Origin Resource Sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing), also known as CORS. If all requests will be made from server-side code, you may skip this section. To add the full URI(s) to the allow-list, navigate to the **CORS Domain** section at the bottom of the **Configuration** tab in the [Developer console](https://app.box.com/developers/console). ## Using SDKs and Client Credentials Grant To learn more about Client Credentials Grant for each SDK head over to: [.Net](https://github.com/box/box-windows-sdk-v2/blob/main/docs/authentication.md#server-auth-with-ccg) [Java](https://github.com/box/box-java-sdk/blob/main/doc/authentication.md#client-credentials-grant) [Python](https://github.com/box/box-python-sdk/blob/main/docs/usage/authentication.md#client-credentials-grant) [Node](https://github.com/box/box-node-sdk/blob/main/docs/authentication.md#client-credentials-grant-authentication) [IOS](https://github.com/box/box-ios-sdk/blob/main/docs/usage/authentication.md#client-credentials-grant) **Reference:** https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/ --- ## Untitled *Type: guide | Category: Authentication * Client Credentials Grant Follow the steps below if you would like to leverage server authentication and verify your application's identity… # Client Credentials Grant Follow the steps below if you would like to leverage server authentication and verify your application's identity using a client ID and client secret. ## Prerequisites - A Platform Application using Server Authentication (with Client Credentials Grant) authentication in the Box [Developer Console](https://app.box.com/developers/console) - [2FA](https://support.box.com/hc/en-us/articles/360043697154-Two-Factor-Authentication-Set-Up-for-Your-Account) enabled on your Box account for viewing and copying the application's client secret from the configuration tab - The application is [authorized](g://authorization) in the Box Admin Console Your client secret is confidential and needs to be protected. Because this is how we securely identify an application's identity when obtaining an Access Token, you do not want to freely distribute a client secret. This includes via email, public forums and code repositories, distributed native applications, or client-side code. If you would like to add more security mechanisms, we recommend using our standard JWT application type. ## How to use When making your API call to obtain an [Access Token](e://post-oauth2-token), your request body needs to contain your client ID and client Secret. Set the `grant_type` to `client_credentials`. If you would like to authenticate as the application's [Service Account](page://platform/user-types/#service-account): - set `box_subject_type` to `enterprise` - set `box_subject_id` to the enterprise ID If you would like to authenticate as an admin or a managed user: - set `box_subject_type` to `user` - set `box_subject_id` to the user ID - enable **App + Enterprise Access** and **Generate User Access Tokens** Box [Developer Console](https://app.box.com/developers/console) If you would like to authenticate as any application user: - set `box_subject_type` to `user` - set `box_subject_id` to the user ID - enable **Generate User Access Tokens** in the Box [Developer Console](https://app.box.com/developers/console) ## Common Errors ### Grant credentials are invalid During authentication, you can encounter the following error: ``` Grant credentials are invalid [400 Bad Request] invalid_grant - Grant credentials are invalid ``` This error indicates either: the client ID and client secret passed are incorrect or are not for the same application, the `box_subject_id` cannot be used based on the selected [application access](g://authentication/client-credentials/client-credentials-setup/#application-access). A CCG app with App Access Only can send in the `box_subject_type` of `enterprise` to authenticate as its service account, but it can't authenticate as a managed user or an admin. to use a `box_subject_type` of `user`, your application should be configured to generate user access tokens in the **Advanced Features** section of the **Configuration tab**. Once you make changes to the app settings, don't forget to [reauthorize](g://authorization/custom-app-approval#re-authorization-on-changes) the application in the Admin Console. - your application has not been authorized in the Box Admin Console **Reference:** https://developer.box.com/guides/authentication/client-credentials/ --- ## Untitled *Type: guide | Category: Authentication * JWT Auth Server-side authentication using JSON Web Tokens (JWT) is the most common way to authenticate to the Box API. JWT is an open… # JWT Auth Server-side authentication using JSON Web Tokens (JWT) is the most common way to authenticate to the Box API. JWT is an [open standard](https://jwt.io/) designed to allow powerful server-to-server authentication. Server-side authentication using JWT is only available to the Platform Application [app type](g://applications/app-types/select). This authentication method does not require end-user interaction and, if granted the proper privileges, can be used to act on behalf of any user in an enterprise. There are two ways you can verify an application's permissions: - using a public and private key pair - using a client id and client secret ([Client Credentials Grant](g://authentication/client-credentials)) To learn more about these options visit our guide on using [JWT without SDKs](g://authentication/jwt/without-sdk). Upon authorizing a JWT application in the Box Admin Console, a [Service Account](page://platform/user-types/#service-account) is automatically generated and is the default Access Token used when authenticating. This is an admin-like user and why applications leveraging JWT require explicit Box Admin approval before use. ## When to use JWT Server-side authentication with JWT is the ideal authentication method for apps that: - Work with users that don't have a Box account - Want to use their own identity system - Don't want users to have to know that they are using Box - Want to store data within the application's Box account and not within the the user's Box account **Reference:** https://developer.box.com/guides/authentication/jwt/ --- ## Untitled *Type: guide | Category: Authentication * as-user Header It is possible to for a JWT application to act on behalf of another user by leveraging the as-user header. In this situation… # as-user Header It is possible to for a JWT application to act on behalf of another user by leveraging the `as-user` header. ``` curl https://api.box.com/2.0/folders/0 \ -H "as-user: [USER_ID]" -H "authorization: Bearer [ACCESS_TOKEN]" ``` In this situation the user ID is the Box identifier for a user. User IDs can found for any user via the `GET /users` endpoint, which is only available to admins, or by calling the `GET /users/me` endpoint with an authenticated user session. ## Preconditions The application must be configured to perform actions as users in the [Developer Console](https://app.box.com/developers/console). Additionally, the authenticated user needs to be a user with Admin permissions, meaning either an Admin or Co-Admin. See our guide on [User Types](page://platform/user-types) for more details. You cannot use the `user_id` of [Service Accounts](page://platform/user-types/#service-account) in the as-user header. ## as-user using SDKs All of the [official Box SDKs](g://tooling/sdks) support acting on behalf of a user using the `as-user` header. ``` var user_client = new BoxClient(config, session, asUser: '[USER_ID]'); ``` ``` client.asUser([USER_ID]"); // client.asSelf(); ``` ``` user_to_impersonate = client.user(user_id='[USER_ID]') user_client = client.as_user(user_to_impersonate) ``` ``` client.asUser('[USER_ID]'); // client.asSelf(); ``` Please note that some of our SDKs create new clients for the other user, while others modify the existing client and provide a way to return to a state where the client authenticates for the original user itself. **Reference:** https://developer.box.com/guides/authentication/jwt/as-user/ --- ## Untitled *Type: guide | Category: Authentication * Setup with JWT A Platform App can be set up to use server-side authentication with JWT. Learn how JWT authentication works Prerequisites To… # Setup with JWT A Platform App can be set up to use server-side authentication with [JWT](g://authentication/jwt). Learn how JWT authentication works ## Prerequisites To set up a Platform App using server-side authentication, you will need to ensure you have access the [Developer Console](https://app.box.com/developers/console) from your Box enterprise account. Alternatively, you may sign up for a [developer account](https://account.box.com/signup/n/developer). ## App creation steps ### Navigate to the Developer Console Log into Box and go to the [Developer Console](https://app.box.com/developers/console). Select **Create Platform App**. ### Select application type Select **Platform App** from the list of application types. A modal will appear to prompt a selection for the next step. ### Provide basic application information To describe your app, provide an app name and description. Use the drop-down list to select the app's purpose. Depending on the option chosen, you might need to specify further details. | Purpose | Details | | --- | --- | | Automation, Custom Portal | Specify if the app is built by a customer or partner. | | Integration | Specify the integration category, external system name if the app is built by a customer or partner. | | Other | Specify the app purpose and if it is built by a customer or partner. | ### Select application authentication Select **Server Authentication (with JWT)** if you would like to verify application identity [with a key pair](g://authentication/jwt/without-sdk/#public-and-private-key-pair) and confirm with **Create Platform App**. Once you make a selection, you will not be able to change to a different authentication method without creating a new application. ## Public and private key pair This section can be skipped if you selected Server Authentication (Client Credentials Grant) as your authentication method. Once a Platform App is created leveraging Server Authentication with JWT, a key pair can be generated via the configuration tab within the [Developer Console](https://app.box.com/developers/console). Alternatively, you can generate your own and supply Box with the public key. Regardless of the method you select, your Box account will need to have [2FA](https://support.box.com/hc/en-us/articles/360043697154-Two-Factor-Authentication-Set-Up-for-Your-Account) enabled for security purposes. ### Generate a keypair (Recommended) If you would like to use a Box generated keypair, navigate to the [Developer Console](https://app.box.com/developers/console) where you can generate a configuration file. This file includes a public/private keypair and a number of other application details that are necessary for authentication. To generate this file, navigate to the **Configuration** tab of the [Developer Console](https://app.box.com/developers/console) and scroll down to the **Add and Manage Public Keys** section. Click the **Generate a Public/Private Keypair** button to have Box generate a keypair you. This will trigger the download of a JSON configuration file that you can move to your application code. For security reasons, Box will not store your private key. If you lose your private key, you will need to reset the entire keypair. ### Manually add keypair Alternatively, you may generate your own keypair and upload the public key to the [Developer Console](https://app.box.com/developers/console). To create a keypair using OpenSSL, open a terminal window and run the following commands. ``` openssl genrsa -des3 -out private.pem 2048 openssl rsa -in private.pem -outform PEM -pubout -out public.pem ``` # For Windows Systems Windows users can install and use the [Cygwin](http://www.cygwin.com/) package to run OpenSSL. Then, navigate to the configuration tab for your application within the [Developer console](https://app.box.com/developers/console) and scroll down to the **Add and Manage Public Keys** section. Click the **Add a Public Key** button, enter the public key generated using the steps above and click **Verify and Save**. ## App Authorization Before the application can be used, a Box Admin needs to authorize the application within the Box Admin Console. Navigate to the **Authorization** tab for your application within the [Developer Console](https://app.box.com/developers/console). Click **Review and Submit** to send an email to your Box enterprise Admin for approval. More information on this process is available in our [support article for app authorization](https://community.box.com/t5/Managing-Developer-Sandboxes/Authorizing-Apps-in-the-Box-App-Approval-Process/ta-p/77293). Learn how to authorize a Platform Application ## Basic configuration ### Application Access An application's access level determines which users and content your app may access. By default, an application can only successfully interact with the content of its [Service Account](page://platform/user-types/#service-account) and any [App Users](page://platform/user-types). To access existing Managed Users of an enterprise and groups that were not created by the app itself, navigate to the **Application Access** settings accessible in the **Configuration** tab of the [Developer console](https://app.box.com/developers/console) and set to **App + Enterprise Access**. Otherwise access to such Managed Users and groups will be blocked. ### Application Scopes An application's scopes determine which endpoints and resources an application can successfully call. See the [scopes guide](g://api-calls/permissions-and-errors/scopes) for detailed information on each option. ### CORS Domains If your application makes API calls from front-end browser code in Javascript, the domain that these calls are made from will need to be added to an allow-list due to [Cross Origin Resource Sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing), also known as CORS. If all requests will be made from server-side code, you may skip this section. To add the full URI(s) to the allow-list, navigate to the **CORS Domain** section at the bottom of the **Configuration** tab in the [Developer console](https://app.box.com/developers/console). **Reference:** https://developer.box.com/guides/authentication/jwt/jwt-setup/ --- ## Untitled *Type: guide | Category: Authentication * JWT with SDKs The official Box SDKs have built-in support for JWT authentication. This guide will take you through user authentication using… # JWT with SDKs The official Box SDKs have built-in support for JWT authentication. This guide will take you through user authentication using JWT with the use of the Box SDKs. JWT authentication is designed for working directly with the Box API without requiring a user to redirect through Box to authorize your application. ## Overview To complete a JWT authorization the following steps need to be completed. 1. Read the configuration file 2. Initialize an SDK client At the end of this flow, the application has a Box SDK client that can be used to make API calls on behalf of the application. The default method of authentication through JWT is inherently tied to the Service Account for the application. Any API call made with this token will seem to come from this application and will not have access to files and folders from other users without explicitly getting access them. ## Prerequisites Before we can get started, you will need to have completed the following steps. - Create a Box Application within the developer console - Create and download the private key configuration file for your application and save it as `config.json` - Ensure your Box Application is approved for usage within your enterprise ## 1. Read JSON configuration After creating a Box Application there should be a `config.json` file containing the application's private key and other details. The following is an example. ``` { "boxAppSettings": { "clientID": "abc...123", "clientSecret": "def...234", "appAuth": { "publicKeyID": "abcd1234", "privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\n....\n-----END ENCRYPTED PRIVATE KEY-----\n", "passphrase": "ghi...345" } }, "enterpriseID": "1234567" } ``` To use this object in the application it needs to be read from file. ``` var reader = new StreamReader("path/to/config.json"); var json = reader.ReadToEnd(); var config = BoxConfig.CreateFromJsonString(json); ``` ``` Reader reader = new FileReader("path/to/config.json"); BoxConfig config = BoxConfig.readFrom(reader); ``` ``` from boxsdk import JWTAuth config = JWTAuth.from_settings_file('path/to/config.json') ``` ``` var config = require("path/to/config.json"); ``` # Parsing JSON In some programming languages there is more than one way to read and parse JSON from a file. Refer to guides on your preferred programming language for more complete guides, including error handling. ## 2. Initialize SDK client The next step is to configure the Box SDK with the configuration and then initialize the client to connect as the application. ``` var sdk = new BoxJWTAuth(config); var token = sdk.AdminToken(); BoxClient client = sdk.AdminClient(token); ``` ``` BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(config); ``` ``` client = Client(config) ``` ``` var sdk = BoxSDK.getPreconfiguredInstance(config); var client = sdk.getAppAuthClient("enterprise"); ``` # Service Accounts At this point the application is authenticated as an application user, not as a managed or app user. Head over to our guide on User Types to learn more about the different types of users. ## Summary By now the application should be able to authorize an application using JWT with any of our official SDKs, by using the following steps. 1. Read the configuration file 2. Initialize an SDK client To learn how to use this client head over to the guide on Making API calls. ## Using SDKs and JSON Web Tokens To learn more about JWT for each SDK head over to: [.Net](https://github.com/box/box-windows-sdk-v2/blob/main/docs/authentication.md#server-auth-with-jwt) [Java](https://github.com/box/box-java-sdk/blob/main/doc/authentication.md#server-authentication-with-jwt) [Python](https://github.com/box/box-python-sdk/blob/main/docs/usage/authentication.md#server-auth-with-jwt) [Node](https://github.com/box/box-node-sdk/blob/main/docs/authentication.md#server-auth-with-jwt) [IOS](https://github.com/box/box-ios-sdk/blob/main/docs/usage/authentication.md#server-auth-with-jwt) **Reference:** https://developer.box.com/guides/authentication/jwt/with-sdk/ --- ## Untitled *Type: guide | Category: Authentication * User Access Token It is possible for a JWT application to create an Access Token for a specific user instead of for the Service Account… # User Access Token It is possible for a JWT application to create an Access Token for a specific user instead of for the [Service Account](page://platform/user-types/#service-account). ## Preconditions The application must be configured to allow the creation of user Access Tokens. This setting can be found in the **Configuration** tab of the [Developer Console](https://app.box.com/developers/console). Additionally, the authenticated user needs to be a user with Admin permissions, meaning either an Admin, Co-Admin, or Service Account. See our guide on [User Types](page://platform/user-types) for more details. ## User Access Tokens with SDKs To create a Box SDK client that authenticates as a specific user, follow the steps described in the [JWT with SDK guide](g://authentication/jwt/with-sdk), but create a user client instead of an "Enterprise" client. ``` var userId = "12345"; var sdk = new BoxJWTAuth(config); var token = sdk.UserToken(appUserID); BoxClient client = sdk.UserClient(userToken, userId); ``` ``` String userId = "12345"; BoxDeveloperEditionAPIConnection api = new BoxDeveloperEditionAPIConnection.getAppUserConnection(userId, config) ``` ``` user = client.user(user_id='12345') auth = JWTAuth( client_id='[CLIENT_ID]', client_secret='[CLIENT_SECRET]', user=app_user, jwt_key_id='[JWT_KEY_ID]', rsa_private_key_file_sys_path='[CERT.PEM]', rsa_private_key_passphrase='[PASSPHRASE]' ) auth.authenticate_user() user_client = Client(auth) ``` ``` var sdk = BoxSDK.getPreconfiguredInstance(config); var client = sdk.getAppAuthClient('user', '12345'); ``` Learn more about using the Box SDKs with JWT ## User Access Tokens without SDKs To create a user Access Token that authenticates as a specific user, follow the steps as described in the [JWT without SDK guide](g://authentication/jwt/without-sdk) but instead of creating a claim for the enterprise, create one for a specific user ID. ``` var userId = "12345"; var claims = new List<Claim>{ new Claim("sub", userid), new Claim("box_sub_type", "user"), new Claim("jti", jti), }; ``` ``` String userId = "12345"; JwtClaims claims = new JwtClaims(); claims.setIssuer(config.boxAppSettings.clientID); claims.setAudience(authenticationUrl); claims.setSubject(userId); claims.setClaim("box_sub_type", "user"); claims.setGeneratedJwtId(64); claims.setExpirationTimeMinutesInTheFuture(0.75f); ``` ``` user_id = '12345' claims = { 'iss': config['boxAppSettings']['clientID'], 'sub': user_id, 'box_sub_type': 'user', 'aud': authentication_url, 'jti': secrets.token_hex(64), 'exp': round(time.time()) + 45 } ``` ``` let user_id = '12345'; let claims = { iss: config.boxAppSettings.clientID, sub: user_id, box_sub_type: "user", aud: authenticationUrl, jti: crypto.randomBytes(64).toString("hex"), exp: Math.floor(Date.now() / 1000) + 45 }; ``` ``` user_id = '12345' claims = { iss: config['boxAppSettings']['clientID'], sub: user_id, box_sub_type: 'user', aud: authentication_url, jti: SecureRandom.hex(64), exp: Time.now.to_i + 45 } ``` ``` $userId = '12345'; $claims = [ 'iss' => $config->boxAppSettings->clientID, 'sub' => $userId, 'box_sub_type' => 'user', 'aud' => $authenticationUrl, 'jti' => base64_encode(random_bytes(64)), 'exp' => time() + 45, 'kid' => $config->boxAppSettings->appAuth->publicKeyID ]; ``` Learn more about manually using JWT authentication **Reference:** https://developer.box.com/guides/authentication/jwt/user-access-tokens/ --- ## Untitled *Type: guide | Category: Authentication * JWT without SDKs This guide takes you through JWT authentication without using a Box SDK. JWT does not require end-user interaction and is… # JWT without SDKs This guide takes you through JWT authentication without using a Box SDK. JWT does not require end-user interaction and is designed to authenticate directly with the Box API. To learn how to use this token visit our guide on making API calls. By default, the Access Token acquired with JWT is tied to the Service Account for the application. Any API call made with this token will come from the application. This account does not have access to any existing files or folders until the application's Service Account is added as a collaborator. It is possible to [act as another user](g://authentication/oauth2/as-user) using the `as-user` header or by requesting a [User Access Token](g://authentication/jwt/user-access-tokens). ## Using a key pair Follow the steps below if you would like to verify your application's identity using a public and private key pair. ### Prerequisites - A Platform Application using JWT authentication within the [Developer Console](https://app.box.com/developers/console) - A private key configuration file named `config.json`, which can be downloaded from the configuration tab of the [Developer Console](https://app.box.com/developers/console) - Ensure your application is [authorized](g://authorization) within the Box Admin Console ### 1. Read JSON configuration Your `config.json` file contains the application's private key and other details necessary to authenticate. The following is an example of this file. ``` { "boxAppSettings": { "clientID": "abc...123", "clientSecret": "def...234", "appAuth": { "publicKeyID": "abcd1234", "privateKey": "-----BEGIN ENCRYPTED PRIVATE KEY-----\n....\n-----END ENCRYPTED PRIVATE KEY-----\n", "passphrase": "ghi...345" } }, "enterpriseID": "1234567" } ``` To use this object in the application it needs to be read from file. ``` using System; using System.IO; using Newtonsoft.Json; class Config { public class BoxAppSettings { public class AppAuth { public string privateKey { get; set; } public string passphrase { get; set; } public string publicKeyID { get; set; } } public string clientID { get; set; } public string clientSecret { get; set; } public AppAuth appAuth { get; set; } } public string enterpriseID { get; set; } public BoxAppSettings boxAppSettings { get; set; } } var reader = new StreamReader("config.json"); var json = reader.ReadToEnd(); var config = JsonConvert.DeserializeObject<Config>(json); ``` ``` import java.io.FileReader; import com.google.gson.Gson; import com.google.gson.GsonBuilder; class Config { class BoxAppSettings { class AppAuth { String privateKey; String passphrase; String publicKeyID; } String clientID; String clientSecret; AppAuth appAuth; } BoxAppSettings boxAppSettings; String enterpriseID; } FileReader reader = new FileReader("config.json"); Gson gson = new GsonBuilder().create(); Config config = (Config) gson.fromJson(reader, Config.class); ``` ``` import json import os config = json.load(open('config.json')) ``` ``` const fs = require("fs"); const config = JSON.parse(fs.readFileSync("config.json")); ``` ``` require 'json' config = JSON.parse( File.read('config.json') ) ``` ``` $json = file_get_contents('config.json'); $config = json_decode($json); ``` # Parsing JSON In some programming languages there is more than one way to read and parse JSON from a file. Refer to guides on your preferred programming language for more complete guides, including error handling. ### 2. Decrypt private key To create the JWT assertion the application needs the private key from the configuration object. This private key is encrypted and requires a passcode to unlock. Both the encrypted key and passcode are provided in the configuration object. ``` using System.Security.Cryptography; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; // https://www.bouncycastle.org/csharp/index.html class PasswordFinder : IPasswordFinder { private string password; public PasswordFinder(string _password) { password = _password; } public char[] GetPassword() { return password.ToCharArray(); } } var appAuth = config.boxAppSettings.appAuth; var stringReader = new StringReader(appAuth.privateKey); var passwordFinder = new PasswordFinder(appAuth.passphrase); var pemReader = new PemReader(stringReader, passwordFinder); var keyParams = (RsaPrivateCrtKeyParameters) pemReader.ReadObject(); public RSA CreateRSAProvider(RSAParameters rp) { var rsaCsp = RSA.Create(); rsaCsp.ImportParameters(rp); return rsaCsp; } public RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey) { RSAParameters rp = new RSAParameters(); rp.Modulus = privKey.Modulus.ToByteArrayUnsigned(); rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned(); rp.P = privKey.P.ToByteArrayUnsigned(); rp.Q = privKey.Q.ToByteArrayUnsigned(); rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length); rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length); rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length); rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length); return rp; } public byte[] ConvertRSAParametersField(BigInteger n, int size) { byte[] bs = n.ToByteArrayUnsigned(); if (bs.Length == size) return bs; if (bs.Length > size) throw new ArgumentException("Specified size too small", "size"); byte[] padded = new byte[size]; Array.Copy(bs, 0, padded, size - bs.Length, bs.Length); return padded; } var key = CreateRSAProvider(ToRSAParameters(keyParams)); ``` ``` import java.io.StringReader; import java.security.PrivateKey; import java.security.Security; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder; import org.bouncycastle.operator.InputDecryptorProvider; import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; // https://www.bouncycastle.org/java.html Security.addProvider(new BouncyCastleProvider()); PEMParser pemParser = new PEMParser( new StringReader(config.boxAppSettings.appAuth.privateKey) ); Object keyPair = pemParser.readObject(); pemParser.close(); char[] passphrase = config.boxAppSettings.appAuth.passphrase.toCharArray(); JceOpenSSLPKCS8DecryptorProviderBuilder decryptBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider("BC"); InputDecryptorProvider decryptProvider = decryptBuilder.build(passphrase); PrivateKeyInfo keyInfo = ((PKCS8EncryptedPrivateKeyInfo) keyPair).decryptPrivateKeyInfo(decryptProvider); PrivateKey key = (new JcaPEMKeyConverter()).getPrivateKey(keyInfo); ``` ``` from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.serialization import load_pem_private_key appAuth = config["boxAppSettings"]["appAuth"] privateKey = appAuth["privateKey"] passphrase = appAuth["passphrase"] # https://cryptography.io/en/latest/ key = load_pem_private_key( data=privateKey.encode('utf8'), password=passphrase.encode('utf8'), backend=default_backend(), ) ``` ``` let key = { key: config.boxAppSettings.appAuth.privateKey, passphrase: config.boxAppSettings.appAuth.passphrase, }; ``` ``` require "openssl" appAuth = config['boxAppSettings']['appAuth'] key = OpenSSL::PKey::RSA.new( appAuth['privateKey'], appAuth['passphrase'] ) ``` ``` $private_key = $config->boxAppSettings->appAuth->privateKey; $passphrase = $config->boxAppSettings->appAuth->passphrase; $key = openssl_pkey_get_private($private_key, $passphrase); ``` # An alternative to loading private key from file the application might not want to keep both the private key and password stored on disk. An alternative option would be to pass in the password as an environment variable, separating the private key from the token used to unlock the key. ### 3. Create JWT assertion To authenticate to the Box API the application needs to create a signed JWT assertion that can be exchanged for an Access Token. A JWT assertion is an encrypted JSON object, consisting of a `header`, `claims`, and `signature`. Let's start by creating the `claims`, sometimes also referred to as the `payload`. ``` using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Collections.Generic; byte[] randomNumber = new byte[64]; RandomNumberGenerator.Create().GetBytes(randomNumber); var jti = Convert.ToBase64String(randomNumber); DateTime expirationTime = DateTime.UtcNow.AddSeconds(45); var claims = new List<Claim>{ new Claim("sub", config.enterpriseID), new Claim("box_sub_type", "enterprise"), new Claim("jti", jti), }; ``` ``` import org.jose4j.jwt.JwtClaims; String authenticationUrl = "https://api.box.com/oauth2/token"; JwtClaims claims = new JwtClaims(); claims.setIssuer(config.boxAppSettings.clientID); claims.setAudience(authenticationUrl); claims.setSubject(config.enterpriseID); claims.setClaim("box_sub_type", "enterprise"); claims.setGeneratedJwtId(64); claims.setExpirationTimeMinutesInTheFuture(0.75f); ``` ``` import time import secrets authentication_url = 'https://api.box.com/oauth2/token' claims = { 'iss': config['boxAppSettings']['clientID'], 'sub': config['enterpriseID'], 'box_sub_type': 'enterprise', 'aud': authentication_url, 'jti': secrets.token_hex(64), 'exp': round(time.time()) + 45 } ``` ``` const crypto = require("crypto"); const authenticationUrl = "https://api.box.com/oauth2/token"; let claims = { iss: config.boxAppSettings.clientID, sub: config.enterpriseID, box_sub_type: "enterprise", aud: authenticationUrl, jti: crypto.randomBytes(64).toString("hex"), exp: Math.floor(Date.now() / 1000) + 45, }; ``` ``` require 'securerandom' authentication_url = 'https://api.box.com/oauth2/token' claims = { iss: config['boxAppSettings']['clientID'], sub: config['enterpriseID'], box_sub_type: 'enterprise', aud: authentication_url, jti: SecureRandom.hex(64), exp: Time.now.to_i + 45 } ``` ``` $authenticationUrl = 'https://api.box.com/oauth2/token'; $claims = [ 'iss' => $config->boxAppSettings->clientID, 'sub' => $config->enterpriseID, 'box_sub_type' => 'enterprise', 'aud' => $authenticationUrl, 'jti' => base64_encode(random_bytes(64)), 'exp' => time() + 45, 'kid' => $config->boxAppSettings->appAuth->publicKeyID ]; ``` | Parameter | Type | Description | | --- | --- | --- | | iss, required | String | The Box Application's OAuth client ID | | sub, required | String | The Box Enterprise ID if this app is to act on behalf of the Service Account of that application, or the User ID if this app wants to act on behalf of another user. | | box_sub_type, required | String | enterprise or user depending on the type of token being requested in the sub claim | | aud, required | String | Always https://api.box.com/oauth2/token | | jti, required | String | A universally unique identifier specified by the application for this JWT. A unique string of at least 16 characters and at most 128 characters. | | exp, required | Integer | The Unix time when this JWT is to expire. Can be set to a maximum value of 60 seconds beyond the issue time. It is recommended to set this to less than the maximum allowed. | | iat, optional | Integer | Issued at time. The token cannot be used before this time. | | nbf, optional | Integer | Not before. Not Specifies when the token will start being valid. | Next, these claims need to be signed using the private key. Depending on the language and library used, the `header` of the JWT is configured by defining the encryption algorithm and the ID of the public key used to sign the claims. ``` using Microsoft.IdentityModel.Tokens; String authenticationUrl = "https://api.box.com/oauth2/token"; var payload = new JwtPayload( config.boxAppSettings.clientID, authenticationUrl, claims, null, expirationTime ); var credentials = new SigningCredentials( new RsaSecurityKey(key), SecurityAlgorithms.RsaSha512 ); var header = new JwtHeader(signingCredentials: credentials); var jst = new JwtSecurityToken(header, payload); var tokenHandler = new JwtSecurityTokenHandler(); string assertion = tokenHandler.WriteToken(jst); ``` ``` import org.jose4j.jws.AlgorithmIdentifiers; import org.jose4j.jws.JsonWebSignature; JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toJson()); jws.setKey(key); jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA512); jws.setHeader("typ", "JWT"); jws.setHeader("kid", config.boxAppSettings.appAuth.publicKeyID); String assertion = jws.getCompactSerialization(); ``` ``` import jwt keyId = config['boxAppSettings']['appAuth']['publicKeyID'] assertion = jwt.encode( claims, key, algorithm='RS512', headers={ 'kid': keyId } ) ``` ``` const jwt = require("jsonwebtoken"); let keyId = config.boxAppSettings.appAuth.publicKeyID; let headers = { algorithm: "RS512", keyid: keyId, }; let assertion = jwt.sign(claims, key, headers); ``` ``` require 'jwt' keyId = appAuth['publicKeyID'] assertion = JWT.encode(claims, key, 'RS512', { kid: keyId }) ``` ``` use \Firebase\JWT\JWT; $assertion = JWT::encode($claims, $key, 'RS512'); ``` For the header the following parameters are supported. | Parameter | Type | Description | | --- | --- | --- | | algorithm, required | String | The encryption algorithm used to sign the JWT claim. This can be one of RS256, RS384, or RS512. | | keyid, required | String | The ID of the public key used to sign the JWT. Not required, though essential when multiple key pairs are defined for an application. | Using JWT libraries Signing your own JWT can be a complicated and painful process. Luckily, the hard work has already been done for you and libraries exist in pretty much every language. Head over to [JWT.io](https://jwt.io/) for an overview. ### 4. Request Access Token The final step is to exchange the short lived JWT assertion for a more long lived Access Token by calling the token endpoint with the assertion as a parameter. ``` using System.Net; using System.Net.Http; var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>( "grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"), new KeyValuePair<string, string>( "assertion", assertion), new KeyValuePair<string, string>( "client_id", config.boxAppSettings.clientID), new KeyValuePair<string, string>( "client_secret", config.boxAppSettings.clientSecret) }); var client = new HttpClient(); var response = client.PostAsync(authenticationUrl, content).Result; class Token { public string access_token { get; set; } } var data = response.Content.ReadAsStringAsync().Result; var token = JsonConvert.DeserializeObject<Token>(data); var accessToken = token.access_token; ``` ``` import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair( "grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")); params.add(new BasicNameValuePair( "assertion", assertion)); params.add(new BasicNameValuePair( "client_id", config.boxAppSettings.clientID)); params.add(new BasicNameValuePair( "client_secret", config.boxAppSettings.clientSecret)); CloseableHttpClient httpClient = HttpClientBuilder.create().disableCookieManagement().build(); HttpPost request = new HttpPost(authenticationUrl); request.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse httpResponse = httpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity); httpClient.close(); class Token { String access_token; } Token token = (Token) gson.fromJson(response, Token.class); String accessToken = token.access_token; ``` ``` import json import requests params = { 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion': assertion, 'client_id': config['boxAppSettings']['clientID'], 'client_secret': config['boxAppSettings']['clientSecret'] } response = requests.post(authentication_url, params) access_token = response.json()['access_token'] ``` ``` const axios = require("axios"); const querystring = require("querystring"); let accessToken = await axios .post( authenticationUrl, querystring.stringify({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: assertion, client_id: config.boxAppSettings.clientID, client_secret: config.boxAppSettings.clientSecret, }) ) .then((response) => response.data.access_token); ``` ``` require 'json' require 'uri' require 'net/https' params = URI.encode_www_form({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: assertion, client_id: config['boxAppSettings']['clientID'], client_secret: config['boxAppSettings']['clientSecret'] }) uri = URI.parse(authentication_url) http = Net::HTTP.start(uri.host, uri.port, use_ssl: true) request = Net::HTTP::Post.new(uri.request_uri) request.body = params response = http.request(request) access_token = JSON.parse(response.body)['access_token'] ``` ``` use GuzzleHttp\Client; $params = [ 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $assertion, 'client_id' => $config->boxAppSettings->clientID, 'client_secret' => $config->boxAppSettings->clientSecret ]; $client = new Client(); $response = $client->request('POST', $authenticationUrl, [ 'form_params' => $params ]); $data = $response->getBody()->getContents(); $access_token = json_decode($data)->access_token; ``` ## Code Samples The code in this guide is available on [GitHub](https://github.com/box-community/samples-docs-authenticate-with-jwt-api). **Reference:** https://developer.box.com/guides/authentication/jwt/without-sdk/ --- ## Untitled *Type: guide | Category: Authentication * Annotator Tokens Annotations is one of the key features supported by new Box View, that allows developers to provide collaboration… # Annotator Tokens Annotations is one of the key features supported by new Box View, that allows developers to provide collaboration capabilities right from within the embedded Box preview in their application. Box View supports three annotation types: highlight only, highlight annotation, and point annotation. Annotations are only supported on document and image previews. ## What is an Annotator Token An Annotator Token is an Access Token that allows an application to create a Preview Embed Link for a file that a user can make annotations on. As an application might not create a new App User for every one of the application's users, the Annotator token allows the application to track which of their own users made the annotations. The Annotator Token is used instead of a regular Access Token, App Token, or File Token to generate a preview session (an expiring embed link) that is linked to a unique user ID and display name. Since a preview session generated using an annotator token is tied to a specific external user, it is strongly recommended that an application generates different preview sessions using different annotator tokens for different end users of an application. ## External user info The external display name associated with an annotation is essentially a stateless "label" appended to the annotation. This means that once an annotation has been added, the display name is permanently associated with the annotation and cannot be updated unless the annotation is deleted and added again with the updated display name. ## Create without SDKs To create an annotator token, follow the instructions for manually authenticating through JWT but replace the JWT claim with the following data. ``` var claims = new List<Claim>{ new Claim("sub", '[EXTERNAL_USER_ID]'), new Claim("name", '[EXTERNAL_USER_DISPLAY_NAME]'), new Claim("box_sub_type", "external"), new Claim("jti", jti), }; ``` ``` JwtClaims claims = new JwtClaims(); claims.setIssuer(config.boxAppSettings.clientID); claims.setAudience(authenticationUrl); claims.setSubject("[EXTERNAL_USER_ID]"); claims.setName("[EXTERNAL_USER_DISPLAY_NAME]"); claims.setClaim("box_sub_type", "external"); claims.setGeneratedJwtId(64); claims.setExpirationTimeMinutesInTheFuture(0.75f); ``` ``` claims = { 'iss': config['boxAppSettings']['clientID'], 'sub': '[EXTERNAL_USER_ID]', 'name': '[EXTERNAL_USER_DISPLAY_NAME]', 'box_sub_type': 'external', 'aud': authentication_url, 'jti': secrets.token_hex(64), 'exp': round(time.time()) + 45 } ``` ``` let claims = { iss: config.boxAppSettings.clientID, sub: "[EXTERNAL_USER_ID]", name: "[EXTERNAL_USER_DISPLAY_NAME]", box_sub_type: "external", aud: authenticationUrl, jti: crypto.randomBytes(64).toString("hex"), exp: Math.floor(Date.now() / 1000) + 45 }; ``` ``` claims = { iss: config['boxAppSettings']['clientID'], sub: "[EXTERNAL_USER_ID]", name: "[EXTERNAL_USER_DISPLAY_NAME]", box_sub_type: 'external', aud: authentication_url, jti: SecureRandom.hex(64), exp: Time.now.to_i + 45 } ``` ``` $claims = [ 'iss' => $config->boxAppSettings->clientID, 'sub' => '[EXTERNAL_USER_ID]', 'name' => '[EXTERNAL_USER_DISPLAY_NAME]', 'box_sub_type' => 'external', 'aud' => $authenticationUrl, 'jti' => base64_encode(random_bytes(64)), 'exp' => time() + 45, 'kid' => $config->boxAppSettings->appAuth->publicKeyID ]; ``` | Parameter | Type | Description | | --- | --- | --- | | sub | String | The external user ID to tie this annotation to. This can be any arbitrary ID tracked by the application | | box_sub_type | String | external to signify an external user ID | | box_sub_type | String | The external user name to tie this annotation to. This will be displayed in the Box UI | Then, convert this claim to an assertion according to the guide and pass this assertion to the [`POST /oauth2/token`](e://post-oauth2-token) endpoint together with an existing valid Access Token, App Token, or File Token, as well as a set of scopes, and the resource for which to create the token. ``` var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>( "grant_type", "urn:ietf:params:oauth:grant-type:token-exchange"), new KeyValuePair<string, string>( "resource", "https://api.box.com/2.0/files/123456"), new KeyValuePair<string, string>( "subject_token", "[ACCESS_TOKEN]"), new KeyValuePair<string, string>( "subject_token_type", "urn:ietf:params:oauth:token-type:access_token"), new KeyValuePair<string, string>( "scope", "item_preview"), new KeyValuePair<string, string>( "actor_token", "[JWT_ASSERTION_FOR_ANNOTATOR_TOKEN]"), new KeyValuePair<string, string>( "actor_token_type", "urn:ietf:params:oauth:token-type:id_token"), }); ``` ``` List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair( "grant_type", "urn:ietf:params:oauth:grant-type:token-exchange")); params.add(new BasicNameValuePair( "resource", "https://api.box.com/2.0/files/123456")); params.add(new BasicNameValuePair( "subject_token", "[ACCESS_TOKEN]")); params.add(new BasicNameValuePair( "subject_token_type", "urn:ietf:params:oauth:token-type:access_token")); params.add(new BasicNameValuePair( "scope", "item_preview")); params.add(new BasicNameValuePair( "actor_token", "[JWT_ASSERTION_FOR_ANNOTATOR_TOKEN]")); params.add(new BasicNameValuePair( "actor_token_type", "urn:ietf:params:oauth:token-type:id_token")); ``` ``` params = urlencode({ 'grant_type': 'urn:ietf:params:oauth:grant-type:token-exchange', 'resource': 'https://api.box.com/2.0/files/123456', 'subject_token': '[ACCESS_TOKEN]', 'subject_token_type': 'urn:ietf:params:oauth:token-type:access_token', 'scope': 'item_preview', 'actor_token': '[JWT_ASSERTION_FOR_ANNOTATOR_TOKEN]', 'actor_token_type': 'urn:ietf:params:oauth:token-type:id_token' }).encode() ``` ``` let accessToken = await axios .post( authenticationUrl, querystring.stringify({ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", resource: "https://api.box.com/2.0/files/123456", subject_token: "[ACCESS_TOKEN]", subject_token_type: "urn:ietf:params:oauth:token-type:access_token", scope: "item_preview", actor_token: "[JWT_ASSERTION_FOR_ANNOTATOR_TOKEN]", actor_token_type: "urn:ietf:params:oauth:token-type:id_token" }) ) .then(response => response.data.access_token); ``` ``` params = URI.encode_www_form({ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', resource: 'https://api.box.com/2.0/files/123456', subject_token: '[ACCESS_TOKEN]', subject_token_type: 'urn:ietf:params:oauth:token-type:access_token', scope: 'item_preview', actor_token: '[JWT_ASSERTION_FOR_ANNOTATOR_TOKEN]', actor_token_type: 'urn:ietf:params:oauth:token-type:id_token' }) ``` ``` $params = [ 'grant_type' => 'urn:ietf:params:oauth:grant-type:token-exchange', 'resource' => 'https://api.box.com/2.0/files/123456', 'subject_token' => '[ACCESS_TOKEN]', 'subject_token_type' => 'urn:ietf:params:oauth:token-type:access_token', 'scope' => 'item_preview', 'actor_token' => '[JWT_ASSERTION_FOR_ANNOTATOR_TOKEN]', 'actor_token_type' => 'urn:ietf:params:oauth:token-type:id_token' ]; ``` | Parameter | Description | | --- | --- | | resource | An optional full URL path to the file the token should be restricted to. | | actor_token | The JWT assertion created earlier | | actor_token_type | Always set to urn:ietf:params:oauth:token-type:id_token | ## Create with SDKs To create a JWT annotator token with an SDK an application can exchange any active token for another token. ``` var options = { actor: { id: "[EXTERNAL_USER_ID]", name: "[EXTERNAL_USER_DISPLAY_NAME" } }; client .exchangeToken( "item_preview", "https://api.box.com/2.0/files/123456", options ) .then(tokenInfo => { //=> tokenInfo.accessToken }); ``` **Reference:** https://developer.box.com/guides/authentication/tokens/annotator-tokens/ --- ## Untitled *Type: guide | Category: Authentication * Access Tokens Instead of a user name and password, Access Tokens are the credentials used to represent the authenticated user to the Box… # Access Tokens Instead of a user name and password, Access Tokens are the credentials used to represent the authenticated user to the Box servers. ## Token Object ### OAuth 2.0 authentication When an Access Token is requested using OAuth 2.0, an Access Token and Refresh Token pair are returned. ``` curl -X POST https://api.box.com/oauth2/token \ -H "content-type: application/x-www-form-urlencoded" \ -d '...' ``` ``` { "access_token": "c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ", "expires_in": 3600, "token_type": "bearer", "refresh_token": "c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ", "issued_token_type": "urn:ietf:params:oauth:token-type:access_token" } ``` Within this object we can see the token string (`access_token`), as well as the Refresh Token (`refresh_token`) that can be used to request a new Access Token when the current one expires (`expires_in`). ### Server authentication When an Access Token is requested using JWT or Client Credentials Grant, only an Access Token is returned: ``` curl --location --request POST 'https://api.box.com/oauth2/token' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode '...' ``` ``` { "access_token": "DkXZmsjUKizvL2z0WiaLvMBeQ756XCGGf", "expires_in": 4123, "restricted_to": [], "issued_token_type": "bearer" } ``` Within this object we can see the token string (`access_token`). Because a Refresh Token is not returned, you must request a new token when the Access Token expires (`expires_in`) using the [token endpoint](e://post-oauth2-token). **Reference:** https://developer.box.com/guides/authentication/tokens/access-tokens/ --- ## Untitled *Type: guide | Category: Authentication * Tokens At the core of every Box API call is an Access Token. Similar to using the Box Web App, you will only be able to successfully… # Tokens At the core of every Box API call is an Access Token. Similar to using the Box Web App, you will only be able to successfully interact with content the user associated with the Access Token either a collaborator on or owns. This can be further restricted by [downscoping](g://authentication/tokens/downscope) a token. Required access scopes, application access, enabled advanced settings, user permissions, and endpoint-specific restrictions all work together to determine which API calls will be successful. For example, even if a user has collaborator access to a folder, a call to get information about the folder will not be successful if the read scope is not granted to the application. ## Types of tokens | Type | Duration | | --- | --- | | Access Token | 60 minutes | | Refresh Token | 60 days or one use | | Developer Token | 60 minutes | ## Application Types & Access Tokens The following shows how each application type is expected to create an Access Token. | Box Application Type | How to get Access Token | | --- | --- | | Platform App + OAuth 2.0 | Explicit user grant | | Platform App + JWT | Exchange a JWT assertion | | Platform App + Client Credentials Grant | Use client ID and client secret | | Limited Access App + App Token | Configure token in Developer Console | | Custom Skill | Access Token in event payload | **Reference:** https://developer.box.com/guides/authentication/tokens/ --- ## Untitled *Type: guide | Category: Authentication * Revoke a Token An Access Token can be revoked at any time by either sending the Access Token or Refresh Token the POST /oauth2/revoke… # Revoke a Token An Access Token can be revoked at any time by either sending the Access Token or Refresh Token the [`POST /oauth2/revoke`](endpoint://post-oauth2-revoke) endpoint. # Usage in SDKs All of the Box SDKs support manually revoking the current Access Token associated with the client. To revoke a specific token, first initialize a new SDK with that token and then call the relevant revoke method. **Reference:** https://developer.box.com/guides/authentication/tokens/revoke/ --- ## Untitled *Type: guide | Category: Authentication * Using in SDKs The SDKs have direct support for JWT and OAuth 2.0 authentication, yet in some cases your application might need to provide an… # Using in SDKs The SDKs have direct support for JWT and OAuth 2.0 authentication, yet in some cases your application might need to provide an Access Token to the SDK directly. ## Developer Token Similarly, developer tokens can be used directly in SDKs without needing any further SDK configuration. ## App Token When using App Token authentication it is possible to directly pass the App Token to the SDKs. **Reference:** https://developer.box.com/guides/authentication/tokens/sdks/ --- ## Untitled *Type: guide | Category: Authentication * Refresh a Token An Access Token can be refreshed by using the Refresh Token that came with the Access Token. This can be done before or… # Refresh a Token An Access Token can be refreshed by using the Refresh Token that came with the Access Token. This can be done before or after the Access Token expires. To do this, the application passes the `refresh_token` to the [`POST /oauth2/token`](endpoint://post-oauth2-token) endpoint as follows. # Usage in SDKs All of the Box SDKs support automatic Access Token renewal for JWT and OAuth 2.0 applications. # Refresh token expiration A Refresh Token is valid for 60 days and can be used to obtain a new Access Token and Refresh Token only once. If the Access Token and Refresh Token are not refreshed within 60 days, the user will need to be re-authorized. Every time an application uses the Refresh Token to get a new Access Token the Refresh Token is invalidated and a new Refresh Token is returned with the new Access Token. This new Refresh Token is then again only valid for 1 use within 60 days. **Reference:** https://developer.box.com/guides/authentication/tokens/refresh/ --- ## Untitled *Type: guide | Category: Authentication * As-User Header It is possible to for an OAuth 2.0 application to act on behalf of another user through the as-user header. In this situation… # As-User Header It is possible to for an OAuth 2.0 application to act on behalf of another user through the `as-user` header. ``` curl https://api.box.com/2.0/folders/0 \ -H "as-user: [USER_ID]" -H "authorization: Bearer [ACCESS_TOKEN]" ``` In this situation the user ID is the Box identifier for a user. User IDs can be found for any user via the `GET /users` endpoint, which is only available to admins, or by calling the `GET /users/me` endpoint with an authenticated user session. ## Preconditions Using the `as-user` header has a few requirements. Firstly, the application needs to be configured to perform actions as users in the Developer Console. Additionally, the authenticated user needs to be a user with admin permissions, meaning either an admin, co-admin, or service account. Co-admin users will also need the 'Manage Users' permission scope. See our guide on User Types for more details. ## as-user using SDKs ``` var user_client = new BoxClient(config, session, asUser: '[USER_ID]'); ``` ``` client.asUser([USER_ID]"); // client.asSelf(); ``` ``` user_to_impersonate = client.user(user_id='[USER_ID]') user_client = client.as_user(user_to_impersonate) ``` ``` client.asUser('[USER_ID]'); // client.asSelf(); ``` Please note that some of our SDKs create new clients for the other user, while others modify the existing client and provide a way to return to a state where the client authenticates for the original user itself. **Reference:** https://developer.box.com/guides/authentication/oauth2/as-user/ --- ## Untitled *Type: guide | Category: Authentication * OAuth 2.0 Auth Client-side OAuth 2.0 is one of the easiest ways to authenticate a user for the Box API. It is an open standard designed to… # OAuth 2.0 Auth Client-side OAuth 2.0 is one of the easiest ways to authenticate a user for the Box API. It is an [open standard](https://oauth.net/2/) designed to allow users to provide applications access to their data in other applications. If you've ever logged in to a website with Twitter, Facebook, or Google you've most likely used OAuth 2.0. Client-side authentication on Box has a similar flow where a user is redirected from an application to the Box web app, required to log in, and grant the application access to the user's data. ## When to use OAuth 2.0 Client-side authentication is the ideal authentication method for apps that: - Work with users that already have existing Box accounts - Want or require users to know that they are using Box - Want to store data within the user's Box account and not within the the application's Box account **Reference:** https://developer.box.com/guides/authentication/oauth2/ --- ## Untitled *Type: guide | Category: Authentication * Setup with OAuth 2.0 A Platform App can be set up to use client-side OAuth 2.0 authentication. Learn how OAuth 2.0 authentication works… # Setup with OAuth 2.0 A Platform App can be set up to use client-side [OAuth 2.0](g://authentication/oauth2) authentication. Learn how OAuth 2.0 authentication works ## Prerequisites To set up a Platform App using OAuth 2.0 authentication, you will need to ensure you have access the [Developer Console](https://app.box.com/developers/console) from your Box enterprise account. Alternatively, you may sign up for a [developer account](https://account.box.com/signup/n/developer). ## App creation steps ### Navigate to the Developer Console Log into Box and go to the [Developer Console](https://app.box.com/developers/console). Select **Create Platform App**. ### Select application type Select **Platform App** from the list of application types. A modal will appear to prompt a selection for the next step. ### Provide basic application information To describe your app, provide an app name and description. Use the drop-down list to select the app's purpose. Depending on the option chosen, you might need to specify further details. | Purpose | Details | | --- | --- | | Automation, Custom Portal | Specify if the app is built by a customer or partner. | | Integration | Specify the integration category, external system name if the app is built by a customer or partner. | | Other | Specify the app purpose and if it is built by a customer or partner. | ### Select application authentication Select **User Authentication (OAuth 2.0)** and confirm with **Create App**. Once you make a selection, you will not be able to change to a different authentication method without creating a new application. ## Basic configuration Before the application can be used, some additional configuration is required. ### Redirect URI During the OAuth 2.0 flow, users are redirected to their browser to authenticate and then authorize the application to take actions on their behalf. Prior to redirecting the user, Box verifies that the `redirect_uri` parameter passed into the [authorization URL](e://get-authorize/#param-redirect_uri) matches one of the redirect URIs configured for the application. This will be an exact match check, meaning the URIs must be exactly the same. Localhost and loopback address redirect URIs will be permitted redirect to any port, but the scheme, domain, path and query parameters must match one of the configured URIs. You can configure these under the OAuth 2.0 Redirect URI section on the Configuration page in the developer console. These must be valid URIs that are HTTPS, or a less secure HTTP for localhost or loopback address. We do not permit duplicate URIs to be saved. Starting November 29, 2021, new applications using OAuth 2.0 will require the URIs set in the configuration tab of the Developer Console to strictly match the one used during redirect. In addition, both new and existing applications, will gain the ability to add multiple redirect URIs. If you configured multiple redirect URIs for the application, the authorization URL must include the `redirect_uri` parameter matching one of the URIs configured in the developer console. If the parameter is not specified, the user will see a `redirect_uri_missing` error and will not be redirected back to the app after granting application access. For existing applications, the deadline to make changes to this URL to avoid service disruption is May 13, 2022. ### Application Scopes Scopes define what permissions your application has in order to access data. See the [scopes guide](g://api-calls/permissions-and-errors/scopes) for detailed information on each option. ### CORS Domains If your application makes API calls from front-end browser code in Javascript, the domain that these calls are made from will need to be added to an allow-list due to [Cross Origin Resource Sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing), also known as CORS. If all requests will be made from server-side code, you may skip this section. To add the full URI(s) to the allow-list, navigate to the **CORS Domain** section at the bottom of the **Configuration** tab in the [Developer Console](https://app.box.com/developers/console). **Reference:** https://developer.box.com/guides/authentication/oauth2/oauth2-setup/ --- ## Untitled *Type: guide | Category: Authentication * OAuth 2.0 with SDKs The Box SDKs have built-in support for client-side OAuth 2.0. In the process a user is redirected to the Box web app in… # OAuth 2.0 with SDKs The Box SDKs have built-in support for client-side OAuth 2.0. In the process a user is redirected to the Box web app in a browser where they log in and authorize the application access to their data before they are redirected back to the applications `redirect_url`. This last step requires the application to be running on a web server somewhere accessible to the user. ## Overview To complete an OAuth 2.0 flow the following steps need to be completed. 1. Configure the Box SDK 2. Redirect the user to the Box website 3. The user grants the application access 4. Exchange the authorization code for an access token At the end of this flow, the application has an Access Token that can be used to make API calls on behalf of this user. The access token acquired through OAuth 2.0 is inherently tied to the user who authorized the application. Any API call made with this token will seem to come from this application, and the user needs to have access to any file or folder the application tries to access with this token. ## Parameters | Parameter | Description | | --- | --- | | CLIENT_ID | The client ID or API key for the application | | CLIENT_SECRET | The client secret or API secret for the application | | REDIRECT_URI | The redirect URL for your application that a user will be sent to after they have authorized the application. This can be configured in the developer console | ## 1. Configure SDK The first step is to make sure your environment has been prepared with the SDK of your choice. ``` var redirectUrl = "[REDIRECT_URI]"; var config = new BoxConfig("[CLIENT_ID]", "[CLIENT_SECRET]", new Uri(redirectUrl)); var sdk = new BoxClient(config); ``` ``` import com.box.sdk.BoxAPIConnection; String authorizationUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code"; ``` ``` from boxsdk import OAuth2, Client auth = OAuth2( client_id='[CLIENT_ID]', client_secret='[CLIENT_SECRET]' ) ``` ``` var BoxSDK = require("box-node-sdk"); var sdk = new BoxSDK({ clientID: "[CLIENT_ID]", clientSecret: "[CLIENT_SECRET]", }); ``` Learn more about installing an SDK for your environment ## 2. Redirect user Next, redirect the user to the authorization URL. Most of the SDKs support a way to get the authorization URL for an SDK client. If you configured multiple redirect URIs for the application, the authorization URL must include the `redirect_uri` parameter matching one of the URIs configured in the developer console. If the parameter is not specified, the user will see a `redirect_uri_missing` error and will not be redirected back to the app after granting application access. ``` var authorizationUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code"; // redirectTo(authorizationUrl); ``` ``` String authorizationUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code"; // response.redirect(authorizationUrl); ``` ``` auth_url, csrf_token = auth.get_authorization_url('[REDIRECT_URL]') // redirect(auth_url, code=302) ``` ``` var authorize_url = sdk.getAuthorizeURL({ response_type: "code", }); // res.redirect(authorize_url) ``` The way in which a user is redirected to a URL depends on the application framework used. Most framework documentation provides extensive guidance on this topic. The [authorization URL](endpoint://get-authorize) can also be created manually as follows. ``` https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code ``` Additional query parameters can be passed along when redirecting the user to limit down the scope, or pass along some extra state. See the reference documentation for more information. If you have [Box Verified Enterprise](https://support.box.com/hc/en-us/articles/360043693554-Box-Verified-Enterprise-Supported-Apps) for your Box instance turned on, you may encounter an issue using the standard `account.box.com` base URL. Instead, use `ent.box.com` in place of `account.box.com`. ## 3. User grants application access Once the user is redirected to the Box web app they will have to log in. After they logged in they are presented with a screen to approve your application. When the user accepts this requests and clicks the button, the browser will redirect to your application's redirect URL as configured in the developer console. ## 4. Exchange code The user is redirected to your application's redirect URL with a query parameter containing a short-lived authorization code. ``` https://your.domain.com/path?code=1234567 ``` This code is not an [Access Token](g://authentication/tokens/access-tokens) and is only valid for a few seconds. The SDKs can be used to exchange the code for an actual Access Token. ``` var session = await sdk.Auth.AuthenticateAsync("[CODE]"); var client = new BoxClient(config, session); ``` ``` BoxAPIConnection client = new BoxAPIConnection( "[CLIENT_ID]", "[CLIENT_SECRET]", "[CODE]" ); ``` ``` auth.authenticate('[CODE]') client = Client(auth) ``` ``` var code = "..."; sdk.getTokensAuthorizationCodeGrant("[CODE]", null, function (err, tokenInfo) { var client = sdk.getPersistentClient(tokenInfo); }); ``` At the end of this flow, the application has an Access Token that can be used to make API calls on behalf of this user. ## Using SDKs and OAuth 2.0 To learn more about OAuth 2.0 authentication for each SDK head over to: [.Net](https://github.com/box/box-windows-sdk-v2/blob/main/docs/authentication.md#traditional-3-legged-oauth2) [Java](https://github.com/box/box-java-sdk/blob/main/doc/authentication.md#standard-3-legged-oauth-20) [Python](https://github.com/box/box-python-sdk/blob/main/docs/usage/authentication.md#traditional-3-legged-oauth2) [Node](https://github.com/box/box-node-sdk/blob/main/docs/authentication.md#traditional-3-legged-oauth2) [IOS](https://github.com/box/box-ios-sdk/blob/main/docs/usage/authentication.md#traditional-3-legged-oauth2) **Reference:** https://developer.box.com/guides/authentication/oauth2/with-sdk/ --- ## Untitled *Type: guide | Category: Authentication * OAuth 2.0 without SDKs Overview While leveraging an official Box SDK removes common hurdles of authentication, it is possible to use the Box… # OAuth 2.0 without SDKs ## Overview While leveraging an official Box SDK removes common hurdles of authentication, it is possible to use the Box APIs without one. This guide reviews the steps to manually complete the OAuth 2.0 flow. 1. Build the authorization URL 2. Redirect the user to the authorization URL 3. The user grants the application access to take actions on their behalf, which, if successful, provides an authorization code 4. Redirect the user back to the application 5. Exchange the authorization code for an Access Token At the end of this flow, the application has an [Access Token](g://authentication/tokens/access-tokens), which can be used to make API calls on behalf of the user. The Access Token acquired through the OAuth 2.0 flow is inherently tied to the user who authorized the application. It is possible to [act as another user](g://authentication/oauth2/as-user) using the `as-user` header. ## Prerequisites Before continuing you will need to complete the following steps: - Create a Platform App within the Box Developer Console, which leverages the OAuth 2.0 authentication method. - Navigate to the configuration tab for the application to copy the `client_id` and `client_secret` values. - Ensure at least one redirect URI is configured in the configuration tab for the application. ## 1. Build authorization URL An [authorization URL](e://get-authorize) is comprised of the following parameters: | Parameter | Status | Description | | --- | --- | --- | | CLIENT_ID | Required | Obtained from the configuration tab of the Developer Console | | REDIRECT_URI | Optional | Configured in the Developer Console and where the user is sent once granting access to the application | | RESPONSE_TYPE | Required | Always set to code | | STATE | Recommended | Protects against cross-site request forgery | If you configured multiple redirect URIs for the application, the authorization URL must include the `redirect_uri` parameter matching one of the URIs configured in the developer console. If the parameter is not specified, the user will see a `redirect_uri_missing` error and will not be redirected back to the app. At the minimum this URL will always use the format: `https://account.box.com/api/oauth2/authorize`?`client_id=CLIENTIDHERE`&`response_type=code` ``` var baseUrl = "https://account.box.com/api/oauth2/authorize"; var clientId = "[CLIENT_ID]"; var authorizationUrl = $"{baseUrl}?client_id={clientId}&response_type=code"; ``` ``` String baseUrl = "https://account.box.com/api/oauth2/authorize"; String clientId = "[CLIENT_ID]"; String authorizationUrl = String.format("%s?client_id=%s&response_type=code", baseUrl, clientId); ``` ``` base_url = 'https://account.box.com/api/oauth2/authorize' client_id = '[CLIENT_ID]' authorizationUrl = f'{base_url}?client_id=${client_id}&response_type=code' ``` ``` var baseUrl = "https://account.box.com/api/oauth2/authorize"; var clientId = "[CLIENT_ID]"; var authorizationUrl = `${baseUrl}?client_id=${clientId}&response_type=code`; ``` Learn more about the authorization URL If you have [Box Verified Enterprise](https://support.box.com/hc/en-us/articles/360043693554-Box-Verified-Enterprise-Supported-Apps) for your Box instance turned on, you may encounter an issue using the standard `account.box.com` base URL. Instead, use `ent.box.com` in place of `account.box.com`. ## 2. Redirect the user Next, redirect the user to the authorization URL. The way this is done depends on the application framework. Most framework documentation provides extensive guidance on this topic. If the authorization URL is not valid for the app specified, the user will see an error page rather than a grant access screen. For example, if the `redirect_uri` parameter in the authorization URL does not match one of the URIs configured for your app, the user will see a `redirect_uri_mismatch` error. ``` var authorizationUrl = $"{baseUrl}?client_id={clientId}&response_type=code"; // redirectTo(authorizationUrl); ``` ``` String authorizationUrl = String.format("%s?client_id=%s&response_type=code", baseUrl, clientId); // response.redirect(authorizationUrl); ``` ``` auth_url = f'{base_url}?client_id=${client_id}&response_type=code' // redirect(auth_url, code=302) ``` ``` var authorizationUrl = `${baseUrl}?client_id=${clientId}&response_type=code`; // res.redirect(authorize_url) ``` Additional query parameters can be passed along when redirecting the user to limit down the scope, or pass along some extra state. See the authorization reference documentation for more information. ## 3. User grants application access The user is redirected to their browser to log in to their account using the Box UI. They are then presented with the list of requested scopes and the option to approve the application to take actions on their behalf. When the user accepts this request by clicking **Grant access to Box**, the browser will redirect to the configured redirect URL with a query parameter containing a short-lived authorization code. If you configured multiple redirect URIs for the application, the authorization URL must include the `redirect_uri` parameter matching one of the URIs configured in the developer console. If the parameter is not specified, the user will see a `redirect_uri_missing` error and will not be redirected back to the app. ``` https://your.domain.com/path?code=1234567 ``` ## 4. Exchange code The provided authorization code is [valid for 30 seconds](g://api-calls/permissions-and-errors/expiration) and must be exchanged for an [Access Token](e://post-oauth2-token) before expiration. ``` using System.Net; using System.Net.Http; using Newtonsoft.Json; String authenticationUrl = "https://api.box.com/oauth2/token"; var client = new HttpClient(); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "authorization_code"), new KeyValuePair<string, string>("code", "[CODE]"), new KeyValuePair<string, string>("client_id", "[CLIENT_ID]"), new KeyValuePair<string, string>("client_secret", "[CLIENT_SECRET]") }); var response = client.PostAsync(authenticationUrl, content).Result; class Token { public string access_token { get; set; } } var data = response.Content.ReadAsStringAsync().Result; var token = JsonConvert.DeserializeObject<Token>(data); var accessToken = token.access_token; ``` ``` String authenticationUrl = "https://api.box.com/oauth2/token"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("grant_type", "authorization_code")); params.add(new BasicNameValuePair("code", "[CODE]")); params.add(new BasicNameValuePair("client_id", "[CLIENT_ID]")); params.add(new BasicNameValuePair("client_secret", "[CLIENT_SECRET]")); CloseableHttpClient httpClient = HttpClientBuilder.create().disableCookieManagement().build(); HttpPost request = new HttpPost(authenticationUrl); request.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse httpResponse = httpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity); httpClient.close(); class Token { String access_token; } Token token = (Token) gson.fromJson(response, Token.class); String accessToken = token.access_token; ``` ``` authentication_url = "https://api.box.com/oauth2/token"; params = urlencode({ 'grant_type': 'authorization_code', 'code': '[CODE]', 'client_id': '[CLIENT_ID]', 'client_secret': '[CLIENT_SECRET]' }).encode() request = Request(authentication_url, params) response = urlopen(request).read() access_token = json.loads(response)['access_token'] ``` ``` const authenticationUrl = "https://api.box.com/oauth2/token"; let accessToken = await axios .post( authenticationUrl, querystring.stringify({ grant_type: "authorization_code", code: "[CODE]", client_id: "[CLIENT_ID]", client_secret: "[CLIENT_SECRET]", }) ) .then((response) => response.data.access_token); ``` To learn how to use an Access Token visit our guide on [Making API calls](g://api-calls). **Reference:** https://developer.box.com/guides/authentication/oauth2/without-sdk/ --- ## Untitled *Type: guide | Category: Authentication * Setup with App Token Auth A Limited Access App can be set up to use server-side App Tokens for authentication. Learn how App Token… # Setup with App Token Auth A Limited Access App can be set up to use server-side [App Tokens](g://authentication/app-token) for authentication. Learn how App Token authentication works ## Prerequisites To set up a Platform App using server-side authentication, you will need to ensure you have access the [Developer Console](https://app.box.com/developers/console) from your Box enterprise account. Alternatively, you may sign up for a [developer account](https://account.box.com/signup/n/developer). ## App creation steps ### 1. Log in to the Developer Console Log into Box and navigate to the [Developer Console](https://app.box.com/developers/console). Select **Create Platform App**. ### 2. Create a Platform App Select **Limited Access App** from the list of application types. A modal will appear to prompt the next step. ### 3. Select an app name Finally, select a unique name for your application and click **Create App**. ## App Authorization Once a keypair is successfully added to your application your Box enterprise Admin needs to authorize the application within the Box Admin Console. Navigate to the **General Settings** tab for your application within the [Developer Console](https://app.box.com/developers/console) and scroll down to the **App Authorization** section. Click **Submit and Review** to send an email to your Box enterprise Admin for approval. More information on this process is available in our [authorization guide](g://authorization). ## Basic configuration Before the application can be used, some basic additional configuration might be required. ### Primary and Secondary App Tokens Authentication with Limited Access Apps is done through preconfigured App Tokens. To configure an app token, navigate to the **Configuration** tab for your application within the [Developer Console](https://app.box.com/developers/console). Scroll down to the **Primary Access Token** section and click the **Generate Key** button. App tokens can be configured to automatically expire or be valid indefinitely. After creation, the key can be used to make [API calls](g://api-calls). # App authorization App Tokens can not be generated until the application is successfully authorized within the Box Admin Console. ### CORS Domains If your application makes API calls from front-end browser code in Javascript, the domain that these calls are made from will need to be added to an allow-list due to [Cross Origin Resource Sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing), also known as CORS. If all requests will be made from server-side code, you may skip this section. To add the full URI(s) to the allow-list, navigate to the **CORS Domain** section at the bottom of the **Configuration** tab in the [Developer Console](https://app.box.com/developers/console). **Reference:** https://developer.box.com/guides/authentication/app-token/app-token-setup/ --- ## Untitled *Type: guide | Category: Authentication * Supported Endpoints App Token authentication currently only supports a handful of the BOX API. Endpoint Path Create a folder POST /folders… # Supported Endpoints App Token authentication currently only supports a handful of the BOX API. | Endpoint | Path | | --- | --- | | Create a folder | POST /folders | | Upload a file | POST /files/content | | Download a file | GET /files/:id/content | | Delete a file | DELETE /files/:id | | Get embed link | GET /files/:id | **Reference:** https://developer.box.com/guides/authentication/app-token/endpoints/ --- ## Untitled *Type: guide | Category: Authentication * App Token Auth Server-side authentication using App Tokens is an alternative way to authenticate to the Box API with fixed, long-lived… # App Token Auth Server-side authentication using App Tokens is an alternative way to authenticate to the Box API with fixed, long-lived Access Tokens that are restricted to the application's [Service Account](page://platform/user-types/#service-account). App Token Auth is intended to be used by applications leveraging [Box View](g://embed/box-view). ## App Token Restrictions A server-side App Token is an authentication method where the application only has access to read and write data to its own account. By using this authentication method there is no need to authorize a user as the application is automatically authenticated as the Service Account that belongs to that application. ## When to use App Tokens Server-side authentication with App Tokens is the ideal authentication method for apps that: - Want to leverage Box's preview services via [Box View](g://embed/box-view) - Work in an environment that either has no user model, or has users that don't have Box accounts - Want to use their own identity system - Don't want users to have to know that they are using Box - Want to store data in the application's Service Account and not a user's account **Reference:** https://developer.box.com/guides/authentication/app-token/ --- ## Untitled *Type: guide | Category: Authentication * App Tokens with SDKs The official Box SDKs have built-in support for App Token authentication. App Token authentication is designed for… # App Tokens with SDKs The official Box SDKs have built-in support for App Token authentication. App Token authentication is designed for working directly with the Box API without requiring a user to redirect through Box to authorize your application, yet is restricted to the application's own data. The method of authentication through JWT is inherently tied to the Service Account for the application. Any API call made with this token will seem to come from this application and will not have access to files and folders from other users without explicitly getting access them. ## Prerequisites Before we can get started, you will need to have completed the following steps. - Create a Box Application within the developer console - Ensure the application is configured to use App Token authentication - Generate a primary and secondary App Token for the application and store the tokens somewhere in your code. ## Initializing an SDK client To initialize an SDK client for app token auth, ensure the SDK is installed and then configure the SDK as follows. ``` var config = new BoxConfig("[CLIENT_ID]", "", new Uri("http://localhost")); var session = new OAuthSession("[APP_TOKEN]", "N/A", 3600, "bearer"); var client = new BoxClient(config, session); ``` ``` BoxTransactionalAPIConnection api = new BoxTransactionalAPIConnection("[APP_TOKEN]"); ``` ``` from boxsdk import Client, OAuth2 auth = OAuth2(access_token='[APP_TOKEN]') client = Client(auth) ``` ``` var BoxSDK = require('box-node-sdk'); var sdk = new BoxSDK({ clientID: '[CLIENT_ID]', clientSecret: '' }); var client = sdk.getBasicClient('[APP_TOKEN]'); ``` With this the application should be able to make API calls to any of the [endpoints](g://authentication/app-token/endpoints) enabled for App Token auth. ## Using SDKs and Application Tokens To learn more about Application Tokens for each SDK head over to: [.Net](https://github.com/box/box-windows-sdk-v2/blob/main/docs/authentication.md#box-view-authentication-with-app-tokens) [Java](https://github.com/box/box-java-sdk/blob/main/doc/authentication.md#box-view-authentication-with-app-token) [Python](https://github.com/box/box-python-sdk/blob/main/docs/usage/authentication.md#box-view-authentication-with-app-tokens) [Node](https://github.com/box/box-node-sdk/blob/main/docs/authentication.md#box-view-authentication-with-app-tokens) **Reference:** https://developer.box.com/guides/authentication/app-token/with-sdk/ --- ## Untitled *Type: guide | Category: Authentication * Rotating App Tokens By updating one of the application's App Tokens at a time the application can rotate the tokens without running into any… # Rotating App Tokens By updating one of the application's App Tokens at a time the application can rotate the tokens without running into any conflicts. ## Why rotate tokens There are a few reasons to rotate App Tokens on a fixed interval. 1. To replace tokens that have been configured to auto-expire 2. To limit the effects of any compromised tokens In either case, Box supports having two active App Tokens at any time, allowing for a seamless rotation from the old to the new tokens. ## Rotation steps These instructions assume that you have already created a primary and secondary App Token before and are ready to replace either of them. By following these steps you can configure your application with two new tokens without any issues. 1. Assuming your application is using the Primary App Token, go to [developer console](https://app.box.com/developers/console) application. Head to the "Configuration" section of your application "Generate Key" button for the Secondary App Token. 2. Update your application with the Secondary Token. Ensure your application is configured with this new token completely before moving on to the next step. 3. Once you are confident that the Primary App token is no longer in use, head over to the [developer console](https://app.box.com/developers/console) and click the "Revoke" button for the Primary App Token. Repeat the same process with the tokens switched to roll back from the Secondary App Token to the Primary App Token. **Reference:** https://developer.box.com/guides/authentication/app-token/rollover/ --- ## Untitled *Type: guide | Category: Authentication * App Tokens without SDKs If you are not ready to use any of the official Box SDKs, or an SDK is not available in your language of choice, it… # App Tokens without SDKs If you are not ready to use any of the official Box SDKs, or an SDK is not available in your language of choice, it is totally possible to use the Box APIs without them. App Token authentication is designed for working directly with the Box API without requiring a user to redirect through Box to authorize your application, yet is restricted to the application's own data. The method of authentication through JWT is inherently tied to the Service Account for the application. Any API call made with this token will seem to come from this application and will not have access to files and folders from other users without explicitly getting access them. ## Prerequisites Before we can get started, you will need to have completed the following steps. - Create a Box Application within the developer console - Ensure the application is configured to use App Token authentication - Generate a primary and secondary App Token for the application and store the tokens somewhere in your code. ## Making API calls To use an App Token directly the application can use the App Token the same way it would use any Access Token. ``` curl https://api.box.com/2.0/users/me \ -H "authorization: Bearer EGmDmRVfhfHsqesn5yVYHAqUkD0dyDfk" ``` **Reference:** https://developer.box.com/guides/authentication/app-token/without-sdk/ --- ## Untitled *Type: guide | Category: Applications * Create Web App Integration This guide explains how to set up a Web App Integration with a Platform App. Server-side integration is no longer… # Create Web App Integration This guide explains how to set up a Web App Integration with a Platform App. Server-side integration is no longer supported. This means the applications using server-side actions will still be working, but you won't be able to modify the server-side configuration options such as Preliminary Callback URL or Basic Authentication. You will be able to deactivate them and change the implementation to a new one. ## Create an OAuth 2.0 Application Navigate to the [Developer Console](https://app.box.com/developers/console) and create a [Platform App](g://applications/app-types/platform-apps) that leverages [OAuth 2.0 authentication](g://authentication/oauth2/oauth2-setup). ## Create a New Integration Then, navigate to the **Integrations** tab and click **Create a Web App Integration**. ## Configure Integration To configure the integration, follow the guidance below for each value. ### App Info | Field | Description | | --- | --- | | Integration name | The name of your integration, which users see in the Box Web App when they select the More Options > Integrations menu on a file or folder. | | Description | The description of the integration displayed in the Box Integrations. | | Supported file extensions | The integration will only appear as an option in the More Options > Integrations menu for the selected file extensions. | | Permissions requirement | Determines what permissions level users need to see the integration. Download permissions are required allows users to download the file - they will not be able to update it. Full permissions are required allows users to download and update the file. | | Integration scopes | Specifies the scope of your integration - either the file/folder from which integration is invoked, or its parent folder. | | Display on shared pages toggle | Determines if an integration can be shown to external users on a shared page. If enabled, users who are not collaborating on the content will see the integration in the context-menu when accessing the items through a shared link. | | Lock to only allow the current user to overwrite the file using your integration toggle | Determines if different web app integrations can edit the file at the same time. | | Integration type | Select desired integration type. Available options are: Files, Folders, Both. | ### Callback Configuration | Field | Description | | --- | --- | | Client Callback URL | Handles additional callback requests from Box after the primary request with Popup Integrations. If the application specifies a file parameter in the REST method, the preliminary callback URL cannot originate from the client. As a result, a second request must be made from the client to your server so the server can send the necessary interface to the user. | | Prompt Message | Specifies the message that users see when they initiate the integration. Use this field to provide context about what happens next. The message is limited to 500 characters. | | User Experience | Informs that the integration will open in a new window. | | New Window Settings | Determines if the application opens in a new tab. | ### Callback Parameters The **Callback Parameters** section configures the parameters that Box sends to the callback URL when a user accepts a confirmation prompt. If this setting is not configured, Box does not send any parameters to the callback URL. To add a parameter, select the **Method** (GET or POST), specify the **Parameter name** and add a **Parameter value**. The **File** method is no longer supported. If you already used this method, you cannot edit its values. You can change the **File** method to **GET** or **POST**, but you can't undo this action. For example: **GET - `userid` - `#user_id#`**. The following parameter values are available. | Parameter | Method | Description | | --- | --- | --- | | user_id | GET, POST | The Box user ID. This information is used in Popup Integrations in which user authentication is required to complete an action. You can store the Box ID in your application to enable subsequent authentication requests from the integration. | | user_name | POST | The full name or email address of the Box user. Not all Box users specify their names at all times. | | file_id | GET, POST | The Box file ID. You can use this ID to make Box API calls that affect the file. | | file_name | POST | The name of the file. | | file_extension | GET, POST | The extension of the file. | | auth_code | GET, POST | The OAuth 2.0 authorization code, which is generated by Box upon successful authentication. Your application must then supply this authorization code to Box in exchange for an OAuth 2.0 Access Token. An authorization header containing a valid Access Token must be included in every Box API request. | | redirect_to_box_url | GET, POST | In Popup Integrations, the URL to which requests are sent by the confirmation prompt. Use this URL to redirect users to the All Files page. This parameter closes the popup panel and refreshes the All Files page to reflect any changes performed by the integration. If you do not want to add this parameter to your application, you can specify the entire URL. Success: #redirect_to_box_url#&status=success&message=Your%20action%20was%20successful%2E. Failure: #redirect_to_box_url#&status=failure&message=Your%20action%20was%20unsuccessful%2E | ### Integration Status - **Development**: The integration is visible and available only to application collaborators listed under the **General Settings** tab. This option is best used when the application is still in development and undergoing testing. - **Online**: The integration is visible and available to all Box users. This option is best used when development is complete and the application is ready to publish in the Integrations. - **Maintenance**: The integration is visible and available only to application collaborators listed under the **General Settings** tab. This option is best used after the integration is published in the Integrations, but needs to perform maintenance updates or troubleshoot issues. Use this option to temporarily take the integration offline for everyone except the application's collaborators. ## Example Use Cases of Box Integrations When a user chooses a Popup Integration, Box sends a callback request to the primary callback URL. It sends the callback parameters have been configured to the server. In some cases, Box may make a second request if the client cannot get all the data it needs from the first request. The following example does not require a client callback URL: - The Popup Integration performs a REST call using a `download_file_url` callback parameter. - The user clicks **OK** in the confirmation prompt to accept the popup. - Box sends a request to the following URL (the primary callback URL plus the callback parameter): `http://www.doceditor.com/service?apikey=abc&file=&redirect=`. - The response from the callback URL displays a user interface to the user who made the request. The popup has all the information needed to continue the action and an additional client callback is not needed. The following example requires a client callback URL: - The Popup Integration performs a REST call using a file-callback parameter. - The user clicks **OK** in the confirmation prompt to accept the popup. - The popup displays a page where Box sends a POST request with the contents of a file, along with the callback parameters to the remote server. - Box receives the response from the remote server and directs the client to POST the response to the client callback URL. The server identified by the URL interprets the response and redirects the user with the correct session ID. ## Client-callback URL Request Format The POST request that Box sends to the client callback URL takes the response from the primary callback URL and forwards it to the same URL along with the same data as the original callback. | Client Callback URL | Example | | --- | --- | | Two GET parameters and one POST parameter: http://your-client-callback-url.com/?get_param1=value1&get_param2=value2 | POST data: post_param1=value1initial_callback_response | The response to the client-callback request is an HTTP status 302, redirecting the user to the correct URL or to the HTML for a UI. Most often the URL points to a separate API or custom script developed for Web App Integrations, which parses the result of the primary callback URL. Also, note that the URL must be publicly accessible on the internet. ## Making Integration Publicly Available To make a Box integration publicly available it needs to be listed in the App Center. Follow the [Integrations](g://applications/integrations) guide for more details. **Reference:** https://developer.box.com/guides/applications/web-app-integrations/configure/ --- ## Untitled *Type: guide | Category: Applications * Web App Integration Web App Integrations allow third-party applications to become part of the Box user experience by allowing users to use… # Web App Integration Web App Integrations allow third-party applications to become part of the Box user experience by allowing users to use such third-party applications when editing or sharing files. ## Features - **File interaction**. Users can modify, share, or edit content stored in Box using a third-party application. - **Recommended Apps support**. Integrations can appear in the Box Preview interface under **Recommended Apps**. For details, see [Recommended Web Integrations](https://support.box.com/hc/en-us/articles/360044195533-Installing-Recommended-Apps-in-your-Enterprise). - **Scoped availability**. Integrations can be restricted to certain content types and file extensions. ## Visibility in Recommended Apps Your web application integration appears in **Recommended Apps** only if it is published in Integrations. Learn how to create a Web App Integration **Reference:** https://developer.box.com/guides/applications/web-app-integrations/ --- ## Untitled *Type: guide | Category: Applications * Integrations Types Currently, Box provides the Popup integration type. Popup Integrations In a popup integration, Box opens a panel and… # Integrations Types Currently, Box provides the Popup integration type. ## Popup Integrations In a popup integration, Box opens a panel and loads the application's callback URL configured for the integration. The application can display its own user interface for the integration in the popup. The integration receives a short-lived authorization code with this request, which can be used to connect to the Box APIs, exchange the code for an Access Token, and then use that to make API calls to Box. Popup panels use HTML `<iframe>` tags to display the embedded content. To protect the security of Box's content, callback URLs should use SSL, and the response from the callback URL should include an `X-Frame-Options` header set to a random string value. **Reference:** https://developer.box.com/guides/applications/web-app-integrations/types/ --- ## Untitled *Type: guide | Category: Applications * User Experience The following explains what a Web App Integration looks like from a user's point of view. Box users can discover… # User Experience The following explains what a Web App Integration looks like from a user's point of view. 1. Box users can discover applications in the Box Integrations. They can visit the Integrations directly, or select the **Integrations** menu from the Box Web App UI. 2. In the Integrations they select the application they would like to add. Every published Box application has a public profile page, which provides details including the integrations it provides. 3. They user adds the application to their account by clicking the **Add** button in the Integrations listing. Once an application is added to an account, all its integrations become available to the user. 4. Select an integration from the **More Actions** menu on a file or folder. 5. Box will ask the user for permission to share the file or folder with the application. The confirmation prompt must accepted before the integration can be successfully used. 6. Upon granting access, Box passes the data to the application. Depending on the type of integration, the application will then display a popup panel or run a server-based process. **Reference:** https://developer.box.com/guides/applications/web-app-integrations/user-experience/ --- ## Untitled *Type: guide | Category: Box AI * Override AI model configuration The ai_agent configuration allows you to override the default AI model configuration. It is available for… # Override AI model configuration The `ai_agent` configuration allows you to override the default AI model configuration. It is available for the following endpoints: - [`POST ai/ask`](e://post_ai_ask#param_ai_agent) - [`POST ai/text_gen`](e://post_ai_text_gen#param_ai_agent) - [`POST ai/extract`](e://post_ai_extract#param_ai_agent) - [`POST ai/extract_structured`](e://post_ai_extract_structured#param_ai_agent) Use the [`GET ai_agent_default`](e://get_ai_agent_default) endpoint to fetch the default configuration. The override examples include: - Replacing the default AI model with a custom one based on your organization's needs. - Tweaking the base `prompt` to allow a more customized user experience. - Changing a parameter, such as `temperature`, to make the results more or less creative. ## Sample configuration A complete configuration for `ai/ask` is as follows: ``` { "type": "ai_agent_ask", "basic_text": { "llm_endpoint_params": { "type": "openai_params", "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>", "temperature": 0, "top_p": 1 }, "model": "azure__openai__gpt_4o_mini", "num_tokens_for_completion": 8400, "prompt_template": "It is `{current_date}`, consider these travel options `{content}` and answer the `{user_question}`.", "system_message": "You are a helpful travel assistant specialized in budget travel" }, "basic_text_multi": { "llm_endpoint_params": { "type": "openai_params", "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>", "temperature": 0, "top_p": 1 }, "model": "azure__openai__gpt_4o_mini", "num_tokens_for_completion": 8400, "prompt_template": "It is `{current_date}`, consider these travel options `{content}` and answer the `{user_question}`.", "system_message": "You are a helpful travel assistant specialized in budget travel" }, "long_text": { "embeddings": { "model": "openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } }, "llm_endpoint_params": { "type": "openai_params", "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>", "temperature": 0, "top_p": 1 }, "model": "azure__openai__gpt_4o_mini", "num_tokens_for_completion": 8400, "prompt_template": "It is `{current_date}`, consider these travel options `{content}` and answer the `{user_question}`.", "system_message": "You are a helpful travel assistant specialized in budget travel" }, "long_text_multi": { "embeddings": { "model": "openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } }, "llm_endpoint_params": { "type": "openai_params", "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>", "temperature": 0, "top_p": 1 }, "model": "azure__openai__gpt_4o_mini", "num_tokens_for_completion": 8400, "prompt_template": "It is `{current_date}`, consider these travel options `{content}` and answer the `{user_question}`.", "system_message": "You are a helpful travel assistant specialized in budget travel" } } ``` ### Differences in parameter sets The set of parameters available for `ask`, `text_gen`, `extract`, `extract_structured` differs slightly, depending on the API call. The agent configuration for the `ask` endpoint includes `basic_text`, `basic_text_multi`, `long_text` and `long_text_multi` parameters. This is because of the `mode` parameter you use to specify if the request is for a single item or multiple items. If you selected `multiple_item_qa` as the `mode`, you can also use `multi` parameters for overrides. The agent configuration for `text_gen` includes the `basic_gen` parameter that is used to generate text. ### LLM endpoint params The `llm_endpoint_params` configuration options differ depending on the overall AI model being [Google](r://ai-llm-endpoint-params-google), [OpenAI](r://ai-llm-endpoint-params-openai) or [AWS](r://ai-llm-endpoint-params-aws) based. For example, both `llm_endpoint_params` objects accept a `temperature` parameter, but the outcome differs depending on the model. For Google and AWS models, the [`temperature`](https://ai.google.dev/gemini-api/docs/models/generative-models#model-parameters) is used for sampling during response generation, which occurs when `top-P` and `top-K` are applied. Temperature controls the degree of randomness in the token selection. For OpenAI models, [`temperature`](https://community.openai.com/t/temperature-top-p-and-top-k-for-chatbot-responses/295542) is the sampling temperature with values between 0 and 2. Higher values like 0.8 make the output more random, while lower values like 0.2 make it more focused and deterministic. When introducing your own configuration, use `temperature` or or `top_p` but not both. ### System message The `system_message` parameter's aim is to help the LLM understand its role and what it’s supposed to do. For example, if your solution is processing travel itineraries, you can add a system message saying: ``` You are a travel agent aid. You are going to help support staff process large amounts of schedules, tickets, etc. ``` This message is separate from the content you send in, but it can improve the results. ### Number of tokens for completion The `num_tokens_for_completion` parameter represents the number of [tokens](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them) Box AI can return. This number can vary based on the model used. **Reference:** https://developer.box.com/guides/box-ai/ai-agents/ai-agent-overrides/ --- ## Untitled *Type: guide | Category: Box AI * AI agent configuration versioning Box updates the default models across the endpoints on a regular basis in order to stay up to date with… # AI agent configuration versioning Box updates the default models across the endpoints on a regular basis in order to stay up to date with the most advanced options. If a default model is updated, it will be posted in the developer changelog. AI agent configuration versioning gives the developers more control over AI agent versioning and ensures consistent responses. AI agent configuration versioning adopts the following principles: - Each AI agent snapshot is supported for at least 12 months, unless there are factors outside of Box's control. For example, a Large Language Model (LLM) may get deprecated. - An AI agent snapshot is available unless a new, stable agent version is released - A 6-month window is provided to test and transition to the new snapshot. ## Historical AI agent configuration The values in the [default agent configuration](g://box-ai/ai-agents/get-agent-default-config) used by the LLM gateway often change to achieve the best possible answer quality. To make sure your configurations are not affected in a negative way, you can use the historical AI agent configuration provided below to [override the default one](g://box-ai/ai-agents/ai-agent-overrides). ``` { "ask": { "type": "ai_agent_ask", "longText": { "model": "azure__openai__gpt_4o_mini", "systemMessage": "", "promptTemplate": "Reply as if it's {current_date}.\nI will ask you for help and provide subsections of one document delimited by five backticks (`````) at the beginning and at the end.\nIf I make a reference to \"this\", I am referring to the document I provided between the five backticks. I may ask you a question where the answer is contained within the document. In that case, do your best to answer using only the document, but if you cannot, feel free to mention that you couldn't find an answer in the document, but you have some answer from your general knowledge.\nI may ask you to perform some kind of computation or symbol manipulation such as filtering a list, counting something, summing, averaging, and other aggregation/grouping functions or some combination of them. In these cases, first list the plan of how you plan to perform such a computation, then follow that plan step by step, keeping track of intermediate results, and at the end tell me the final answer.\nI may ask you to enumerate or somehow list people, places, characters, or other important things from the document, if I do so, please only use the document provided to list them.\nTEXT FROM DOCUMENT STARTS\n`````\n{content}\n `````\nTEXT FROM DOCUMENT ENDS\nNever mention five backticks in your response. Unless you are told otherwise, a one paragraph response is sufficient for any requested summarization tasks.\nHere is how I need help from you: {user_question}", "numTokensForCompletion": 6000, "llmEndpointParams": { "type": "openai_params", "temperature": 0.0, "topP": 1.0, "frequencyPenalty": 0.0, "presencePenalty": 1.5, "stop": "<|im_end|> " }, "embeddings": { "model": "azure__openai__text_embedding_ada_002", "strategy": { "id": "basic", "numTokensPerChunk": 64 } } }, "basicText": { "model": "azure__openai__gpt_4o_mini", "systemMessage": "", "promptTemplate": "Reply as if it's {current_date}.\nI will ask you for help and provide the entire text of one document delimited by five backticks (`````) at the beginning and at the end.\nIf I make a reference to \"this\", I am referring to the document I provided between the five backticks. I may ask you a question where the answer is contained within the document. In that case, do your best to answer using only the document, but if you cannot, feel free to mention that you couldn't find an answer in the document, but you have some answer from your general knowledge.\nI may ask you to perform some kind of computation or symbol manipulation such as filtering a list, counting something, summing, averaging, and other aggregation/grouping functions or some combination of them. In these cases, first list the plan of how you plan to perform such a computation, then follow that plan step by step, keeping track of intermediate results, and at the end tell me the final answer.\nI may ask you to enumerate or somehow list people, places, characters, or other important things from the document, if I do so, please only use the document provided to list them.\nTEXT FROM DOCUMENT STARTS\n `````\n{content}\n`````\nTEXT FROM DOCUMENT ENDS\nNever mention five backticks in your response. Unless you are told otherwise, a one paragraph response is sufficient for any requested summarization tasks.\nHere is how I need help from you: {user_question}", "numTokensForCompletion": 6000, "llmEndpointParams": { "type": "openai_params", "temperature": 0.0, "topP": 1.0, "frequencyPenalty": 0.0, "presencePenalty": 1.5, "stop": "<|im_end|>" } }, "longTextMulti": { "model": "azure__openai__gpt_4o_mini", "systemMessage": "Role and Goal: You are an assistant designed to analyze and answer a question based on provided snippets from multiple documents, which can include business-oriented documents like docs, presentations, PDFs, etc. The assistant will respond concisely, using only the information from the provided documents.\n\nConstraints: The assistant should avoid engaging in chatty or extensive conversational interactions and focus on providing direct answers. It should also avoid making assumptions or inferences not supported by the provided document snippets.\n\nGuidelines: When answering, the assistant should consider the file's name and path to assess relevance to the question. In cases of conflicting information from multiple documents, it should list the different answers with citations. For summarization or comparison tasks, it should concisely answer with the key points. It should also consider the current date to be the date given.\n\nPersonalization: The assistant's tone should be formal and to-the-point, suitable for handling business-related documents and queries.\n", "promptTemplate": "Current date: {current_date}\n\nTEXT FROM DOCUMENTS STARTS\n{content}\nTEXT FROM DOCUMENTS ENDS\n\nHere is how I need help from you: {user_question}\n.", "numTokensForCompletion": 6000, "llmEndpointParams": { "type": "openai_params", "temperature": 0.0, "topP": 1.0, "frequencyPenalty": 0.0, "presencePenalty": 1.5, "stop": "<|im_end|>" }, "embeddings": { "model": "azure__openai__text_embedding_ada_002", "strategy": { "id": "basic", "numTokensPerChunk": 64 } } }, "basicTextMulti": { "model": "azure__openai__gpt_4o_mini", "systemMessage": "", "promptTemplate": "Current date: {current_date}\n\nTEXT FROM DOCUMENTS STARTS\n{content}\nTEXT FROM DOCUMENTS ENDS\n\nHere is how I need help from you: {user_question}\n.", "numTokensForCompletion": 6000, "llmEndpointParams": { "type": "openai_params", "temperature": 0.0, "topP": 1.0, "frequencyPenalty": 0.0, "presencePenalty": 1.5, "stop": "<|im_end|>" } }, }, "extract": { "type": "ai_agent_extract", "longText": { "model": "google__gemini_1_5_flash_001", "systemMessage": "Respond only in valid json. You are extracting metadata that is name, value pairs from a document. Only output the metadata in valid json form, as {\"name1\":\"value1\",\"name2\":\"value2\"} and nothing else. You will be given the document data and the schema for the metadata, that defines the name, description and type of each of the fields you will be extracting. Schema is of the form {\"fields\": [{\"key\": \"key_name\", \"displayName\": \"key display name\", \"type\": \"string\", \"description\": \"key description\"}]}. Leverage key description and key display name to identify where the key and value pairs are in the document. In certain cases, key description can also indicate the instructions to perform on the document to obtain the value. Prompt will be in the form of Schema is ``schema`` \n document is````document````", "promptTemplate": "If you need to know today's date to respond, it is {current_date}. Schema is ``{user_question}`` \n document is````{content}````", "numTokensForCompletion": 4096, "llmEndpointParams": { "type": "google_params", "temperature": 0.0, "topP": 1.0, "frequencyPenalty": 0.0, "presencePenalty": 0.0 }, "embeddings": { "model": "azure__openai__text_embedding_ada_002", "strategy": { "id": "basic", "numTokensPerChunk": 64 } } }, "basicText": { "model": "google__gemini_1_5_flash_001", "systemMessage": "Respond only in valid json. You are extracting metadata that is name, value pairs from a document. Only output the metadata in valid json form, as {\"name1\":\"value1\",\"name2\":\"value2\"} and nothing else. You will be given the document data and the schema for the metadata, that defines the name, description and type of each of the fields you will be extracting. Schema is of the form {\"fields\": [{\"key\": \"key_name\", \"displayName\": \"key display name\", \"type\": \"string\", \"description\": \"key description\"}]}. Leverage key description and key display name to identify where the key and value pairs are in the document. In certain cases, key description can also indicate the instructions to perform on the document to obtain the value. Prompt will be in the form of Schema is ``schema`` \n document is````document````", "promptTemplate": "If you need to know today's date to respond, it is {current_date}. Schema is ``{user_question}`` \n document is````{content}````", "numTokensForCompletion": 4096, "llmEndpointParams": { "type": "google_params", "temperature": 0.0, "topP": 1.0, "frequencyPenalty": 0.0, "presencePenalty": 0.0 } } }, "textGen": { "type": "ai_agent_text_gen", "basicGen": { "model": "azure__openai__gpt_4o_mini", "systemMessage": "\nIf you need to know today's date to respond, it is {current_date}.\nThe user is working in a collaborative document creation editor called Box Notes.\nAssume that you are helping a business user create documents or to help the user revise existing text.\nYou can help the user in creating templates to be reused or update existing documents, you can respond with text that the user can use to place in the document that the user is editing.\nIf the user simply asks to \"improve\" the text, then simplify the language and remove jargon, unless the user specifies otherwise.\nDo not open with a preamble to the response, just respond.\n", "promptTemplate": "{user_question}", "numTokensForCompletion": 12000, "llmEndpointParams": { "type": "openai_params", "temperature": 0.1, "topP": 1.0, "frequencyPenalty": 0.75, "presencePenalty": 0.75, "stop": "<|im_end|>" }, "embeddings": { "model": "azure__openai__text_embedding_ada_002", "strategy": { "id": "basic", "numTokensPerChunk": 64 } }, "contentTemplate": "`````{content}`````" } }, "extractStructured": { "type": "ai_agent_extract_structured", "longText": { "model": "google__gemini_1_5_flash_001", "systemMessage": "Respond only in valid json. You are extracting metadata that is name, value pairs from a document. Only output the metadata in valid json form, as {\"name1\":\"value1\",\"name2\":\"value2\"} and nothing else. You will be given the document data and the schema for the metadata, that defines the name, description and type of each of the fields you will be extracting. Schema is of the form {\"fields\": [{\"key\": \"key_name\", \"prompt\": \"prompt to extract the value\", \"type\": \"date\"}]}. Leverage prompt for each key to identify where the key and value pairs are in the document. In certain cases, prompt can also indicate the instructions to perform on the document to obtain the value. Prompt will be in the form of Schema is ``schema`` \n document is````document````", "promptTemplate": "If you need to know today's date to respond, it is {current_date}. Schema is ``{user_question}`` \n document is````{content}````", "numTokensForCompletion": 4096, "llmEndpointParams": { "type": "google_params", "temperature": 0.0, "topP": 1.0, "frequencyPenalty": 0.0, "presencePenalty": 0.0 }, "embeddings": { "model": "google__textembedding_gecko_003", "strategy": { "id": "basic", "numTokensPerChunk": 64 } } }, "basicText": { "model": "google__gemini_1_5_flash_001", "systemMessage": "Respond only in valid json. You are extracting metadata that is name, value pairs from a document. Only output the metadata in valid json form, as {\"name1\":\"value1\",\"name2\":\"value2\"} and nothing else. You will be given the document data and the schema for the metadata, that defines the name, description and type of each of the fields you will be extracting. Schema is of the form {\"fields\": [{\"key\": \"key_name\", \"prompt\": \"prompt to extract the value\", \"type\": \"date\"}]}. Leverage prompt for each key to identify where the key and value pairs are in the document. In certain cases, prompt can also indicate the instructions to perform on the document to obtain the value. Prompt will be in the form of Schema is ``schema`` \n document is````document````", "promptTemplate": "If you need to know today's date to respond, it is {current_date}. Schema is ``{user_question}`` \n document is````{content}````", "numTokensForCompletion": 4096, "llmEndpointParams": { "type": "google_params", "temperature": 0.0, "topP": 1.0, "frequencyPenalty": 0.0, "presencePenalty": 0.0 } } } } ``` **Reference:** https://developer.box.com/guides/box-ai/ai-agents/ai-agent-versioning/ --- ## Untitled *Type: guide | Category: Box AI * AI model overrides Box updates the default models across the endpoints on a regular basis to stay up to date with the most advanced options… # AI model overrides Box updates the default models across the endpoints on a regular basis to stay up to date with the most advanced options. If your implementation is based on Box AI, a new default model might alter the results in a way that could break or change a downstream process. Switching to a specific version may prevent encountering any issues. Selecting a specific model may also bring better results to your use case. This is why, you can switch to any model included in the [supported models](g://box-ai/ai-models) list. Apart from switching models, you can pass options to further customize the agents used in Box AI implementation and get the responses that suit your use case. To see specific use cases, check the [overrides tutorial](g://box-ai/ai-agents/ai-agent-overrides). **Reference:** https://developer.box.com/guides/box-ai/ai-agents/ --- ## Untitled *Type: guide | Category: Box AI * Get default AI agent configuration The GET /2.0/ai_agent_default endpoint allows you to fetch the default configuration for AI services… # Get default AI agent configuration The `GET /2.0/ai_agent_default` endpoint allows you to fetch the default configuration for AI services. Once you get the configuration details you can override them using the [`ai_agent`](g://box-ai/ai-agents/ai-agent-overrides) parameter. ## Send a request To send a request, use the `GET /2.0/ai_agent_default` endpoint. Make sure you have generated the developer token to authorize your app. See [getting started with Box AI](g://box-ai/ai-tutorials/prerequisites) for details. ### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Example | | --- | --- | --- | | language | The language code the agent configuration is returned for. If the language is not supported, the default configuration is returned. | ja-JP | | mode | The mode used to filter the agent configuration. The value can be ask, text_gen, extract, or extract_structured depending on the result you want to achieve. | ask | | model | The model you want to get the configuration for. To make sure your chosen model is supported, see the list of models. | azure__openai__gpt_4o_mini | ## Responses The responses to the call may vary depending on the `mode` parameter value you choose. When you set the `mode` parameter to `ask` the response will be as follows: ``` { "type": "ai_agent_ask", "basic_text": { "model": "azure__openai__gpt_4o_mini", "system_message": "", "prompt_template": "prompt_template": "{user_question}Write it in an informal way.{content}" }, "num_tokens_for_completion": 6000, "llm_endpoint_params": { "temperature": 0, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 1.5, "stop": "<|im_end|>", "type": "openai_params" } }, "long_text": { "model": "azure__openai__gpt_4o_mini", "system_message": "", "prompt_template": "prompt_template": "{user_question}Write it in an informal way.{content}" }, "num_tokens_for_completion": 6000, "llm_endpoint_params": { "temperature": 0, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 1.5, "stop": "<|im_end|>", "type": "openai_params" }, "embeddings": { "model": "azure__openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } } }, "basic_text_multi": { "model": "azure__openai__gpt_4o_mini", "system_message": "", "prompt_template": "Current date: {current_date}\n\nTEXT FROM DOCUMENTS STARTS\n{content}\nTEXT FROM DOCUMENTS ENDS\n\nHere is how I need help from you: {user_question}\n.", "num_tokens_for_completion": 6000, "llm_endpoint_params": { "temperature": 0, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 1.5, "stop": "<|im_end|>", "type": "openai_params" } }, "long_text_multi": { "model": "azure__openai__gpt_4o_mini", "system_message": "Role and Goal: You are an assistant designed to analyze and answer a question based on provided snippets from multiple documents, which can include business-oriented documents like docs, presentations, PDFs, etc. The assistant will respond concisely, using only the information from the provided documents.\n\nConstraints: The assistant should avoid engaging in chatty or extensive conversational interactions and focus on providing direct answers. It should also avoid making assumptions or inferences not supported by the provided document snippets.\n\nGuidelines: When answering, the assistant should consider the file's name and path to assess relevance to the question. In cases of conflicting information from multiple documents, it should list the different answers with citations. For summarization or comparison tasks, it should concisely answer with the key points. It should also consider the current date to be the date given.\n\nPersonalization: The assistant's tone should be formal and to-the-point, suitable for handling business-related documents and queries.\n", "prompt_template": "Current date: {current_date}\n\nTEXT FROM DOCUMENTS STARTS\n{content}\nTEXT FROM DOCUMENTS ENDS\n\nHere is how I need help from you: {user_question}\n.", "num_tokens_for_completion": 6000, "llm_endpoint_params": { "temperature": 0, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 1.5, "stop": "<|im_end|>", "type": "openai_params" }, "embeddings": { "model": "azure__openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } } } } ``` When you set the `mode` parameter to `text_gen` the response will be as follows: ``` { "type": "ai_agent_text_gen", "basic_gen": { "model": "azure__openai__gpt_4o_mini", "system_message": "\nIf you need to know today's date to respond, it is {current_date}.\nThe user is working in a collaborative document creation editor called Box Notes.\nAssume that you are helping a business user create documents or to help the user revise existing text.\nYou can help the user in creating templates to be reused or update existing documents, you can respond with text that the user can use to place in the document that the user is editing.\nIf the user simply asks to \"improve\" the text, then simplify the language and remove jargon, unless the user specifies otherwise.\nDo not open with a preamble to the response, just respond.\n", "prompt_template": "{user_question}", "num_tokens_for_completion": 12000, "llm_endpoint_params": { "temperature": 0.1, "top_p": 1, "frequency_penalty": 0.75, "presence_penalty": 0.75, "stop": "<|im_end|>", "type": "openai_params" }, "embeddings": { "model": "azure__openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } }, "content_template": "`````{content}`````" } } ``` When you set the `mode` parameter to `extract` the response will be as follows: ``` { "type": "ai_agent_extract", "basic_text": { "model": "google__gemini_1_5_flash_001", "system_message": "Respond only in valid json. You are extracting metadata that is name, value pairs from a document. Only output the metadata in valid json form, as {\"name1\":\"value1\",\"name2\":\"value2\"} and nothing else. You will be given the document data and the schema for the metadata, that defines the name, description and type of each of the fields you will be extracting. Schema is of the form {\"fields\": [{\"key\": \"key_name\", \"displayName\": \"key display name\", \"type\": \"string\", \"description\": \"key description\"}]}. Leverage key description and key display name to identify where the key and value pairs are in the document. In certain cases, key description can also indicate the instructions to perform on the document to obtain the value. Prompt will be in the form of Schema is ``schema`` \n document is````document````", "prompt_template": "If you need to know today's date to respond, it is {current_date}. Schema is ``{user_question}`` \n document is````{content}````", "num_tokens_for_completion": 4096, "llm_endpoint_params": { "temperature": 0, "top_p": 1, "top_k": null, "type": "google_params" } }, "long_text": { "model": "google__gemini_1_5_flash_001", "system_message": "Respond only in valid json. You are extracting metadata that is name, value pairs from a document. Only output the metadata in valid json form, as {\"name1\":\"value1\",\"name2\":\"value2\"} and nothing else. You will be given the document data and the schema for the metadata, that defines the name, description and type of each of the fields you will be extracting. Schema is of the form {\"fields\": [{\"key\": \"key_name\", \"displayName\": \"key display name\", \"type\": \"string\", \"description\": \"key description\"}]}. Leverage key description and key display name to identify where the key and value pairs are in the document. In certain cases, key description can also indicate the instructions to perform on the document to obtain the value. Prompt will be in the form of Schema is ``schema`` \n document is````document````", "prompt_template": "If you need to know today's date to respond, it is {current_date}. Schema is ``{user_question}`` \n document is````{content}````", "num_tokens_for_completion": 4096, "llm_endpoint_params": { "temperature": 0, "top_p": 1, "top_k": null, "type": "google_params" }, "embeddings": { "model": "azure__openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } } } } ``` When you set the `mode` parameter to `extract_structured` the response will be as follows: ``` { "type": "ai_agent_extract_structured", "basic_text": { "model": "google__gemini_1_5_flash_001", "system_message": "Respond only in valid json. You are extracting metadata that is name, value pairs from a document. Only output the metadata in valid json form, as {\"name1\":\"value1\",\"name2\":\"value2\"} and nothing else. You will be given the document data and the schema for the metadata, that defines the name, description and type of each of the fields you will be extracting. Schema is of the form {\"fields\": [{\"key\": \"key_name\", \"prompt\": \"prompt to extract the value\", \"type\": \"date\"}]}. Leverage prompt for each key to identify where the key and value pairs are in the document. In certain cases, prompt can also indicate the instructions to perform on the document to obtain the value. Prompt will be in the form of Schema is ``schema`` \n document is````document````", "prompt_template": "If you need to know today's date to respond, it is {current_date}. Schema is ``{user_question}`` \n document is````{content}````", "num_tokens_for_completion": 4096, "llm_endpoint_params": { "temperature": 0, "top_p": 1, "top_k": null, "type": "google_params" } }, "long_text": { "model": "google__gemini_1_5_flash_001", "system_message": "Respond only in valid json. You are extracting metadata that is name, value pairs from a document. Only output the metadata in valid json form, as {\"name1\":\"value1\",\"name2\":\"value2\"} and nothing else. You will be given the document data and the schema for the metadata, that defines the name, description and type of each of the fields you will be extracting. Schema is of the form {\"fields\": [{\"key\": \"key_name\", \"prompt\": \"prompt to extract the value\", \"type\": \"date\"}]}. Leverage prompt for each key to identify where the key and value pairs are in the document. In certain cases, prompt can also indicate the instructions to perform on the document to obtain the value. Prompt will be in the form of Schema is ``schema`` \n document is````document````", "prompt_template": "If you need to know today's date to respond, it is {current_date}. Schema is ``{user_question}`` \n document is````{content}````", "num_tokens_for_completion": 4096, "llm_endpoint_params": { "temperature": 0, "top_p": 1, "top_k": null, "type": "google_params" }, "embeddings": { "model": "google__textembedding_gecko_003", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } } } } ``` **Reference:** https://developer.box.com/guides/box-ai/ai-agents/get-agent-default-config/ --- ## Untitled *Type: guide | Category: Authentication * Use a Token Every authenticated API call requires an Access Token to be passed in the Authorization header as a Bearer Token or it will… # Use a Token Every authenticated API call requires an Access Token to be passed in the `Authorization` header as a `Bearer Token` or it will return a `401 Unauthorized` HTTP status. ``` curl https://api.box.com/2.0/users/me \ -H "authorization: Bearer EGmDmRVfhfHsqesn5yVYHAqUkD0dyDfk" ``` Use the [`GET /users/me`](endpoint://get-users-id) endpoint to inspect what user an Access Token is authenticated for. **Reference:** https://developer.box.com/guides/authentication/tokens/api-calls/ --- ## Untitled *Type: guide | Category: Box AI * AWS Claude 3.7 Sonnet Overview AWS Claude 3.7 Sonnet model is designed to enhance language understanding and generation tasks. Model details… # AWS Claude 3.7 Sonnet ## Overview **AWS Claude 3.7 Sonnet** model is designed to enhance language understanding and generation tasks. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | AWS Claude 3.7 Sonnet | The name of the model. | | Model category | Premium | The category of the model - standard or premium. | | API model name | aws__claude_3_7_sonnet | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Amazon Web Services (AWS) | The trusted organization that securely hosts LLM. | | Model provider | Anthropic | The organization that provides this model. | | Release date | February 24, 2025 | The release date for the model. | | Knowledge cutoff date | October 2024 | The date after which the model does not get any information updates. | | Input context window | 200k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 8k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 42 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official AWS Claude documentation](https://aws.amazon.com/bedrock/claude/). **Reference:** https://developer.box.com/guides/box-ai/ai-models/aws-claude-3-7-sonnet-model-card/ --- ## Untitled *Type: guide | Category: Box AI * AWS Claude 3.5 Sonnet Overview AWS Claude 3.5 Sonnet model is designed to enhance language understanding and generation tasks. Model details… # AWS Claude 3.5 Sonnet ## Overview **AWS Claude 3.5 Sonnet** model is designed to enhance language understanding and generation tasks. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | AWS Claude 3.5 Sonnet | The name of the model. | | Model category | Premium | The category of the model - standard or premium. | | API model name | aws__claude_3_5_sonnet | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Amazon Web Services (AWS) | The trusted organization that securely hosts LLM. | | Model provider | Anthropic | The organization that provides this model. | | Release date | June 20th, 2024 | The release date for the model. | | Knowledge cutoff date | April 2024 | The date after which the model does not get any information updates. | | Input context window | 200k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 8k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official AWS Claude 3.5 Sonnet documentation](https://aws.amazon.com/bedrock/claude/). **Reference:** https://developer.box.com/guides/box-ai/ai-models/aws-claude-3-5-sonnet-model-card/ --- ## Untitled *Type: guide | Category: Box AI * AWS Claude 3 Sonnet AWS Claude 3 Sonnet model is designed for advanced language tasks, focusing on comprehension and context handling. Model… # AWS Claude 3 Sonnet **AWS Claude 3 Sonnet** model is designed for advanced language tasks, focusing on comprehension and context handling. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | AWS Claude 3 Sonnet | The name of the model. | | Model category | Premium | The category of the model - standard or premium. | | API model name | aws__claude_3_sonnet | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Amazon Web Services (AWS) | The trusted organization that securely hosts LLM. | | Model provider | Anthropic | The organization that provides this model. | | Release date | March 4th 2024 | The release date for the model. | | Knowledge cutoff date | August 2023 | The date after which the model does not get any information updates. | | Input context window | 200k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 4k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 49.8 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official AWS Claude 3 Sonnet documentation](https://aws.amazon.com/bedrock/claude/). **Reference:** https://developer.box.com/guides/box-ai/ai-models/aws-claude-3-sonnet-model-card/ --- ## Untitled *Type: guide | Category: Box AI * AWS Claude 3 Haiku Overview AWS Claude 3 Haiku model is tailored for various language tasks, including creative writing and conversational… # AWS Claude 3 Haiku ## Overview **AWS Claude 3 Haiku** model is tailored for various language tasks, including creative writing and conversational AI. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | AWS Claude 3 Haiku | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | aws__claude_3_haiku | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Amazon Web Services (AWS) | The trusted organization that securely hosts LLM. | | Model provider | Anthropic | The organization that provides this model. | | Release date | March 13th, 2024 | The release date for the model. | | Knowledge cutoff date | August 2023 | The date after which the model does not get any information updates. | | Input context window | 200k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 4k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 117 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official AWS Claude 3 Haiku documentation](https://aws.amazon.com/bedrock/claude/). **Reference:** https://developer.box.com/guides/box-ai/ai-models/aws-claude-3-haiku-model-card/ --- ## Untitled *Type: guide | Category: Box AI * AWS Claude 4 Opus AWS Claude 4 Opus model excels at coding and complex problem-solving, powering frontier agent products. It's possible to… # AWS Claude 4 Opus **AWS Claude 4 Opus** model excels at coding and complex problem-solving, powering frontier agent products. It's possible to run Claude Code in the background, enabling developers to assign long-running coding tasks for Opus to handle independently. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | AWS Claude 4 Opus | The name of the model. | | Model category | Premium | The category of the model - standard or premium. | | API model name | aws__claude_4_opus | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Amazon Web Services (AWS) | The trusted organization that securely hosts LLM. | | Model provider | Anthropic | The organization that provides this model. | | Release date | March 4th 2024 | The release date for the model. | | Knowledge cutoff date | August 2023 | The date after which the model does not get any information updates. | | Input context window | 200k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 32k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official AWS Claude 4 Opus documentation](https://aws.amazon.com/bedrock/claude/). **Reference:** https://developer.box.com/guides/box-ai/ai-models/aws-claude-4-opus-model-card/ --- ## Untitled *Type: guide | Category: Box AI * AWS Claude 4 Sonnet AWS Claude 4 Sonnet model delivers superior coding and reasoning while responding more precisely to your instructions… # AWS Claude 4 Sonnet **AWS Claude 4 Sonnet** model delivers superior coding and reasoning while responding more precisely to your instructions, and brings frontier performance to everyday use cases. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | AWS Claude 4 Sonnet | The name of the model. | | Model name | AWS Titan Text Lite | The name of the model - standard or premium. | | API model name | aws__claude_4_sonnet | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Amazon Web Services (AWS) | The trusted organization that securely hosts LLM. | | Model provider | Anthropic | The organization that provides this model. | | Release date | May 22nd 2025 | The release date for the model. | | Knowledge cutoff date | November 2024 | The date after which the model does not get any information updates. | | Input context window | 200k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 64k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official AWS Claude 4 Sonnet documentation](https://aws.amazon.com/bedrock/claude/). **Reference:** https://developer.box.com/guides/box-ai/ai-models/aws-claude-4-sonnet-model-card/ --- ## Untitled *Type: guide | Category: Box AI * AWS Titan Text Lite AWS Titan Text Lite model is designed for advanced language processing, capable of handling extensive contexts, making… # AWS Titan Text Lite **AWS Titan Text Lite** model is designed for advanced language processing, capable of handling extensive contexts, making it suitable for complex tasks, although the model itself is lightweight. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | AWS Titan Text Lite | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | aws__titan_text_lite | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Amazon Web Services (AWS) | The trusted organization that securely hosts LLM. | | Model provider | Anthropic | The organization that provides this model. | | Release date | September 2024 | The release date for the model. | | Knowledge cutoff date | Not provided | The date after which the model does not get any information updates. | | Input context window | 128k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 4k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official AWS Titan documentation](https://aws.amazon.com/bedrock/titan/). **Reference:** https://developer.box.com/guides/box-ai/ai-models/aws-titan-text-lite-model-card/ --- ## Untitled *Type: guide | Category: Box AI * Azure OpenAI GPT-4.1 Mini Azure OpenAI GPT-4.1 Mini is a multimodal model designed to handle lightweight tasks. Model details Item Value… # Azure OpenAI GPT-4.1 Mini **Azure OpenAI GPT-4.1 Mini** is a multimodal model designed to handle lightweight tasks. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | GPT-4.1 mini | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | azure__openai__gpt_4.1_mini | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Microsoft Azure | The trusted organization that securely hosts LLM. | | Model provider | Microsoft Azure | The organization that provides this model. | | Release date | April 14th, 2025 | The release date for the model. | | Knowledge cutoff date | May 2024 | The date after which the model does not get any information updates. | | Input context window | 1m tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 32k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 87.5 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Azure OpenAI GPT-4o documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4o-and-gpt-4-turbo). **Reference:** https://developer.box.com/guides/box-ai/ai-models/azure-openai-gpt-4-1-mini-model-card/ --- ## Untitled *Type: guide | Category: Box AI * Azure OpenAI GPT-4.1 Azure OpenAI GPT-4.1 is a multimodal model, highly efficient in handling complex, multi-step tasks. Model details Item… # Azure OpenAI GPT-4.1 **Azure OpenAI GPT-4.1** is a multimodal model, highly efficient in handling complex, multi-step tasks. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | GPT-4.1 | The name of the model. | | Model category | Premium | The category of the model - standard or premium. | | API model name | azure__openai__gpt_4_1 | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Microsoft Azure | The trusted organization that securely hosts LLM. | | Model provider | Microsoft Azure | The organization that provides this model. | | Release date | April 14th, 2025 | The release date for the model. | | Knowledge cutoff date | May 2024 | The date after which the model does not get any information updates. | | Input context window | 1m tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 32k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 87.5 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Azure OpenAI GPT-4o documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4o-and-gpt-4-turbo). **Reference:** https://developer.box.com/guides/box-ai/ai-models/azure-openai-gpt-4-1-model-card/ --- ## Untitled *Type: guide | Category: Box AI * Azure OpenAI GPT-4o Azure OpenAI GPT-4o is a multimodal model designed to handle lightweight tasks. Model details Item Value Description… # Azure OpenAI GPT-4o **Azure OpenAI GPT-4o** is a multimodal model designed to handle lightweight tasks. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | GPT-4o | The name of the model. | | Model category | Premium | The category of the model - standard or premium. | | API model name | azure__openai__gpt_4o | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Microsoft Azure | The trusted organization that securely hosts LLM. | | Model provider | Microsoft Azure | The organization that provides this model. | | Release date | May 13th, 2024 | The release date for the model. | | Knowledge cutoff date | September 2023 | The date after which the model does not get any information updates. | | Input context window | 128k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 2k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 87.5 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Azure OpenAI GPT-4o documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4o-and-gpt-4-turbo). **Reference:** https://developer.box.com/guides/box-ai/ai-models/azure-openai-gpt-4o-model-card/ --- ## Untitled *Type: guide | Category: Box AI * Azure OpenAI GPT-4o Mini Azure OpenAI GPT-4o Mini is a multimodal model designed to handle lightweight tasks. Model details Item Value… # Azure OpenAI GPT-4o Mini **Azure OpenAI GPT-4o Mini** is a multimodal model designed to handle lightweight tasks. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | GPT-4o Mini | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | azure__openai__gpt_4o_mini | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Microsoft Azure | The trusted organization that securely hosts LLM. | | Model provider | Microsoft Azure | The organization that provides this model. | | Release date | July 18th, 2024 | The release date for the model. | | Knowledge cutoff date | October 2023 | The date after which the model does not get any information updates. | | Input context window | 128k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 16k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 85.4 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Usage Box Webapp uses this model to cover the following use cases: - Creating content - Editing content - Creating summaries - Single doc Q&A on text Box AI API uses this model to cover the following use cases: - Creating content - Editing content - Creating summaries - Single doc Q&A on text - Extracting metadata ## Additional documentation For additional information, see [official Azure OpenAI GPT-4o Mini documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models?tabs=python-secure#gpt-4o-and-gpt-4-turbo). **Reference:** https://developer.box.com/guides/box-ai/ai-models/azure-openai-gpt-4o-mini-model-card/ --- ## Untitled *Type: guide | Category: Box AI * Azure text-embedding-ada-002 Azure text-embedding-ada-002 is a multimodal model designed to handle lightweight tasks. Model details Item… # Azure text-embedding-ada-002 **Azure text-embedding-ada-002** is a multimodal model designed to handle lightweight tasks. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | text-embedding-ada-002 | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | azure__openai__text_embedding_ada_002 | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Microsoft Azure | The trusted organization that securely hosts LLM. | | Model provider | Microsoft Azure | The organization that provides this model. | | Release date | December 2022 | The release date for the model. | | Knowledge cutoff date | September 2021 | The date after which the model does not get any information updates. | | Input context window | 8k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | Not applicable | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 1000 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Azure Embeddings models documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models#embeddings). **Reference:** https://developer.box.com/guides/box-ai/ai-models/azure-text-embedding-ada-002-model-card/ --- ## Untitled *Type: guide | Category: Box AI * Google Gemini 1.5 Flash Google Gemini 1.5 Flash is a multimodal model designed to handle lightweight tasks. It is designed for high-volume… # Google Gemini 1.5 Flash **Google Gemini 1.5 Flash** is a multimodal model designed to handle lightweight tasks. It is designed for high-volume, low-latency tasks, making it highly efficient for large-scale use cases like summarization, multimodal processing, and categorization ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | Google Gemini 1.5 Flash | The name of the model. | | API model name | google__gemini_1_5_flash_001 | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Google | The trusted organization that securely hosts LLM. | | Model provider | Google | The organization that provides this model. | | Release date | May 14th 2024 | The release date for the model. | | Knowledge cutoff date | November 2023 | The date after which the model does not get any information updates. | | Input context window | 1m tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 8k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 176 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Google Gemini 1.5 Flash documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#gemini-models). **Reference:** https://developer.box.com/guides/box-ai/ai-models/google-gemini-1-5-flash-001-model-card/ --- ## Untitled *Type: guide | Category: Box AI * Google Gemini 2.0 Flash Lite Google Gemini 2.0 Flash Lite is a multimodal model designed to handle lightweight tasks. It is designed for… # Google Gemini 2.0 Flash Lite **Google Gemini 2.0 Flash Lite** is a multimodal model designed to handle lightweight tasks. It is designed for high-volume, low-latency tasks, making it highly efficient for large-scale use cases like summarization, multimodal processing, and categorization but with higher quality than Gemini 1.5 Flash. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | Google Gemini 2.0 Flash Lite | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | google__gemini_2_0_flash_lite_preview | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Google | The trusted organization that securely hosts LLM. | | Model provider | Google | The organization that provides this model. | | Release date | February 5th 2025 | The release date for the model. | | Knowledge cutoff date | June 2024 | The date after which the model does not get any information updates. | | Input context window | 1m tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 8k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 168 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Google Gemini 2.0 Flash Lite documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#gemini-models). **Reference:** https://developer.box.com/guides/box-ai/ai-models/google-gemini-2-0-flash-lite-preview-02-05/ --- ## Untitled *Type: guide | Category: Box AI * Google Gemini 1.5 Pro 001 Google Gemini 1.5 Pro 001 is a multimodal model designed to handle lightweight tasks. This model mid-size… # Google Gemini 1.5 Pro 001 **Google Gemini 1.5 Pro 001** is a multimodal model designed to handle lightweight tasks. This model mid-size multimodal model capable of handling extensive inputs like long videos, hours of audio, large data sets, and complex reasoning tasks ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | Google Gemini 1.5 Pro 001 | The name of the model. | | API model name | google__gemini_1_5_pro_001 | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Google | The trusted organization that securely hosts LLM. | | Model provider | Google | The organization that provides this model. | | Release date | February 15th 2024 | The release date for the model. | | Knowledge cutoff date | November 2023 | The date after which the model does not get any information updates. | | Input context window | 1m tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 8k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 45.5 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Google Gemini 1.5 Pro documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#gemini-models). **Reference:** https://developer.box.com/guides/box-ai/ai-models/google-gemini-1-5-pro-001-model-card/ --- ## Untitled *Type: guide | Category: Authentication * Developer Tokens A Developer Token is an Access Token available to developers during development and testing. These tokens are short lived… # Developer Tokens A Developer Token is an Access Token available to developers during development and testing. These tokens are short lived, as they expire after 60 minutes, and cannot be refreshed programmatically. ## Create Developer Token To create a Developer Token for an application: - Navigate to the Box [Developer Console](https://app.box.com/developers/console) and select the application to create a Developer Token for. - Select the **Configuration** tab. - Under Developer Token, select **Generate Developer Token**. You can also generate a Developer Token directly from [My Platform Apps](g://applications) view, using the menu available for each app. ## Using Developer Token A Developer Token can be used like any Access Token in the `Authorization` header of an API call. ``` curl https://api.box.com/2.0/users/me \ -H "authorization: Bearer [DEVELOPER_TOKEN]" ``` A Developer Token is associated with the the user that is logged in to the Developer Console when the token is generated. Our SDKs can be initialized with a Developer Token to create a basic API client. # Developer tokens should not be used in production environments Developer Tokens should only be used for development or testing purposes. When you explicitly revoke a developer token for a given app via the Developer console, all webhooks created by that application get deleted. ## Using SDKs and Developer Tokens To learn more about Developer Tokens for each SDK head over to: [.Net](https://github.com/box/box-windows-sdk-v2/blob/main/docs/authentication.md#developer-token) [Java](https://github.com/box/box-java-sdk/blob/main/doc/authentication.md#developer-token) [Python](https://github.com/box/box-python-sdk/blob/main/docs/usage/authentication.md#developer-token) [Node](https://github.com/box/box-node-sdk/blob/main/docs/authentication.md#developer-token) [IOS](https://github.com/box/box-ios-sdk/blob/main/docs/usage/authentication.md#developer-token) **Reference:** https://developer.box.com/guides/authentication/tokens/developer-tokens/ --- ## Untitled *Type: guide | Category: Box AI * Google Gemini 2.0 Flash Google Gemini 2.0 Flash is a multimodal model designed for optimal for high-volume, high-frequency tasks at scale… # Google Gemini 2.0 Flash **Google Gemini 2.0 Flash** is a multimodal model designed for optimal for high-volume, high-frequency tasks at scale. It capable of multimodal reasoning and has a context window of 1 million tokens. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | Google Gemini 2.0 Flash | The name of the model. | | Model name | Google Gemini 2.0 Flash | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | google__gemini_2_0_flash_001 | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Google | The trusted organization that securely hosts LLM. | | Model provider | Google | The organization that provides this model. | | Release date | February 5th 2025 | The release date for the model. | | Knowledge cutoff date | June 2024 | The date after which the model does not get any information updates. | | Input context window | 1m tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 8k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | 168 | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Google Gemini 2.0 Flash documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#gemini-models). **Reference:** https://developer.box.com/guides/box-ai/ai-models/google-gemini-2-0-flash-001-model-card/ --- ## Untitled *Type: guide | Category: Authentication * Downscope a Token Downscoping is a way to exchange an existing Access Token for a new one that is more restricted. Reasons to downscope An… # Downscope a Token Downscoping is a way to exchange an existing Access Token for a new one that is more restricted. ## Reasons to downscope An application might need to share the Access Token with an environment that it does not fully control. A common example of this would be when using Box UI Elements in a web browser. When an application needs to pass an Access Token to the browser there is a potential security risk that needs to be resolved. In order to limit this risk the Access Token can be exchanged for a new token with much stricter permissions. ## High-level overview A downscoped token is a token that has fewer permissions (scopes) than the original token, as well as the optional additional restriction to only allow access to a specific file. The new token takes the permissions of the original token and restricts them to the tokens passed in, as well as the resource provided. ## Downscoping in practice To downscope a token, pass the `POST /oauth2/token` endpoint an existing Access Token, a list of scopes, as well as an optional file URL to restrict the token to. | Parameter | Description | | --- | --- | | subject_token | The original token to downscope. This can be a token that was acquired through OAuth 2.0, JWT token exchange, or as an App Token. | | scope | A space-delimited list of scopes to limit the new token to. Any valid scope for the application can be used, though a special set of scopes for Box UI elements is available | | resource | An optional full URL path to the file the token should be restricted to. | | box_shared_link | An optional shared link URL for a file or folder on Box. Password protected links are not supported. This option cannot be used in addition to the resource option nor can it be a shared link created on a weblink. | | subject_token_type | Always set to urn:ietf:params:oauth:token-type:access_token | | grant_type | Always set to urn:ietf:params:oauth:grant-type:token-exchange | ## Downscoped Access Token Object A downscoped Access Token returned by the `POST /oauth2/token` endpoint contains extra information on the specific restrictions. ``` { "access_token": "1!DgsZ6V9kMWZu2StrxwQDF5BudQNen-xUmU2cfcVKArE....", "expires_in": 4175, "token_type": "bearer", "restricted_to": [ { "scope": "item_preview", "object": { "type": "folder", "id": "1234567890", "sequence_id": "0", "etag": "0", "name": "Test" } } ], "issued_token_type": "urn:ietf:params:oauth:token-type:access_token" } ``` Most importantly here is the list of `restricted_to` entries that will contain each combination of `object` and `scope` that the new token has the permissions for. A downscoped token does not include a refresh token. To get a new downscoped token, refresh the original refresh token and use that new token to get a downscoped token. **Reference:** https://developer.box.com/guides/authentication/tokens/downscope/ --- ## Untitled *Type: guide | Category: Box AI * Google Gemini 2.5 Pro Google Gemini 2.5 Pro is a multimodal model capable of solving complex problems. It can comprehend vast datasets and… # Google Gemini 2.5 Pro **Google Gemini 2.5 Pro** is a multimodal model capable of solving complex problems. It can comprehend vast datasets and challenging problems from different information sources, including text, audio, images, video, and even entire code repositories. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | Google Gemini 2.5 Pro | The name of the model. | | Model category | Premium | The category of the model: Standard or Premium. | | API model name | google__gemini_2_5_pro | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | Google | The trusted organization that securely hosts LLM. | | Model provider | Google | The organization that provides this model. | | Release date | June 17th 2025 | The release date for the model. | | Knowledge cutoff date | January 2025 | The date after which the model does not get any information updates. | | Input context window | 1m tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 65k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official Google Gemini 2.5 Pro documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/2-5-pro). **Reference:** https://developer.box.com/guides/box-ai/ai-models/google-gemini-2-5-pro-model-card/ --- ## Untitled *Type: guide | Category: Box AI * IBM Llama 3.2 Vision Instruct IBM Llama 3.2 Vision Instruct is a model built for image-in, text-out use cases such as document-level… # IBM Llama 3.2 Vision Instruct **IBM Llama 3.2 Vision Instruct** is a model built for image-in, text-out use cases such as document-level understanding, interpretation of charts and graphs, and captioning of images. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | IBM Llama 3.2 Vision Instruct | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | ibm__llama__3_2_90b_vision_instruct | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | IBM | The trusted organization that securely hosts LLM. | | Model provider | Meta | The organization that provides this model. | | Release date | September 25th 2024 | The release date for the model. | | Knowledge cutoff date | December 2023 | The date after which the model does not get any information updates. | | Input context window | 128k | The number of tokens supported by the input context window. | | Maximum output tokens | Not specified | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | Yes | Specifies if the model's code is available for public use. | | IP infringement protection | No | Use of this model does not come with any intellectual property rights assurances or protections from Box. Please consider any potential IP issues that might arise from using the model’s outputs. | ## Additional documentation For additional information, see [official IBM Llama 3.2 Vision Instruct documentation](https://www.ibm.com/docs/en/watsonx/w-and-w/2.1.0?topic=models-third-party-foundation#llama-3-2-vision). **Reference:** https://developer.box.com/guides/box-ai/ai-models/ibm-llama-3-2-90b-vision-instruct-model-card/ --- ## Untitled *Type: guide | Category: Box AI * OpenAI GPT o3 OpenAI GPT o3 is specifically designed to tackle reasoning and problem-solving tasks with increased focus and capability. It… # OpenAI GPT o3 **OpenAI GPT o3** is specifically designed to tackle reasoning and problem-solving tasks with increased focus and capability. It spends more time processing and understanding the user's request, making it exceptionally strong in areas like science, coding, and math compared to previous iterations. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | GPT o3 | The name of the model. | | Model category | Premium | The category of the model - standard or premium. | | API model name | openai__gpt_o3 | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | OpenAI | The trusted organization that securely hosts LLM. | | Model provider | OpenAI | The organization that provides this model. | | Release date | April 16th, 2025 | The release date for the model. | | Knowledge cutoff date | May 2024 | The date after which the model does not get any information updates. | | Input context window | 200k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 100k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | ## Additional documentation For additional information, see [official OpenAI GPT o3 documentation](https://openai.com/index/introducing-o3-and-o4-mini/). **Reference:** https://developer.box.com/guides/box-ai/ai-models/openai-gpt-o3-model-card/ --- ## Untitled *Type: guide | Category: Box AI * IBM Llama 4 Scout IBM Llama 4 Scout is an auto-regressive language model that uses a mixture-of-experts (MoE) architecture and incorporates… # IBM Llama 4 Scout **IBM Llama 4 Scout** is an auto-regressive language model that uses a mixture-of-experts (MoE) architecture and incorporates early fusion for native multimodality. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | IBM Llama 4 Scout | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | ibm__llama_4_scout | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | IBM | The trusted organization that securely hosts LLM. | | Model provider | Meta | The organization that provides this model. | | Release date | April 5th 2025 | The release date for the model. | | Knowledge cutoff date | August 2024 | The date after which the model does not get any information updates. | | Input context window | 10m | The number of tokens supported by the input context window. | | Maximum output tokens | Not specified | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | Yes | Specifies if the model's code is available for public use. | | IP infringement protection | No | Use of this model does not come with any intellectual property rights assurances or protections from Box. Please consider any potential IP issues that might arise from using the model’s outputs. | ## Additional documentation For additional information, see [official IBM Llama 4 Scout documentation](https://www.ibm.com/docs/en/watsonx/w-and-w/2.1.0?topic=models-third-party-foundation). **Reference:** https://developer.box.com/guides/box-ai/ai-models/ibm-llama-4-scout-model-card/ --- ## Untitled *Type: guide | Category: Box AI * xAI Grok 3 Beta xAI Grok 3 Beta is a model that excels at enterprise use cases like data extraction, coding, and text summarization… # xAI Grok 3 Beta **xAI Grok 3 Beta** is a model that excels at enterprise use cases like data extraction, coding, and text summarization. Possesses deep domain knowledge in finance, healthcare, law, and science. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | xAI Grok 3 Beta | The name of the model. | | Model category | Premium | The category of the model - standard or premium. | | API model name | xai__grok_3_beta | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | xAI | The trusted organization that securely hosts LLM. | | Model provider | xAI | The organization that provides this model. | | Release date | April 17th 2025 | The release date for the model. | | Knowledge cutoff date | January 2025 | The date after which the model does not get any information updates. | | Input context window | 1m tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 131k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | | IP infringement protection | No | Use of this model does not come with any intellectual property rights assurances or protections from Box. Please consider any potential IP issues that might arise from using the model’s outputs. | ## Additional documentation For additional information, see [official xAI Grok 3 Mini Beta documentation](https://docs.x.ai/docs/models). **Reference:** https://developer.box.com/guides/box-ai/ai-models/xai-grok-3-beta-model-card/ --- ## Untitled *Type: guide | Category: Box AI * xAI Grok 3 Mini Reasoning Beta xAI Grok 3 Mini Reasoning Beta is a lightweight model that thinks before responding. Fast, smart, and great… # xAI Grok 3 Mini Reasoning Beta **xAI Grok 3 Mini Reasoning Beta** is a lightweight model that thinks before responding. Fast, smart, and great for logic-based tasks that do not require deep domain knowledge. The raw thinking traces are accessible. ## Model details | Item | Value | Description | | --- | --- | --- | | Model name | xAI Grok 3 Mini Reasoning Beta | The name of the model. | | Model category | Standard | The category of the model - standard or premium. | | API model name | xai__grok_3_mini_reasoning_beta | The name of the model that is used in the Box AI API for model overrides. The user must provide this exact name for the API to work. | | Hosting layer | xAI | The trusted organization that securely hosts LLM. | | Model provider | xAI | The organization that provides this model. | | Release date | April 9th 2025 | The release date for the model. | | Knowledge cutoff date | unknown | The date after which the model does not get any information updates. | | Input context window | 131k tokens | The number of tokens supported by the input context window. | | Maximum output tokens | 131k tokens | The number of tokens that can be generated by the model in a single request. | | Empirical throughput | Not specified | The number of tokens the model can generate per second. | | Open source | No | Specifies if the model's code is available for public use. | | IP infringement protection | No | Use of this model does not come with any intellectual property rights assurances or protections from Box. Please consider any potential IP issues that might arise from using the model’s outputs. | ## Additional documentation For additional information, see [official xAI Grok 3 Mini Beta documentation](https://docs.x.ai/docs/models). **Reference:** https://developer.box.com/guides/box-ai/ai-models/xai-grok-3-mini-beta-model-card/ --- ## Untitled *Type: guide | Category: Box AI * Ask questions to Box AI Box AI API is available to all Enterprise Plus and Enterprise Advanced customers. Box AI API allows you to ask a… # Ask questions to Box AI Box AI API is available to all Enterprise Plus and Enterprise Advanced customers. Box AI API allows you to ask a question about a supplied file or a set of files, and get a response based on the content. For example, while viewing a document in Box, you can ask Box AI to summarize the content. ## Before you start Make sure you followed the steps listed in [getting started with Box AI](g://box-ai/ai-tutorials/prerequisites) to create a platform app and authenticate. ## Send a request To send a request containing your question, use the `POST /2.0/ai/ask` endpoint and provide the mandatory parameters. ### Parameters To make a call, you need to pass the following parameters. Mandatory parameters are in **bold**. | Parameter | Description | Available values | Example | | --- | --- | --- | --- | | mode | The type of request. It can be a question about a single file or a set of files. For a single text files, Box AI API supports up to 1MB of text representation. If the file size exceeds 1MB, the first 1MB of text representation will be processed. If you want to list multiple files, the limit is 25 files. Box AI handles image documents with a resolution of 1024 x 1024 pixels, with a maximum of 5 images or 5 pages for multi-page images. If the number of image or image pages exceeds 5, the first 5 images or pages will be processed. If you set mode to single_item_qa, the items array can list only one element. Currently Box AI does not support multi-modal requests. If both images and text are sent Box AI will only process the text. | single_item_qa, multiple_item_qa | single_item_qa | | prompt | The question about your document or content. The prompt's length cannot exceed 10000 characters. | | What is this document about? | | dialogue_history.prompt | The prompt previously provided by the client and answered by the Large Language Model (LLM). | Make my email about public APIs sound more professional | | | dialogue_history.answer | The answer previously provided by the LLM. | Here is a draft of your professional email about public APIs. | | | dialogue_history.created_at | The ISO date formatted timestamp of when the previous answer to the prompt was created. | 2012-12-12T10:53:43-08:00 | | | include_citations | Specifies if the citations should be returned in the answer. | true, false | true | | items.id | The Box file ID you want to provide as input. | | 112233445566 | | items.type | The type of the provided input. Currently, it can be a single file or multiple files. | file | file | | items.content | The content of the item. Usually it is the text representation. | | An application programming interface (API) is a way for two or more computer programs or components to communicate with each other. It is a type of software interface... | | ai_agent | The AI agent used to override the default agent configuration. You can use this parameter replace the default LLM with a custom one using the model parameter for shorter and longer texts, tweak the base prompt to allow for a more customized user experience, or change an LLM parameter, such as temperature, to make the results more or less creative. Before you use the ai_agent parameter, you can get the default configuration using the GET 2.0/ai_agent_default request. For specific use cases, see the AI model overrides tutorial. | | | ## Use cases ## Ask questions about an item This example shows how to ask a question about one or more items using the `POST ask/ai` API. When using this endpoint, remember to specify the `mode` parameter depending on the number of items you want to supply. ``` curl -i -L POST "https://api.box.com/2.0/ai/ask" \ -H "content-type: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "mode": "single_item_qa", "items": [ { "id": "12345678", "type": "file" } ], "prompt": "List the guidelines on creating questions in Box AI for Documents" }' ``` The response will be as follows: ``` { "answer": "The guidelines for working with questions in Box AI for Documents are as follows:\n\n1. Box AI pulls information only from the document loaded in preview.\n2. If questions fall outside the scope of the document, Box AI will inform you that it cannot answer.\n3. Be specific when asking questions; use parameters like numbered lists, brevity, tables, and central themes or key points.\n4. Aim to stay within the scope of the document.\n5. Focus on text-based responses only.", "created_at": "2024-11-04T02:30:09.557-08:00", "completion_reason": "done" } ``` ## Ask questions with content parameter If you use the `content` parameter as the source of input for Box AI, it will use it as the primary source. ``` curl -i -L POST "https://api.box.com/2.0/ai/ask" \ -H "content-type: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "mode": "single_item_qa", "items": [ { "id": "12345678", "type": "file", "content": "This is a document about Box AI For documents. It consists of the functionality summary and guidelines on how to work with Box AI. Additionally, it provides a set of best practices for creating questions." } ], "prompt": "List the guidelines on creating questions in Box AI for Documents" }' ``` The response to this request is based on the `content` parameter instead of the file's content: ``` { "answer": "The document does not provide specific guidelines on working with questions in Box AI for Documents. It only mentions that it includes a set of best practices for creating questions, but the details of those guidelines are not included in the text provided. If you have more information or another document, I can help further!", "created_at": "2024-11-04T02:31:51.125-08:00", "completion_reason": "done" } ``` ## Ask questions with citations parameter Setting the `citations` parameter to `true` causes the response to include excerpts from source file or files Box AI used to compile the answer. ``` curl -i -L POST "https://api.box.com/2.0/ai/ask" \ -H "content-type: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "mode": "multiple_item_qa", "include_citations": true, "items": [ { "id": "12345678", "type": "file" } ], "prompt": "List the guidelines on working with responses in Box AI for Documents" }' ``` The resulting answer includes the source file and direct content citations. ``` { "answer": "The guidelines for working with questions in Box AI for Documents are as follows:\n\n1. Box AI pulls information only from the document loaded in preview, and cannot answer questions outside its scope.\n2. Be specific when asking questions; use parameters like numbered lists, brevity, tables, and central themes or key points.\n3. Examples of better phrasing include asking for a numbered list of key points instead of just \"list key points,\" and requesting a succinct outline of important points rather than a general inquiry about the document's purpose.\n4. Stay within the scope of the document and focus on text-based responses only.", "created_at": "2024-11-04T02:35:00.578-08:00", "completion_reason": "done", "citations": [ { "type": "file", "id": "12345678", "name": "Box AI for Documents.docx", "content": "Guidelines for Box AI questions\nBox AI pulls information only from the document you loaded in preview." }, { "type": "file", "id": "12345678", "name": "Box AI for Documents.docx", "content": "If you ask any questions outside of the scope of the document, Box AI informs you that it cannot answer the question with the information provided." }, { "type": "file", "id": "12345678", "name": "Box AI for Documents.docx", "content": "As you ask Box AI to analyze your document, consider these suggestions:\n· Be as specific as possible." }, { "type": "file", "id": "12345678", "name": "Box AI for Documents.docx", "content": "Box AI for Documents\n\nWhen viewing a document in Box, you can ask Box AI to summarize document content, search key points, and write outline drafts based on your document files." } ] } ``` **Reference:** https://developer.box.com/guides/box-ai/ai-tutorials/ask-questions/ --- ## Untitled *Type: guide | Category: Box AI * Override AI model configuration Before you start Make sure you followed the steps listed in getting started with Box AI to create a platform… # Override AI model configuration ## Before you start Make sure you followed the steps listed in [getting started with Box AI](g://box-ai/ai-tutorials/prerequisites) to create a platform app and authenticate. To get more context, read about [agent overrides](g://box-ai/ai-agents/ai-agent-overrides). ## Override prompt This example shows how to use the `prompt_template` parameter to change the query result. The first step is to ask Box AI to summarize a document about Box AI for Documents. The `mode` parameter is set to `single_item_qa` because only one document is supplied. ``` curl -i -L POST "https://api.box.com/2.0/ai/ask" \ -H "content-type: application/json" \ -H "authorization: <Bearer TOKEN>" \ -d '{ "mode": "single_item_qa", "prompt": "Summarize this article about Box AI for Documents", "items": [ { "type": "file", "id": "123467890" } ] }' ``` You will get a response similar to the following: ``` { "answer": "Box AI for Documents is a tool that enhances document analysis by allowing users to summarize content, identify key points, and draft outlines directly from files in Box. It supports various file types, including text documents, spreadsheets, and presentation slides. Users can initiate interactions with Box AI through the web app, where they can select suggestions or type specific questions. Responses are generated in real time, and users have options to save or clear chat history. The document also provides guidelines for effective inquiries and troubleshooting tips for potential issues with using Box AI.", "created_at": "2024-10-08T00:29:07.283-07:00", "completion_reason": "done" } ``` To further improve the result, you can use the `prompt_template` parameter to add some more instructions for Box AI. In this example, let's change the tone of the response. ``` { "prompt": "Summarize this article about Box AI for Documents", "mode": "single_item_qa", "items": [ { "id": "123467890", "type": "file" } ], "ai_agent": { "type": "ai_agent_ask", "basic_text": { "prompt_template": "prompt_template": "{user_question} Write the summary in an informal way.{content}" }, } } } ``` The response would be slightly less formal: ``` { "answer": "Box AI for Documents is a tool that helps you analyze and gain insights from your documents in Box. You can use it to summarize content, identify key points, and draft outlines, making it easier to handle meeting notes, reports, and marketing materials. To get started, just open a file in the Box web app and click the Box AI button. It offers quick suggestions like summarizing the document or checking for next steps. Responses are generated in real time, and you can save them or clear chat history as needed. Just remember, Box AI only pulls info from the document you're viewing, so be specific with your questions!", "created_at": "2024-10-08T00:38:01.767-07:00", "completion_reason": "done" } ``` ## Override AI model (text generation) This example shows you how changing the AI model in the `ai_agent` options can influence the way the text is generated. First let's generate some text using the `POST ai/text_gen` endpoint. This endpoint is using the OpenAI 3.5 turbo model by default. ``` curl -i -L POST "https://api.box.com/2.0/ai/text_gen" \ -H "content-type: application/json" \ -H "authorization: Bearer TOKEN" \ -d '{ "prompt": "Write a short post about Box AI for documents.Make it highlight the benefits of the solution. You can add some emoticons.", "items": [ { "id": "123467890", "type": "file" } ] } ``` The response is as follows: ``` { "answer": "🌟 Exciting News! 🌟\n\nIntroducing Box AI for documents - your new best friend in creating smarter, more efficient content! 🤖💡\n\n🔹 Say goodbye to manual searching and organizing - Box AI does it all for you!\n🔹 Enjoy lightning-fast document analysis and categorization.\n🔹 Boost productivity with automated suggestions and smart recommendations.\n🔹 Collaborate seamlessly with real-time insights and intelligent tagging.\n\nExperience the future of document creation with Box AI - making work easier, faster, and more fun! 🚀💻 #BoxAI #SmartDocuments", "created_at": "2024-10-08T01:19:06.22-07:00", "completion_reason": "done" } ``` Let's change the model using the `ai_agent` configuration: ``` curl -i -L POST "https://api.box.com/2.0/ai/text_gen" \ -H "content-type: application/json" \ -H "authorization: Bearer TOKEN" \ -d '{ "prompt": "Write a short post about Box AI for documents.Make it highlight the benefits of the solution. You can add some emoticons.", "items": [ { "id": "123467890", "type": "file" } ], "ai_agent": { "type": "ai_agent_text_gen", "basic_gen": { "model": "openai__gpt_4o_2024_05_13" } } } ``` After the model switch, the response is slightly different: ``` { "answer": "🚀 **Boost Your Productivity with Box AI for Documents!** 📄✨\n\nSay goodbye to tedious document creation and editing! With Box AI, you can streamline your workflow and focus on what truly matters. Here’s why you’ll love it:\n\n1. **Smart Suggestions** 🤖: Get real-time recommendations to enhance your content.\n2. **Automated Formatting** 📝: Ensure consistency across all your documents effortlessly.\n3. **Collaboration Made Easy** 👥: Work seamlessly with your team, no matter where they are.\n4. **Time-Saving Templates** ⏳: Use pre-built templates to speed up document creation.\n5. **Enhanced Accuracy** ✅: Reduce errors with intelligent proofreading.\n\nTransform the way you work with documents and experience a new level of efficiency with Box AI! 🌟", "created_at": "2024-10-08T01:28:36.777-07:00", "completion_reason": "done" } ``` As you can see the responses differ to some extent. Thanks to the model switch, you can optimize your interaction with Box AI and choose the most suitable model for your needs. ## Override AI model (metadata extraction) Switching models can also give us different results for metadata extraction. Let's use a sample contract to extract the metadata. In this example, the model used is Google Gemini. ``` curl -i -L 'https://api.box.com/2.0/ai/extract' \ -H 'content-type: application/json' \ -H 'authorization: Bearer TOKEN' \ -d '{ "prompt": "Extract any data that would be good metadata to save for future contracts.", "items": [ { "type": "file", "id": "123456789" } ] }' ``` The response is a set of metadata: ``` { "answer": "{\"Buyer Legal Entity Name\": \"Acme Retail Corp.\", \"Supplier Legal Entity Name\": \"Acme Manufacturing Inc.\", \"Buyer Contact Person\": \"Jane Doe\", \"Supplier Contact Person\": \"Eva Smith\", \"Payment Term\": \"payment in full before pickup of goods\", \"Invoice Currency\": \"Euro\", \"Incoterm\": \"FCA Amsterdam\", \"Governing Law\": \"laws state jurisdiction in which supplier is located\", \"Effective Date\": \"March 27, 2024\", \"Buyer Signature Date\": \"March 28th, 2024\", \"Supplier Signature Date\": \"March 28th, 2024\"}", "created_at": "2024-10-08T01:53:14.993-07:00", "completion_reason": "done" } ``` Let's change the model to the most recent OpenAI option: ``` curl -i -L 'https://api.box.com/2.0/ai/extract' \ -H 'content-type: application/json' \ -H 'authorization: Bearer TOKEN' \ -d '{ "prompt": "Extract any data that would be good metadata to save for future contracts.", "items": [ { "type": "file", "id": "123456789" } ], "ai_agent": { "type": "ai_agent_extract", "basic_text": { "model": "openai__gpt_4o_2024_05_13" } } }' ``` Using this model results in a response listing more metadata entries: ``` { "answer": "{\"Effective Date\": \"March 27, 2024\", \"Supplier Legal Entity Name\": \"Acme Manufacturing Inc.\", \"Supplier Registered Office Address\": \"123 Main Street\", \"Supplier Contact Person(s)\": \"Eva Smith\", \"Buyer Legal Entity Name\": \"Acme Retail Corp.\", \"Buyer Registered Office Address\": \"456 Market Avenue\", \"Buyer Contact Person(s)\": \"Jane Doe\", \"Incoterm\": \"FCA Amsterdam\", \"Payment Term\": \"payment in full before pickup of goods\", \"Invoice Currency\": \"Euro\", \"Buyer Printed Name\": \"Jane Doe\", \"Buyer Date\": \"March 28th, 2024\", \"Buyer Title / Position\": \"CEO\", \"Seller Printed Name\": \"Eve Smith\", \"Seller Date\": \"March 28th, 2024\", \"Seller Title / Position\": \"Sales Manager\"}", "created_at": "2024-10-08T01:54:28.099-07:00", "completion_reason": "done" } ``` **Reference:** https://developer.box.com/guides/box-ai/ai-tutorials/default-agent-overrides/ --- ## Untitled *Type: guide | Category: Box AI * Extract metadata from file (structured) With Box AI API, you can extract metadata from the provided file and get the result in the form of… # Extract metadata from file (structured) With Box AI API, you can extract metadata from the provided file and get the result in the form of key-value pairs. As input, you can either create a structure using the `fields` parameter, or use an already defined metadata template. To learn more about creating templates, see [Creating metadata templates in the Admin Console](https://support.box.com/hc/en-us/articles/360044194033-Customizing-Metadata-Templates) or use the [metadata template API](g://metadata/templates/create). ## Before you start Make sure you followed the steps listed in [getting started with Box AI](g://box-ai/ai-tutorials/prerequisites) to create a platform app and authenticate. ## Send a request To send a request, use the `POST /2.0/ai/extract_structured` endpoint. ### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. The `items` array can have exactly one element. | Parameter | Description | Example | | --- | --- | --- | | metadata_template | The metadata template containing the fields to extract. For your request to work, you must provide either metadata_template or fields, but not both. | | | metadata_template.type | The type of metadata template. | metadata_template | | metadata_template.scope | The scope of the metadata template that can either be global or enterprise. Global templates are those available to any Box enterprise, whereas enterprise templates are bound to a specific enterprise. | metadata_template | | metadata_template.template_key | The name of your metadata template. | invoice | | items.id | Box file ID of the document. The ID must reference an actual file with an extension. | 1233039227512 | | items.type | The type of the supplied input. | file | | items.content | The content of the item, often the text representation. | This article is about Box AI. | | fields.type | The type of the field. It include but is not limited to string, float, date, enum, and multiSelect. | string | | fields.description | A description of the field. | The person's name. | | fields.displayName | The display name of the field. | Name | | fields.key | A unique identifier for the field. | name | | fields.options | A list of options for this field. This is most often used in combination with the enum and multiSelect field types. | [{"key":"First Name"},{"key":"Last Name"}] | | fields.options.key | A unique identifier for the field. | First Name | | fields.prompt | Additional context about the key (identifier) that may include how to find and format it. | Name is the first and last name from the email address | | ai_agent | The AI agent used to override the default agent configuration. This parameter allows you to, for example, replace the default LLM with a custom one using the model parameter, tweak the base prompt to allow for a more customized user experience, or change an LLM parameter, such as temperature, to make the results more or less creative. Before you use the ai_agent parameter, you can get the default configuration using the GET 2.0/ai_agent_default request. For specific use cases, see the AI model overrides tutorial. | | ## Use cases This example shows you how to extract metadata from a sample invoice in a structured way. Let's assume you want to extract the vendor name, invoice number, and a few more details. ### Create the request To get the response from Box AI, call `POST /2.0/ai/extract_structured` endpoint with the following parameters: - `items.type` and `items.id` to specify the file to extract the data from. - `fields` to specify the data that you want to extract from the given file. - `metadata_template` to supply an already existing metadata template. You can use either `fields` or `metadata_template` to specify your structure, but not both. ### Use fields parameter The `fields` parameter allows you to specify the data you want to extract. Each `fields` object has a subset of parameters you can use to add more information about the searched data. For example, you can add the field type, description, or even a prompt with some additional context. ``` curl --location 'https://api.box.com/2.0/ai/extract_structured' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <ACCESS_TOKEN>'' \ --data '{ "items": [ { "id": "1517628697289", "type": "file" } ], "fields": [ { "key": "document_type", "type": "enum", "prompt": "what type of document is this?", "options": [ { "key": "Invoice" }, { "key": "Purchase Order" }, { "key": "Unknown" } ] }, { "key": "document_date", "type": "date" }, { "key": "vendor", "description": "The name of the entity.", "prompt": "Which vendor is sending this document.", "type": "string" }, { "key": "document_total", "type": "float" } ] }' ``` The response lists the specified fields and their values: ``` { "document_date": "2024-02-13", "vendor": "Quasar Innovations", "document_total": $1050, "document_type": "Purchase Order" } ``` ### Use metadata template If you prefer to use a metadata template, you can provide its `template_key`, `type`, and `scope`. ``` curl --location 'https://api.box.com/2.0/ai/extract_structured' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <ACCESS_TOKEN>' \ --data '{ "items": [ { "id": "1517628697289", "type": "file" } ], "metadata_template": { "template_key": "rbInvoicePO", "type": "metadata_template", "scope": "enterprise_1134207681" } }' ``` The response lists the fields included in the metadata template and their values: ``` { "documentDate": "February 13, 2024", "total": "$1050", "documentType": "Purchase Order", "vendor": "Quasar Innovations", "purchaseOrderNumber": "003" } ``` **Reference:** https://developer.box.com/guides/box-ai/ai-tutorials/extract-metadata-structured/ --- ## Untitled *Type: guide | Category: Box AI * Supported AI models Box supports a variety of AI models, categorized along two dimensions: access level and capability tier. Access Levels… # Supported AI models Box supports a variety of AI models, categorized along two dimensions: access level and capability tier. ## Access Levels ### Core Models These models are built into Box AI and available by default for all customers. No configuration is required. ### Customer-Enabled Models These models require activation by Box admins in the Admin Console or a request to Box to enable them. Some models may be subject to additional terms or pricing. ## Capability Tiers ### Standard Models Designed for high-speed, cost-efficient tasks like basic summarization, Q&A, and structured data extraction from shorter or simpler documents. Ideal for high-volume, low-complexity use cases. ### Premium Models Offer more advanced reasoning, larger context windows, and better performance on long-form, complex, or domain-specific content. Suitable for sophisticated tasks like multi-step reasoning, understanding large taxonomies, and analyzing lengthy or unstructured documents. A model can be both customer-enabled and premium, or core and standard. In other words, access level and capability tiers are independent categorizations (for example, models can be either capability tier regardless of access level). The two categorizations are complementary. ## Using models How to use the supported AI models: - get the [default AI agent configuration](e://get_ai_agent_default), - override the AI agent configuration used in [`POST 2.0/ai/ask`](e://post_ai_ask), [`POST 2.0/ai/text_gen`](e://post_ai_text_gen), [`POST 2.0/ai/extract`](e://post_ai_extract), [`POST 2.0/ai/extract_structured`](e://post_ai_extract_structured) endpoints. When using the `model` parameter your API calls, use the **API Name** visible on each tile and model card. For example, to get the AI agent configuration for a specific model, use the [model](e://get-ai-agent-default#param-model) parameter and provide the `azure__openai__gpt_4o_mini` API name. Make sure you use **two underscores** after the provider name. The list may change depending on the model availability. Models offered in **Beta** mode have not been fully performance-tested at scale and are made available on an as-is basis. You may experience variability in model/output quality, availability, and accuracy. ## Core Box AI Models Box AI is powered by the following AI models. These models are integrated with Box AI to facilitate various use cases while adhering to enterprise grade standards. Below, you’ll find information about each model, including its capabilities, intended applications, and applicable usage guidelines. A multimodal model designed to handle lightweight tasks. Default for Box AI for Box Hubs Default for Box AI for Docs Default for Box AI for Box Notes Q&A Chat Available Standard A multimodal model, highly efficient in handling complex, multi-step tasks. Chat Available Premium A multimodal model designed to handle lightweight tasks. Chat Available Standard A multimodal model, highly efficient in handling complex, multi-step tasks. Chat Preview Available Premium A most capable 2nd generation text embedding model. Skilled in text search, code search, and sentence similarity. Embeddings Available Standard Gemini multimodal model with a 1 million token context window and advanced reasoning capabilities. Chat Available Premium Gemini multimodal model designed for optimal for high-volume, high-frequency tasks at scale. Chat Available Standard Gemini multimodal model designed to handle lightweight tasks. Default for Box AI Extract Chat Available Standard A model tailored for various language tasks, including creative writing and conversational AI. Chat Available Standard A model designed for advanced language tasks, focusing on comprehension and context handling. Chat Available Premium A model designed to enhance language understanding and generation tasks. Chat Available Premium A model designed to enhance language understanding and generation tasks Chat Available Premium A model that brings frontier performance to everyday use cases. Chat Available Premium A model that excels at coding and complex problem-solving, powering frontier agent products. Chat Available Premium A model capable of advanced language processing, handling extensive contexts, making it suitable for complex tasks. Chat Available Standard A model built for document-level understanding, interpretation of charts and graphs, and captioning of images. Chat Available Standard A natively multimodal AI model that enables text and multimodal experiences. Chat Available Standard ## Customer-enabled models Certain Box AI customers may enable additional AI models upon their request and/or otherwise made available to them through their admin console. Use of these models may be subject to additional terms. By selecting a customer-enabled model, customer acknowledges that their data may be processed by additional [subprocessors](https://www.box.com/legal/subprocessors) of their choice. A model that excels at enterprise use cases like data extraction, coding, and text summarization. Chat Beta Premium A lightweight model that is great for logic-based tasks that do not require deep domain knowledge. Chat Beta Premium A multimodal model, highly efficient in handling complex, multi-step tasks. Beta Premium **Reference:** https://developer.box.com/guides/box-ai/ai-models/ --- ## Untitled *Type: guide | Category: Box AI * Extract metadata from file (freeform) Box AI API allows you to query a document or image and extract metadata based on a provided prompt… # Extract metadata from file (freeform) Box AI API allows you to query a document or image and extract metadata based on a provided prompt. **Freeform** means that the prompt can include a stringified version of formats such as JSON or XML, or even plain text. ## Before you start Make sure you followed the steps listed in [getting started with Box AI](g://box-ai/ai-tutorials/prerequisites) to create a platform app and authenticate. ## Send a request To send a request, use the `POST /2.0/ai/extract` endpoint. ### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. The `items` array can have exactly one element. | Parameter | Description | Example | | --- | --- | --- | | prompt | The request for Box AI to generate or refine the text. The prompt's length cannot exceed 10000 characters. | Create a meeting agenda for a weekly sales meeting. | | items.id | Box file ID of the document. The ID must reference an actual file with an extension. | 1233039227512 | | items.type | The type of the supplied input. | file | | items.content | The content of the item, often the text representation. | This article is about Box AI. | | ai_agent | The AI agent used to override the default agent configuration. This parameter allows you to, for example, replace the default LLM with a custom one using the model parameter, tweak the base prompt to allow for a more customized user experience, or change an LLM parameter, such as temperature, to make the results more or less creative. Before you use the ai_agent parameter, you can get the default configuration using the GET 2.0/ai_agent_default request. For specific use cases, see the AI model overrides tutorial. | | ## Use cases This example shows you how to extract metadata from a sample invoice. ### Create the request To get the response from Box AI, call `POST /2.0/ai/extract` endpoint with the following parameters: - `prompt` that can be a query, or a structured or unstructured list of fields to extract. - `type` and `id` of the file to extract the data from. ### Create the prompt Depending on the use case and the level of detail, you can construct various prompts. #### Use plain text Because this endpoint allows freeform prompts, you can use plain text to get the information. ``` curl --location 'https://api.box.com/2.0/ai/extract' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <ACCESS_TOKEN>' \ --data '{ "prompt": "find the document type (invoice or po), vendor, total, and po number", "items": [ { "type": "file", "id": "1443721424754" } ] }' ``` In such a case, the response will be based on the keywords included in the text: ``` { "answer": "{\"Document Type\": \"Invoice\", \"Vendor\": \"Quasar Innovations\", \"Total\": \"$1,050\", \"PO Number\": \"003\"}", "created_at": "2024-05-31T10:30:51.223-07:00", "completion_reason": "done" } ``` #### Use specific terms If you don't want to write the entire sentence, the prompt can consist of terms that you expect to find in an invoice: ``` curl --location 'https://api.box.com/2.0/ai/extract' \ --header 'Content-Type: application/json' \ --header 'Authorization: <ACCESS_TOKEN>' \ --data '{ "prompt": "{\"vendor\",\"total\",\"doctype\",\"date\",\"PO\"}", "items": [ { "type": "file", "id": "1443721424754" } ] }' ``` Using this approach results in a list of terms provided in the request and their values: ``` { "answer": "{\"vendor\": \"Quasar Innovations\", \"total\": \"$1,050\", \"doctype\": \"Invoice\", \"PO\": \"003\"}", "created_at": "2024-05-31T10:28:51.906-07:00", "completion_reason": "done" } ``` #### Use key-value pairs The prompt can also be a list of key-value pairs that helps Box AI to come up with the metadata structure. This approach requires listing the key-value pairs within a `fields` array. ``` curl --location 'https://api.box.com/2.0/ai/extract' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <ACCESS_TOKEN>' \ --data '{ "prompt": "{\"fields\": [{\"key\":\"vendor\",\"displayName\":\"Vendor\",\"type\":\"string\",\"description\":\ "Vendorname\"},{\"key\":\"documentType\",\"displayName\":\"Type\",\"type\":\"string\",\"description\":\"\"}]}", "items": [ { "type": "file", "id": "1443721424754" } ] }' ``` The response includes the `fields` present in the file, along with their values: ``` { "answer": "{\"vendor\": \"Quasar Innovations\", \"documentType\": \"Invoice\"}", "created_at": "2024-05-31T10:15:38.17-07:00", "completion_reason": "done" } ``` **Reference:** https://developer.box.com/guides/box-ai/ai-tutorials/extract-metadata/ --- ## Untitled *Type: guide | Category: Box AI * Generate text with Box AI Box AI API is available to all Enterprise Plus and Enterprise Advanced customers. You can use Box AI to generate… # Generate text with Box AI Box AI API is available to all Enterprise Plus and Enterprise Advanced customers. You can use Box AI to generate text based on provided content. For example, you can ask Box AI to generate a template based on the content you read or create in Box Notes. Then you can embed the generated text directly into your document. ## Before you start Make sure you followed the steps listed in [getting started with Box AI](g://box-ai/ai-tutorials/prerequisites) to create a platform app and authenticate. ## Send a request To send a request, use the `POST /2.0/ai/text_gen` endpoint. ### Parameters To make a call, you must pass the following parameters. Mandatory parameters are in **bold**. **Note**: The `items` array can have exactly one element. | Parameter | Description | Example | | --- | --- | --- | | prompt | The request for Box AI to generate or refine the text. The prompt's length cannot exceed 10000 characters. | Create a meeting agenda for a weekly sales meeting. | | items.id | Box file ID of the document. | 1233039227512 | | items.type | The type of the supplied input. | file | | items.content | The content of the item, often the text representation. | This article is about Box AI. | | dialogue_history.prompt | The prompt previously provided by the client and answered by the Large Language Model (LLM). | Make my email about public APIs sound more professional | | dialogue_history.answer | The answer previously provided by the LLM. | Here is a draft of your professional email about public APIs. | | dialogue_history.created_at | The ISO date formatted timestamp of when the previous answer to the prompt was created. | 2012-12-12T10:53:43-08:00 | | ai_agent | The AI agent used to override the default agent configuration. This parameter allows you to, for example, replace the default LLM with a custom one using the model parameter, tweak the base prompt to allow for a more customized user experience, or change an LLM parameter, such as temperature, to make the results more or less creative. Before you use the ai_agent parameter, you can get the default configuration using the GET 2.0/ai_agent_default request. For specific use cases, see the AI model overrides tutorial | | ## Use cases Generate text based on the provided file content and a prompt. ``` curl -i -L POST "https://api.box.com/2.0/ai/text_gen" \ -H "content-type: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "items": [ { "id": "12345678", "type": "file" } ], "prompt": "Create a short blog post that provides information on Box AI for Documents and focuses on best practices for asking questions. You can add emoticons, but not too many." }' ``` The result will be as follows: ``` { "answer": "📝 **Box AI for Documents: Best Practices for Asking Questions** 🤔\n\n---\n\nWelcome to our blog post on Box AI for Documents! 🎉 Today, we're going to dive into some best practices when it comes to asking questions within this innovative platform.\n\n1. **Be Clear and Concise**: When formulating a question in Box Notes, make sure your query is clear and to the point. This helps Box AI understand exactly what you're looking for.\n\n2. **Provide Context**: Giving context around your question can significantly improve the accuracy of the response generated by Box AI. Include relevant details or background information.\n\n3. **Use Keywords**: Utilize keywords related to your query within the question itself. This can help Box AI better identify the main topic of your inquiry.\n\n4. **Avoid Ambiguity**: Try to avoid vague or ambiguous questions that could lead to misunderstandings. The more precise you are, the better Box AI can assist you.\n\n5. **Review Suggestions Carefully**: After receiving suggestions from Box AI, take the time to review them carefully before incorporating them into your document. Ensure they align with your intended message.\n\nBy following these best practices, you can maximize the effectiveness of Box AI for Documents and streamline your workflow like never before! 💼✨\n\nStay tuned for more tips and tricks on leveraging technology for enhanced productivity! 👩‍💻🚀", "created_at": "2024-11-04T02:46:23.459-08:00", "completion_reason": "done" } ``` **Reference:** https://developer.box.com/guides/box-ai/ai-tutorials/generate-text/ --- ## Untitled *Type: guide | Category: Box AI * Get started with Box AI To implement Box AI API in your solutions, you need to make sure you have access to the functionality. You will also… # Get started with Box AI To implement Box AI API in your solutions, you need to make sure you have access to the functionality. You will also need a platform application with enabled Box AI scope, and a developer token to authenticate your calls. To use Box AI API, make sure it is enabled by an admin in the Admin Console. If you want to use the Box AI APIs in your sandbox, request access from the Box AI team using [this form](https://forms.gle/Nsh3TwM3W8qg4U35A). ## Create a platform application First you need to create a platform application you will use to make calls. To create an application, follow the guide on [creating platform apps](g://applications/app-types/platform-apps). ## Enable Box AI API access To interact with Box AI API, you need the `ai.readwrite` [scope](g://api-calls/permissions-and-errors/scopes) added for your application. Before you add the scope, make sure that the Box Admin has granted you the access to Box AI API. If you can't see the **Manage AI** option in your app configuration settings, contact your admin. To add a scope: Open your application in Developer Console. Go to **Configuration** > **Required Access Scopes** > **Content Actions** Select the **Manage AI** scope. Box Platform will automatically include the scope when making the call. If you are added as an collaborator for a given app, but do not have Box AI API access, you will see the **Manage AI** scope checked and grayed out. This means the app owner has the AI scope enabled but you cannot change this setting. Submit your app for [authorization or enablement](g://authorization). If you want to enable Box AI API for an existing application, you must [re-authorize](g://authorization/custom-app-approval#re-authorization-on-changes) it. ## Generate a developer token You need a developer token to authenticate your app when sending requests. To generate a token: 1. Go to **Developer Console** > **My Platform Apps**. 2. Click the **Options menu** button (…) on the right. 3. Select **Generate Developer Token**. The token will be automatically generated and saved to clipboard. You can also open your app, go to **Configuration** > **Developer Token** and generate the token. A developer token is only valid for one hour. For additional details, see [developer token](g://authentication/tokens/developer-tokens). After you generate the token, you can use it in cURL or other clients, such as [Postman](g://tooling/postman), to make calls. **Reference:** https://developer.box.com/guides/box-ai/ai-tutorials/prerequisites/ --- ## Untitled *Type: guide | Category: Box AI * Box AI tutorials The listed tutorials provide you with an overview and use cases for Q&A and text generation, metadata extraction, and AI… # Box AI tutorials The listed tutorials provide you with an overview and use cases for Q&A and text generation, metadata extraction, and AI model configuration overrides. **Reference:** https://developer.box.com/guides/box-ai/ai-tutorials/ --- ## Untitled *Type: guide | Category: Box MCP Server * Remote Box MCP Server The remote Box MCP Server allows third party AI systems to securely connect and interact with your content in Box. Box… # Remote Box MCP Server The remote Box MCP Server allows third party AI systems to securely connect and interact with your content in Box. Box MCP Server offered subject to Box’s Main Beta Agreement, meaning the available capabilities may change at any time. Box MCP Server is available for customers with Enterprise Plus or Enterprise Advanced plans. ## Access and manage predefined Box MCP Servers 1. Click **Integrations** in the sidebar of Box Admin Console. 2. Click **Box Integrations & Clients** in the Integrations window. 3. Scroll down to **Individual Integration Controls**. 4. Search for predefined Box MCP Server, for example the **Box MCP Server for Copilot Studio (Beta)**. 5. Hover on the chosen integration, then click **Configure**. 6. Click Save. ## Create an unlisted Box MCP Server To create a new, unlisted Box MCP Server: 1. Click Integrations in the sidebar of Box Admin Console. 2. Scroll down to **Individual Integration Controls** in the Box Integrations & Clients tab. 3. Search for **Box MCP Server**. 4. Hover on the **Box MCP Server** application, then click **Configure**. 5. In the **Additional Configuration** section, click on **+ Add Integration Credentials**. 6. Enter the Redirect URI provided by the external MCP Client. 7. Copy the generated Client ID and Client Secret. 8. Under Scopes, ensure that *Manage AI Requests* is selected. ## Add Box MCP Server to MCP clients To connect to Box from the AI Agent platform, you need to: - Add an endpoint URL: `https://mcp.box.com` - Pass an MCP name: `box-remote-mcp` - Provide an `authorization_token` Exact steps may vary depending on the AI platform. Refer to your platform’s documentation for client-side setup instructions. Check this sample code for reference: ``` response = await client.beta.messages.create( model="claude-3-opus-20240229", # Or your preferred model max_tokens=4096, messages=conversation_history, mcp_servers=[ { "type": "url", "url": "https://mcp.box.com", "name": "box-remote-mcp", "authorization_token": BEARER_TOKEN, } ], betas=["mcp-client-2025-04-04"] ) ``` ### Anthropic's Messages API Connect the remote Box MCP Server with Anthropic's Messages API (beta). Clone [this sample chat bot project](https://github.com/box-community/remote-box-mcp-anthropic) to get started quickly. It allows you to have a conversation with an Anthropic model, which has access to tools provided by the Box remote MCP server. The chatbot runs in a terminal, maintains conversation history for context-aware responses, and uses `asyncio` for asynchronous operation. ### Copilot Studio To add an MCP server, follow the instructions provided by the Copilot Studio side. Detailed steps and guidance are available in the official Microsoft documentation: [Add an MCP Server in Copilot Studio](https://learn.microsoft.com/en-us/microsoft-copilot-studio/agent-extend-action-mcp#add-tools-from-an-existing-mcp-connector-to-an-agent). ### Azure API Center To add an MCP server in Azure API Center's Enterprise Registry, follow the instructions provided by Azure. Detailed steps and guidance are available in the official Microsoft documentation: [Add an MCP Server in Azure API Center's Enterprise Registry](https://learn.microsoft.com/en-us/azure/api-center/register-discover-mcp-server). ### Using Box AI Features with the MCP Server When you use Box AI in third party applications, you can achieve the best experience and highest quality results by accessing the applications through the Box MCP Server. This ensures full functionality, improved performance, and a seamless user experience. ## Available tools Remote Box MCP Server includes several tools you can use: | Tool | Description | | --- | --- | | box-remote-mcp_who_am_i | Returns detailed information about the currently authenticated Box user. | | box-remote-mcp_search_folders_by_name | Searches for folders within Box by name using keyword matching. | | box-remote-mcp_list_folder_content_by_folder_id | Lists files, folders, and web links in a folder. | | box-remote-mcp_search_files_keyword | Searches for files using keywords. Supports metadata filters, file extension filtering, and field selection. | | box-remote-mcp_search_files_metadata | Searches for files using SQL-like metadata queries. Supports complex filtering with parameters, field selection, and folder scoping. | | box-remote-mcp_ai_qa_single_file | Asks a question to a single file using Box AI. | | box-remote-mcp_ai_qa_multi_file | Asks a question to multiple files using Box AI. | | box-remote-mcp_ai_qa_hub | Asks a question to a Box Hub using Box AI. | | box-remote-mcp_ai_extract_freeform | Extracts metadata from files using Box AI in freeform format without requiring predefined template structures. | | box-remote-mcp_ai_extract_structured | Extracts structured metadata from files using Box AI based on either custom fields definition or an existing metadata template. | **Reference:** https://developer.box.com/guides/box-mcp/remote/ --- ## Untitled *Type: guide | Category: Box MCP Server * Self-hosted Box MCP Server The Self-hosted Box MCP Server is a Python project that integrates with the Box API to perform various operations… # Self-hosted Box MCP Server The [Self-hosted Box MCP Server](https://github.com/box-community/mcp-server-box.git) is a Python project that integrates with the Box API to perform various operations such as file search, text extraction, AI-based querying, and data extraction. It leverages the Box Python Next Gen SDK library and provides a set of tools to interact with Box files and folders. ## Installation ### Prerequisites - Python 3.13 or higher - Box Platform app credentials (Client ID, Client Secret) Follow the steps from this section to set up the self-hosted Box MCP Server. 1. Clone the repository: ``` git clone https://github.com/box-community/mcp-server-box.git cd mcp-server-box ``` 1. Install `uv` if it's not installed on your machine: ``` curl -LsSf https://astral.sh/uv/install.sh | sh ``` ``` powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` Restart your terminal afterwards to ensure that the `uv` command gets picked up. 1. Create and set up our project: ``` # Create virtual environment and activate it uv venv source .venv/bin/activate # Lock the dependencies uv lock ``` ``` # Create virtual environment and activate it uv venv .venv\Scripts\activate # Lock the dependencies uv lock ``` 1. Create a `.env` file in the root directory and fill your Box Platform app credentials: ``` BOX_CLIENT_ID=your_client_id BOX_CLIENT_SECRET=your_client_secret ``` You can also watch a video tutorial and see example usage of Box MCP tools. ## Running Box MCP Server locally To start the Box MCP Server, run the following command: ``` uv --directory /Users/USER_NAME/PATH_TO_PROJECT/mcp-server-box run src/mcp_server_box.py ``` Update the path so it reflects your local setup. ### Use Cursor as the Box MCP client Prerequisites: - Download [Cursor desktop app](https://www.cursor.com/) Follow these instructions to start using Box MCP Sever with Cursor: 1. Open the Cursor app. 2. Click the cog icon to open settings. 3. Select `MCP` within the Cursor Settings tab. 4. Click the `Add new global MCP server` button. This opens the `mcp.json` file. 5. Update the values with your local setup and paste the following JSON: ``` { "mcpServers": { "box": { "command": "uv", "args": [ "--directory", "/Users/USER_NAME/PATH_TO_PROJECT/mcp-server-box", "run", "src/mcp_server_box.py" ] } } } ``` 1. Save and close the `mcp.json` file. 2. Restart Cursor if necessary. 3. Use the `box_authorize_app_tool` tool to start using Box MCP. ### Use Claude for Desktop as the Box MCP client Prerequisites: - Download [Claude for Desktop](https://claude.ai/download) client - Optionally, set up [`code`](https://code.visualstudio.com/docs/setup/mac#_configure-the-path-with-vs-code) command for VS Code Follow these steps to set up Box MCP in Claude for Desktop: 1. Edit your `claude_desktop_config.json`. You can run this command in your terminal: ``` code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` Alternatively, in the main Claude navigation choose `Settings`. Select the Developers tab and click `Edit Config`. This opens a folder window containing `claude_desktop_config.json`. 1. Add the configuration: ``` { "mcpServers": { "mcp-server-box": { "command": "uv", "args": [ "--directory", "/Users/Users/USER_NAME/PATH_TO_PROJECT/mcp-server-box", "run", "src/mcp_server_box.py" ] } } } ``` 1. Restart Claude for Desktop. 2. Authenticate the Box MCP Server using `box_authorize_app_tool` tool. ## Available tools ### Authentication and user tools | Tool | Description | Parameters | Returns | | --- | --- | --- | --- | | box_who_am_i | Gets the current user information and checks the connection status. | None | User information string. | | box_authorize_app_tool | Starts the Box application authorization process. | None | Authorization status message. | ### Search and navigation tools | Tool | Description | Parameters | Returns | | --- | --- | --- | --- | | box_search_tool | Search for files in Box | - query (str): Search query. - file_extensions (List[str], optional): Filter by extensions. - where_to_look_for_query (List[str], optional): Locations to search. - ancestor_folder_ids (List[str], optional): Folder IDs to limit the search. | Newline-separated list of file names and IDs | | box_search_folder_by_name | Locate a folder by name | folder_name (str): Name of the folder | Folder ID and information | | box_list_folder_content_by_folder_id | List folder contents | folder_id (str): ID of the folder. is_recursive (bool): Whether to list recursively. | Folder content in JSON format | ### File operations | Tool | Description | Parameters | Returns | | --- | --- | --- | --- | | box_read_tool | Read the text content of a Box file | - file_id (str): ID of the file to read. | File content | | box_upload_file_from_path_tool | Upload a file from local path | file_path (str): Local file path. folder_id (str, optional): Destination folder ID. new_file_name (str, optional): New file name. | File details or error message | | box_upload_file_from_content_tool | Upload content as a file | content (str|bytes): Content to upload. file_name (str): File name. folder_id (str, optional): Destination folder ID. is_base64 (bool, optional): If content is base64 encoded. | Upload success message | | box_download_file_tool | Download a file from Box | file_id (str): File ID. save_file (bool, optional): Whether to save locally. save_path (str, optional): Local save path. | File content or save confirmation | ### Folder Management | Tool | Description | Parameters | Returns | | --- | --- | --- | --- | | box_manage_folder_tool | Create, update, or delete folders | - action (str): create, delete, or update. - folder_id (str, optional): Folder ID. - name (str, optional): Folder name. - parent_id (str, optional): Parent folder ID. - description (str, optional): Folder description. - recursive (bool, optional): For recursive delete. Status message with folder details ### Box AI tools Tool | Description | | box_ask_ai_tool | Ask Box AI about a file | file_id (str): File ID. prompt (str): Question for the AI. | AI response | | box_ask_ai_tool_multi_file | Query Box AI using multiple files | file_ids (List[str]): List of file IDs. prompt (str): Instruction for AI. | AI-generated answer | | box_hubs_ask_ai_tool | Ask Box AI about a hub | hubs_id (str): ID of the hub. prompt (str): Question for the AI. | AI response | | box_ai_extract_data | Extract data from a file using AI | file_id (str): File ID. fields (str): Fields to extract. | Extracted data in JSON format | ### Box Doc Gen tools | Tool | Description | Parameters | Returns | | --- | --- | --- | --- | | box_docgen_create_batch_tool | Generate documents using a template | - file_id (str): Template file ID. - destination_folder_id (str): Output folder ID. - user_input_file_path (str): JSON input data path. - output_type (str, optional): Output format. | Batch generation result | | box_docgen_get_job_tool | Fetch a Doc Gen job by ID | job_id (str): Job identifier | Job details in JSON | | box_docgen_list_jobs_tool | List all Doc Gen jobs | - marker (str, optional): Pagination marker. - limit (int, optional): Max jobs to return. | List of jobs in JSON | | box_docgen_list_jobs_by_batch_tool | List jobs in a specific batch | - batch_id (str): Batch identifier. - marker (str, optional): Pagination marker. - limit (int, optional): Max jobs to return. | Batch jobs details | | box_docgen_template_create_tool | Mark a file as a template | file_id (str): File ID to mark | Template details | | box_docgen_template_list_tool | List all available templates | - marker (str, optional): Pagination marker. - limit (int, optional): Max templates to list. | List of templates | | box_docgen_template_delete_tool | Remove template marking | template_id (str): Template identifier | Deletion confirmation | | box_docgen_template_get_by_id_tool | Get template details | template_id (str): Template identifier | Template details | | box_docgen_template_list_tags_tool | List template tags | - template_id (str): Template ID. - template_version_id (str, optional): Version ID. - marker (str, optional): Pagination marker. - limit (int, optional): Max tags to return. | List of tags | | box_docgen_template_list_jobs_tool | List jobs using a template | - template_id (str): Template identifier. - marker (str, optional): Pagination marker. - limit (int, optional): Max jobs to list. | Job details | ### Box Metadata tools | Tool | Description | Parameters | Returns | | --- | --- | --- | --- | | box_metadata_template_get_by_key_tool | Retrieves a metadata template by its key. | template_name (str): The key of the metadata template to retrieve. | The metadata template associated with the provided key. | | box_metadata_template_get_by_name_tool | Retrieve a metadata template by its name. | template_name (str): The name of the metadata template to retrieve. | The metadata template associated with the provided name. | ## Troubleshooting In case of an `Error: spawn uv ENOENT` on MacOS when running the MCP server with Claude Desktop, you can: - Remove `uv` and reinstall it with Homebrew: `brew install uv`. - Provide the full path to the `uv` executable in your configuration: ``` /Users/USER_NAME/.local/bin/uv --directory /Users/USER_NAME/local/mcp-server-box run src/mcp_server_box.py ``` In case of additional issues related to setup, post your question on our [Developer Community forum](https://community.box.com/ai-developers-23). **Reference:** https://developer.box.com/guides/box-mcp/self-hosted/ --- ## Untitled *Type: guide | Category: CLI * Box CLI with JWT Authentication Previously, our Box CLI Quick Start Guide, followed the JWT or server authentication application setup flow… # Box CLI with JWT Authentication Previously, our [Box CLI Quick Start Guide](g://cli/quick-start), followed the JWT or server authentication application setup flow. Since we released a new OAuth 2.0 version of the Box CLI, we updated it to use the new feature. We migrated the original JWT setup instructions here, in case you would still like to use the server authentication application type. ## Setup a JWT application The first step to using the CLI with server authentication is creating a Box application in the [Developer Console](https://account.box.com/developers/console), which the CLI can use behind the scenes to make API calls. If you would like to associate your CLI with an existing JWT application you can skip this step. However, you will want to ensure that, at a minimum, the following scopes are set in the **Configuration** tab of your application: - Read all files and folders stored in Box - Write all files and folders stored in Box From the left-hand navigation panel on your All Files page, open the [Developer Console](https://account.box.com/developers/console). If this is your first time using the Box API and this option is not already available, you can add it to your account by clicking [here](https://account.box.com/developers/console). Click **Create Platform App** > **Platform App** > **Server Authentication (with JWT)** > name the application > **Create App** Server Authentication (with JWT) always requires Admin authorization before use. ## Configure the application This will bring you to the application’s configuration page where you need to choose its access and permissions. Again, keep in mind that because of the application’s authentication type, it will require Admin approval. At a minimum, you will need the following [scopes](g://api-calls/permissions-and-errors/scopes): - Read all files and folders stored in Box - Write all files and folders stored in Box You can choose either App Access Only or App + Enterprise Access as the [application access](g://authentication/jwt/jwt-setup/#application-access). ## Authorize the application All applications leveraging Server Authentication must be authorized in the Admin Console before making successful API calls. This is because all JWT applications have a [Service Account](page://platform/user-types/#service-account), which, based on the applications [scopes](g://api-calls/permissions-and-errors/scopes), may be able to perform Admin actions. Steps for developers and Admins can be found in our [authorization guide](g://authorization/custom-app-approval). If you would like more information on how scopes, application access, tokens, and permissions work together, please see our article on understanding [Box's security mechanisms](https://medium.com/box-developer-blog/box-api-understanding-security-9fcad7b1d72e). If configuration changes are made to this application, it will need to be reauthorized in order for the changes to take effect. You will know when an application is ready for use by visiting its Authorization tab in the [Developer Console](https://account.box.com/developers/console). The state and status must be enabled and authorized. ## Download Required Data The CLI needs a configuration file stored locally in order to make API calls. To download the configuration file, visit the **Configuration** tab in the [Developer Console](https://account.box.com/developers/console). Click **Generate a Public/Private Keypair**, which will send you through 2FA verification before automatically downloading the configuration file for your application. For more information see our [guide](g://authentication/jwt/jwt-setup/#public-and-private-key-pair). For security reasons 2FA must be enabled on your Box account to successfully generate a public/private keypair. Locate the downloaded file on your machine which has a default name in the format: `EnterpriseID_publicKeyID_config.json`. You may leave this name or choose to rename it. This guide assumes the file is renamed to `config.json`. It is critical you place the file in a location where it will not be inadvertently deleted or moved. If this occurs you will need to repeat the step 2 to reconfigure the CLI. ## CLI Installation and Configuration Installers are available for Windows and macOS. However, the raw source-code is available if you would like to build the CLI in other environments. ## Windows & macOS Installers To install the latest CLI on your machine, download the latest `.exe` for Windows or `.pkg` for macOS for the latest release. Download the latest CLI installer ## Linux & Node install Additionally, the CLI can be installed as a Node package on any platform, including Linux. For this to work you will need to have [Node JS](https://nodejs.org/) installed on your machine. ``` npm install --global @box/cli ``` ## Source Code The source code for the CLI is available via [GitHub](https://github.com/box/boxcli). ## Run configuration command You will now need to configure the CLI to point to to the configuration file downloaded in step 1. Open your terminal or command line and execute the command: `box configure:environments:add PathToConfigFileHere`, replacing `PathToConfigHere` with the path to your `config.json` file. For example: `box configure:environments:add /Users/ExampleUser/Documents/CLI/config.json` You can drag the csv file from the Finder/File Explorer to the terminal/command line window to auto-populate the path. ## Confirm configuration To confirm successful configuration, use the command `box users:get`. A successful response will provide details about the [Service Account](page://platform/user-types/#service-account) user associated with your [Access Token](g://authentication/tokens): ``` Type: user ID: ''0123456789'' Name: Box CLI - Quickstart Example Login: AutomationUser_123456_8jSo6Lqvko@boxdevedition.com Created At: '2020-01-01T09:45:01-07:00' Modified At: '2021-03-01T09:30:05-07:00' Language: en Timezone: America/Los_Angeles Space Amount: 999999999999999 Space Used: 6291500 Max Upload Size: 16106127360 Status: active Job Title: '' Phone: '' Address: example+user@box.com Avatar URL: '' Notification Email: [] ``` By default, JWT applications automatically obtain an Access Token for the Service Account. It is possible to change the default user, but this guide assumes you do not do this. ## Next Steps - You can checkout the [commands](https://github.com/box/boxcli#command-topics) page on GitHub for example code. - You can also go to the second part of the [OAuth 2.0 Quick Start](g://cli/quick-start/build-commands-help) for a tutorial on how to use the commands. **Reference:** https://developer.box.com/guides/cli/cli-docs/jwt-cli/ --- ## Untitled *Type: guide | Category: CLI * CLI guides Here you can find guides on how to use Box CLI features and capabilities. Set up and test Box CLI with JWT authentication. Set up… # CLI guides Here you can find guides on how to use Box CLI features and capabilities. - Set up and test [Box CLI with JWT authentication](g://cli/cli-docs/jwt-cli). - Set up and use [Box CLI bulk commands](g://cli/cli-docs/bulk-commands). **Reference:** https://developer.box.com/guides/cli/cli-docs/ --- ## Untitled *Type: guide | Category: CLI * CLI bulk commands The Box CLI bulk commands help you to automate repetitive tasks. By adding a --bulk-file-path flag to your command, you… # CLI bulk commands The Box CLI bulk commands help you to automate repetitive tasks. By adding a `--bulk-file-path` flag to your command, you are able to perform actions for many items at once. For example, this command creates several folders using a CSV file specifying folder `Name`, `Description`, and the `ParentId` of the parent folder: ``` box folders:create --bulk-file-path <PATH_TO_CSV>/folders-create.csv ``` ## CSV templates Predefined CSV templates help you to structure the data you want to manage in bulk. Templates reside in the [`Bulk actions`](https://github.com/box/boxcli/tree/main/docs/Bulk%20actions) directory, grouped into folders. The table below lists the currently available templates. | Templates | Description | | --- | --- | | box collaborations | Create, delete, and update collaborations. | | box files | Download, update, and upload files. | | box folders | Create and update folders, add metadata to folders. | | box groups | Create groups and add memberships. | | box metadata-templates | Create metadata templates and metadata cascade policies on folders. | | box shared-links | Delete shared links. | | box users | Create and update users, move one user's content to another user. | | box webhooks | Delete webhooks. | ## Prerequisites To use bulk commands, you will need a Box application with OAuth 2.0 authentication. If you don't have one, go to your [Developer Console](https://app.box.com/developers/console), and follow the guide [Setup with OAuth 2.0](g://authentication/oauth2/oauth2-setup). ## Set up and use bulk commands Clone the `boxcli` GitHub repository or download the files from [`Bulk actions`](https://github.com/box/boxcli/tree/main/docs/Bulk%20actions) directory. ``` git clone https://github.com/box/boxcli.git ``` Adjust the `.csv` template to your needs. For example, if you want to create several folders, you can use the [`folders-create.csv`](https://github.com/box/boxcli/blob/main/docs/Bulk%20actions/folders/folders-create.csv) template as your starting point. Run the command. ``` box users:create --bulk-file-path <PATH_TO_CSV>/folders-create.csv ``` **Reference:** https://developer.box.com/guides/cli/cli-docs/bulk-commands/ --- ## Untitled *Type: quick-start | Category: CLI * Building Commands and Help Feature A full list of CLI commands and usage information can be found in the GitHub repository. Only Service… # Building Commands and Help Feature A full list of CLI commands and usage information can be found in the [GitHub repository](https://github.com/box/boxcli#command-topics-1). Only Service Accounts and Admins are able to use some commands. If your user is not authorized with the necessary scopes or you configured your CLI to obtain a default token for another user, calls may fail. Add `-v` or `--verbose` to your command for verbose error logging. If you do not see a command for an endpoint you need, you can build a [custom request](https://github.com/box/boxcli/blob/master/docs/request.md). Use repository documentation in conjunction with reference documentation to see information the help command does not provide. This includes restrictions, token permission requirements, fields, etc. ## First: Reset browser storage Now that you've imported the Box API credentials into the CLI you should take a moment to remove these credentials from your browser's storage. Clear credentials Removing your API credentials from the browser storage ensures that no other script can read your **Client ID** or **Client Secret** ## Creating a folder with help Every CLI command begins with `box`. Add the option `--help` to any command for help building it. For example, executing `box --help` will bring you to a list of all possible object commands. Options are discussed more in [step 4](g://cli/quick-start/options-and-bulk-commands/#options). Then, for example, use the folder object and execute the command `box folders --help`. This provides a list of all eligible actions for this object. Discover the required arguments for creating a folder: `box folders:create --help` Execute the command `box folders:create 0 "My CLI Folder"` and note the folder ID returned in the response. The root level of the folder tree, the All Files page, is always represented by folder ID 0. Log into **your** Box account. Can you see this folder in your folder tree? If you set up the Box CLI using JWT authentication, you will not see the folder in your Box account. The folder will live in the service account of the application that was created after application approval. ## Summary - You used the **help** feature to create a folder I created my first folder **Reference:** https://developer.box.com/guides/cli/quick-start/build-commands-help/ --- ## Untitled *Type: quick-start | Category: CLI * Use Box CLI with OAuth 2.0 The Box CLI is a user-friendly command line tool which allows both technical and non-technical users to leverage… # Use Box CLI with OAuth 2.0 The Box CLI is a user-friendly command line tool which allows both technical and non-technical users to leverage the Box API to perform routine or bulk actions. There is no need to write any code, as these actions are executed through a set of [commands](https://github.com/box/boxcli#command-topics). ## Overview This guide will take you through the following steps. 1. [Create and configure](g://cli/quick-start/create-oauth-app) a Box application 2. [Install and configure](g://cli/quick-start/install-and-configure) the CLI 3. [Run commands](g://cli/quick-start/build-commands-help) with the CLI 4. Use [options and bulk commands](g://cli/quick-start/options-and-bulk-commands) 5. Explore automation using [Powershell scripts with the CLI](g://cli/quick-start/powershell-script-templates) 6. [Next steps](g://cli/quick-start/next-steps) I am ready to get started **Reference:** https://developer.box.com/guides/cli/quick-start/ --- ## Untitled *Type: quick-start | Category: CLI * Configure a Box App To use the Box CLI you will need to create a Box App. A Box App is an application that can be used for making API calls… # Configure a Box App To use the **Box CLI** you will need to create a **Box App**. A Box App is an application that can be used for making API calls. When using the Box CLI you can choose to either set up your own Box App or use our preconfigured one. The key benefit of setting up your own Box App is that you won't need to go through login every hour, but it does require a few extra steps to set up. ## Select a Box App to use # Create new Box App We can set up a Box App for you right here from the documentation. With a few clicks you will be ready to go! # Use existing Box App If you've already created a Box App before that you want to use, then we can use the credentials for that application. # Create a Box App To use your own **Box App** you will need to create a new Box App in the **Box Developer Console**. Click the button below and we will set it up for you. At the end you will have a **Client ID** and **Client Secret**. Create an app We will use these credentials to authenticate the Box CLI in the next step. # Use existing Box App If you have already created a Box App before you can use that as well. We require a few settings to be set for this to work. 1. Go to the [Developer Console](https://cloud.app.box.com/developers/console) 2. Select your application 3. Go to the application’s **Configuration** section 4. Make sure your application uses **Standard OAuth 2.0** as the authentication method 5. Scroll down to the **OAuth 2.0 redirect URI** configuration and set the **Redirect URI** to the value `http://localhost:3000/callback`. 6. Scroll down to the **Application Scopes** section to select your desired [permissions](g://api-calls/permissions-and-errors/scopes). **Your application must have at least one or more** **of the following scopes:** read all files and folders stored in Box, read and write all files and folders in Box. 7. At the top of the page click the button to **Save Changes** Next, copy the values for the Client ID and Client Secret into these 2 fields. Client ID Client Secret We will use these credentials to authenticate the Box CLI in the next step. # Security notice Your API credentials are now stored in the browser cache. We highly recommend clearing out this storage by clicking the **Reset** button later in this guide. ## Summary You either selected to create a new **Box App** - Signed up for a developer account (Optional) - Had us create a **Platform App** for you that uses **OAuth 2.0** authentication - Had us set up the **redirect URL** for the application Or you selected to use an **existing Box App** I have configured a Box app **Reference:** https://developer.box.com/guides/cli/quick-start/create-oauth-app/ --- ## Untitled *Type: quick-start | Category: CLI * CLI Installation and Configuration Installers are available for Windows and macOS. However, the raw source-code is available if you would… # CLI Installation and Configuration Installers are available for Windows and macOS. However, the raw source-code is available if you would like to build the CLI in other environments. ## Windows & macOS Installers To install the latest CLI on your machine, download the latest `.exe` for Windows or `.pkg` for macOS for the latest release. Download the latest CLI installer ## Linux & Node install Additionally, the CLI can be installed as a Node package on any platform, including Linux. For this to work you will need to have [Node JS](https://nodejs.org/) installed on your machine. ``` npm install --global @box/cli ``` ## Source Code The source code for the CLI is available via [GitHub](https://github.com/box/boxcli). ## Run configuration command You will now need to configure the CLI by logging in to your Box App. In this step, we will use the **Client ID** and **Client Secret** from the previous step to log you in and create an **Access Token** for your user. ## The reason to log in Currently you have provided us with the following information. Client ID Client Secret Open your terminal or command line and execute the command: `box login -n example_name`. Copy the Client ID and Client Secret into the terminal window when prompted. Click the **Grant access to Box** button that appears in the browser window. If successful, you will see the following success message. ## Confirm configuration To confirm successful configuration, make your first Box API call with the Box CLI by entering the command `box users:get me`. A successful response will provide details about your user account. ``` Type: user ID: ''0123456789'' Name: Aaron Levie Login: example@box.com Created At: '2020-01-01T09:45:01-07:00' Modified At: '2021-03-01T09:30:05-07:00' Language: en Timezone: America/Los_Angeles Space Amount: 999999999999999 Space Used: 6291500 Max Upload Size: 16106127360 Status: active Job Title: '' Phone: '' Address: example+user@box.com Avatar URL: '' Notification Email: [] ``` ## Summary - You installed the CLI - You configured the CLI to use the OAuth 2.0 Application created earlier - You **made your first Box CLI Box API call** confirmed the user associated with your Access Token I installed and configured the CLI # Incomplete previous step Please complete the previous step to set up the **Box App** you want to use. **Reference:** https://developer.box.com/guides/cli/quick-start/install-and-configure/ --- ## Untitled *Type: quick-start | Category: CLI * Next steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. Created and configured an… # Next steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. 1. [Created and configured](g://cli/quick-start/create-oauth-app) an OAuth 2.0 application. 2. [Installed and configured](g://cli/quick-start/install-and-configure) the CLI 3. [Built and executed CLI commands](g://cli/quick-start/build-commands-help) 4. Learned about [options and bulk commands](g://cli/quick-start/options-and-bulk-commands) 5. Explored using the CLI to [run a Powershell script](g://cli/quick-start/powershell-script-templates) To take the next step, the following resources are recommended: 1. Review all [commands](https://github.com/box/boxcli#command-topics). 2. Review [token cache](https://github.com/box/boxcli/blob/master/docs/configure.md#box-configureenvironmentsupdate-name) settings. 3. Review [autocomplete](https://github.com/box/boxcli/blob/master/docs/autocomplete.md) settings. 4. Review all of the [CLI sample scripts](g://cli/scripts). **Reference:** https://developer.box.com/guides/cli/quick-start/next-steps/ --- ## Untitled *Type: quick-start | Category: CLI * Using Options and Bulk Commands Options Options provide additional, optional functionality to use with a CLI command. You may also hear… # Using Options and Bulk Commands ## Options Options provide additional, optional functionality to use with a CLI command. You may also hear these referred to as flags or arguments. As mentioned in the previous step, `--help` is an example of an option. To see all valid options for a command, visit the [GitHub repository](https://github.com/box/boxcli#command-topics). For example, look at the command documentation for [deleting folders](https://github.com/box/boxcli/blob/master/docs/folders.md#box-foldersdelete-id). You will see a list of options to use with this command, such as `--recursive` or `--force`. ## As-User Header To use the [as-user header](g://authentication/jwt/as-user), add the `--as-user=USERID` option to the end of the command. For example, the following command will create a folder called `Example_Folder` at the root level in user ID 123456’s account. ``` box folders:create 0 Example_Folder --as-user=123456 ``` Only Service Accounts and Admins are able to use the as-user header. If your application was not authorized with the necessary scopes or you configured your CLI to obtain a default token for another user, this call may fail. Add `-v` or `--verbose` to your command for verbose error logging. ## Bulk Commands You can use a CSV file to execute commands in bulk. Each row of the spreadsheet is treated as an individual API call. To execute a bulk command, use the option `--bulk-file-path=<PATH_TO_CSV>`, where `<PATH_TO_CSV>` is the local path of a CSV file containing the necessary information. As an example, let's create folders using the command `box folders:create --bulk-file-path=pathtoacsv` Drag the CSV file from your finder window/file explorer to the terminal/command line window to auto-populate the path. To specify the column names for your CSV file, go to the [GitHub repository](https://github.com/box/boxcli#command-topics) documentation and look at the argument names or use the `--help` option. In this case, these are `PARENTID` and `NAME` and are case insensitive. You can also use a CSV [template](https://github.com/box/boxcli/blob/main/docs/Bulk%20actions/folders/folders-create.csv) for this example bulk create folders command. Executing the command below creates three folders at the root level, 0, of the Service Account's folder tree. ``` box folders:create --bulk-file-path=/Users/ExampleUser/Desktop/bulkcreatefolders.csv ``` ## Bulk Commands with Options Passing an option in a command will automatically apply to it to each row in the CSV file. For example, `box folders:collaborations:create --bulk-file-path=pathtocsv --role=editor` will create collaborations for each user in the csv as an editor. However, you can also use options in the CSV file. Building on the last example, instead of using the `--role=editor` option in the command itself, it can be a column called `role`. The command itself becomes: `box folders:collaborations:create --bulk-file-path=pathtocsv` For more details on bulk commands read [this document](g://cli/cli-docs/bulk-commands). ## Summary - You used an option with a command and/or a bulk command. I know how to use options and bulk commands **Reference:** https://developer.box.com/guides/cli/quick-start/options-and-bulk-commands/ --- ## Untitled *Type: quick-start | Category: CLI * Using PowerShell Scripts with the Box CLI By itself, the CLI is already powerful, but using it alongside a PowerShell script lets you… # Using PowerShell Scripts with the Box CLI By itself, the CLI is already powerful, but using it alongside a PowerShell script lets you complete repetitive tasks even quicker. We created an example [scripts](https://github.com/box/boxcli/tree/main/examples) folder within our CLI GitHub repository to help jump start your development. To show you how CLI scripts work, we are going to use the provision and create users [script](https://github.com/box/boxcli/tree/main/examples/User%20Creation%20&%20Provisioning) template. This script uses the Box CLI to build and create a personal folder structure, create managed users in bulk, and provision such new users by adding them to the newly created folder structure as collaborators with viewer or uploader roles. This part of the quick start is for service accounts and users with administrative privileges only. Skip this step if you are not a Box administrator or you do not use a service account. ## Use case To automatically create users and folder structure, the script performs the following steps: 1. Uses a `.csv` file to load employee data in bulk. 2. Defines folder structure using a JSON file or uploads the structure from the user's local directory. 3. Creates each new managed user a predetermined personal folder structure ## Prerequisites ### Windows Install the latest version of [dotnet core](https://dotnet.microsoft.com/download). ### MacOS & Linux Install [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2) If you encounter issues make sure you installed both [dotnet core](https://dotnet.microsoft.com/download) and [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2) ### Box CLI To use the script, you will need the Box CLI installed and configured. If you haven't done so yet, see [step 1](g://cli/quick-start/create-oauth-app) of this quick start guide. Alternatively, go to your [developer console](https://app.box.com/developers/console), and follow the guide [Setup with OAuth 2.0](g://authentication/oauth2/oauth2-setup). ### Create a personal folder parent folder This script works by creating a folder structure for each user that is created. In order to do this, you should go ahead and create a parent folder for all of the personal folders to live in. Otherwise, every folder will live in the root of the user that the CLI is setup with. You may name and place the folder wherever you wish, but the user you setup the CLI with must have access to the folder. Here is an example of what the structure will look like after running the script. ## Download the script Clone the script to a directory of your choice and navigate to that directory. ``` git clone https://github.com/box/boxcli.git box-cli cd box-cli/examples/User\ Creation\ \&\ Provisioning/ ``` ## Configure the script settings Adapt the script to run in your own environment. In this example, you will use the sample data provided with the script. ### Provide the parameters There are a few parameters you need to supply before running the script: - `EmployeeList`: Path to `Employee List` CSV. - `PersonalFolderParentID`: Destination folder ID for all personal folders to be created in, either when using JSON file as input to create folder structure, or uploading local structure. This folder should be made prior to running the script the first time. It is not advised to make this value `0`, as this will create individual Personal folders in root of the account you set up the CLI with. - `FolderStructureJSONPath`: Your own folder structure JSON path. - `PersonalFolderSlug`: Ending name of the folder that will be created as parent for personal folders. It's set to `Personal Folder` by default, but feel free to set it to your needs. The username is concatenated with this value to create each user's personal folder name. ex - `rsmith2's Personal Folder`. - `LocalUploadPath`: Local directory to upload folder structure directly. Specify either a local upload path or a JSON file with the folder structure, not both. ### Update the user list You can use the following sample files to load users: `Employees_1.csv`, `Employees_5.csv`, and `Employees_10.csv`. Each will load 1, 5 or 10 new users. Customize these files for a test run. For example, update the `Employees_1.csv` with the following data: ``` firstName,lastName,email,username Isaac,Newton,abc@abc.local,INewton23 ``` With the `EmployeeList` parameter, specify which `.csv` file you would like to load data from. Emails must be unique across all of Box, and usernames must be unique across your specific Box instance. Otherwise, an error will be thrown when running the script. ### Create folder structure You can either create a folder structure from a JSON file or upload it from your local drive. #### Use a JSON file The `Folder_Structure.json` file contains the folder structure you want to create. As an example, you will create a `Market Research` and a `Sales Plays` folder, each with a subfolder `Statistics` and `Big Pharma` respectively. The script will place this folder structure under the `Personal Folder` folder for that user inside the parent folder you designate. With the `FolderStructureJSONPath` parameter, provide the location of the `Folder_Structure.json` file. #### Upload file from local drive You can also upload a folder structure directly from the local file system. With the `LocalUploadPath` parameter, provide the path to your local folder you want to upload. The folder is still named and uploaded identically to the JSON file method. ### Update the parameters You have 3 ways to pass parameters before running the script: Use static values in the script Remember to update all required parameters in the script before running. ``` # Set Employee List CSV Path # firstname, lastname, email, username $EmployeeList = "" # Personal Folder Structure: Set either path build off JSON or directly upload # a local folder $FolderStructureJSONPath = "" $LocalUploadPath = "" # Ending slug of folder that will be used in creating personal folders for new # users. Value will get concatenated with username # If username is RSMITH, the personal folder name would be # RSMITH's Personal Folder $PersonalFolderSlug = "" # ID of parent folder for created personal folders to be created in # This folder should be created before running the script the first time. # It is not advised to make this value 0, as this will create individual # Personal folders in root of the account you set up the cli with $PersonalFolderParentID = "" ``` Run the script with parameters You can specify parameters while running the script, for example: ``` PS > ./Users_Create_Provision.ps1 -EmployeeList ./Employees_1.csv ` -LocalUploadPath ./PersonalLocalUpload ` -PersonalFolderSlug "Personal Folder" ` -PersonalFolderParentID 123456789 Starting User Creation & Provisioning script... ``` Provide the parameters when prompted If some parameters are still missing at runtime, the script will prompt you to provide them: ``` PS > ./Users_Create_Provision.ps1 Please enter the path to the employee list CSV file: ./Employees_1.csv Please enter the path to the folder structure JSON file or the local upload path: Folder_Structure.json Folder structure JSON path set to: Folder_Structure.json Please enter the ID of the folder where you would like to create the personal folders: 0 Starting User Creation & Provisioning script... ``` ## Run the script Change the directory to the folder containing the script. In this example, it is the `User Creation & Provisioning` folder. ``` pwsh ``` Run the script: ``` PS /home/rvb/box-cli/examples/User Creation & Provisioning> ./Users_Create_Provision.ps1 ``` The response will be similar to the following: ``` Starting User Creation & Provisioning script... firstName lastName email --------- -------- ----- Isaac Newton abc@abc.local Extracting folder structure Found current User ID: 18622116055 Created a user owned Onboarding folder with id: 164734146745 Created subfolder Market Research under Onboarding folder with id: 164735375585 Created subfolder under Statistics folder with id: 164734956242 Created subfolder Sales Plays under Onboarding folder with id: 164735683001 Created subfolder under Big Pharma folder with id: 164736160637 Creating employee Managed User account with first name: Isaac, last name: Newton, email: abc@abc.local, and Created Managed user with id: 19605663027 Type: collaboration ID: '37250833128' Created By: Type: user ID: '18622116055' Name: Rui Barbosa Login: barduinor@gmail.com Created At: '2022-06-07T13:58:05-07:00' Modified At: '2022-06-07T13:58:05-07:00' Expires At: null Status: accepted Accessible By: Type: user ID: '19605663027' Name: Isaac Newton Login: abc@abc.local Invite Email: null Role: viewer uploader Acknowledged At: '2022-06-07T13:58:05-07:00' Item: Type: folder ID: '164734146745' Sequence ID: '0' ETag: '0' Name: Onboarding Collaborated Managed User Isaac Newton to current users Onboarding folder for provisioning ``` ## Running the script again for new users It is common to run this script regularly as your company hires new employees. You can simply edit the `.csv` file, removing the previous rows of users and adding the information for the new users. Then, the script may be ran again. ## Summary You explored automation using a PowerShell script with the Box CLI to provision users and create an initial folder structure. Make sure to explore our other [sample scripts](g://cli/scripts) for more use cases. I know how to use the sample scripts to automate repetitive tasks **Reference:** https://developer.box.com/guides/cli/quick-start/powershell-script-templates/ --- ## Untitled *Type: guide | Category: CLI * Deprovision users and archive folders This script allows you to deprovision and delete a list of users. It performs the following steps… # Deprovision users and archive folders This script allows you to deprovision and delete a list of users. It performs the following steps: 1. Transfers the user content to the another user's root folder under specified in `EmployeeArchiveFolderName` parameter. 2. Deletes the user. ## Prerequisites ### Windows Install the latest version of [dotnet core](https://dotnet.microsoft.com/download). ### MacOS & Linux Install [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). Run the `pwsh` command to test the installation. ``` pwsh ``` Depending on the directory you are running the command in, the output may differ. For example: ``` PowerShell 7.2.5 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /Users/user/repos/boxcli/examples> ``` If you encounter issues make sure you installed both [dotnet core](https://dotnet.microsoft.com/download) and [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). ### Box CLI To use the script, you will need the Box CLI installed and configured. You can get this done by going through our [quick start guide](g://cli/quick-start/create-oauth-app). The user you use to login with should be the main Box admin or co-admin. ## Configure the script Clone the `boxcli` GitHub repository and cd into this example's folder or download the files from [`examples`](https://github.com/box/boxcli/tree/main/examples/User%20Deprovisioning) directory. ``` git clone https://github.com/box/boxcli.git boxcli cd boxcli/examples/User\ Deprovisioning/ ``` Create the list of employees for deletion in `.csv`. The header row should look like as follows: ``` name, email ``` where: - `name` is the name of the user in Box. - `email` is the primary email address of the user in Box. For example: | name | email | | --- | --- | | Managed User 1 | ManagedUser1@test.com | | Managed User 2 | ManagedUser2@test.com | | Managed User 3 | ManagedUser3@test.com | ### List of parameters | Parameter | Description | Required | Default Value | | --- | --- | --- | --- | | EmployeeList | Path to Employee List CSV with employees to be deleted. | Yes | - | | SkipTransferContent | Set this flag to skip transfer of user content before deletion when running the script. Otherwise user's content will be transferred. | No | False | | NewFilesOwnerID | The ID of the user to transfer files to before deleting the user. If not specified, the script will prompt to input in the interactive mode, or use the current authenticated user ID to receive the content. | No | If not specified, the script will prompt to input in the interactive mode, or use the current authenticated user ID. | | EmployeeArchiveFolderName | The name of a folder, where users' content will be moved to if SkipTransferContent is set to False. If a folder with this name already exists in the user's NewFilesOwnerID root folder, it will be used. Otherwise, a new one will be created. | Yes | Employee Archive | | DryRun | A flag that determines the script should be run in a mode, where no delete/create/update calls will be made, only read ones. | No | False | ### Define script parameters You can the following options to pass parameters. Use hardcoded value in script. To use this option, update all required parameters listed in the [script parameters section](https://github.com/box/boxcli/tree/main/examples/User%20Deprovisioning/Users_Deprovision.ps1#L17-L36) before running. Run script with parameters. You can specify parameters while providing the command. For example: ``` PS > ./Users_Deprovision.ps1 -EmployeeList ./Employees_to_delete.csv ` -NewFilesOwnerID 123456789 -EmployeeArchiveFolderName "Employee Archive" ``` or ``` PS > ./Users_Deprovision.ps1 -EmployeeList ./Employees_to_delete.csv ` -SkipTransferContent ``` If you don't specify parameters, the script will prompt you to enter it. ``` PS > ./Users_Deprovision.ps1 Please enter the path to the employee list CSV file: ./Employees_to_delete.csv Please specify the user ID of the user who will own the files of the users being deprovisioned. Press Enter if you want to use the current user as the new owner. User ID: 1234567689 Starting User Deprovisioning script... ``` ## Run the script Now all you need to do is run the script. Run the Powershell command. ``` pwsh ``` Run the script: ``` ./Users_Deprovision.ps1 ``` When all parameters are defined, you will see following output to confirm the script started: ``` PS /home/rvb/box-cli/examples/User Deprovisioning> ./Users_Deprovision.ps1 Starting User Deprovisioning script... ``` ## Logging Logs are stored in a `logs` folder located in the main folder. You have access to these log files: - `Users_Deprovision_all.txt` that contains all log entries - `Users_Deprovision_errors.txt` that contains only errors. **Reference:** https://developer.box.com/guides/cli/scripts/deprovision-users/ --- ## Untitled *Type: guide | Category: CLI * CLI sample scripts Box CLI scripts are designed to help you automate your tasks. Currently, the sample scripts library provides several… # CLI sample scripts Box CLI scripts are designed to help you automate your tasks. Currently, the sample scripts library provides several PowerShell scripts you can use and customize. In order to run them, you will need to have the Box CLI installed and configured. You can follow the [quick start guide](g://cli/quick-start/create-oauth-app) to get that done. Most of the below scripts require the user you run commands with to have Box [administrative privileges](https://support.box.com/hc/en-us/articles/360043694174-Understanding-Administrator-and-Co-Administrator-Permissions). ## PowerShell scripts - [Provision users and folders](g://cli/quick-start/powershell-script-templates) - [Deprovision users and archive folders](g://cli/scripts/deprovision-users) - [Manage groups and collaborations](g://cli/scripts/manage-groups-collaborations) - [Report inactive users](g://cli/scripts/report-inactive-users) - [Extract metadata](g://cli/scripts/metadata-extraction) - [Update user zones](g://cli/scripts/user-zones-mass-update) - [Manage Slack integration folder mappings](g://cli/scripts/slack-integration-mappings) **Reference:** https://developer.box.com/guides/cli/scripts/ --- ## Untitled *Type: guide | Category: CLI * Manage groups and collaborations Script structure This script uses Box CLI to create or update groups, add users to them, and finally to… # Manage groups and collaborations ## Script structure This script uses Box CLI to create or update groups, add users to them, and finally to create collaborations between groups and folders. The script consists of two parts described in detail in the sections below. You can run them both or use the optional flags to decide which part to run. ### Create or update groups The script uses the `.csv` file you specify for the `UserGroupAdditionPath` parameter. The file lists group names and user emails. When creating the file, you can use the same group name for several users, and assign one user to several groups. For example: | GroupName | UserEmail | | --- | --- | | Group1 | ManagedUser1@test.com | | Group1 | ManagedUser2@test.com | | Group2 | ManagedUser3@test.com | | Group3 | ManagedUser1@test.com | If the group doesn't exist, the script creates it. If it does exist, the script can update the entries based on the provided data. ### Create or update collaborations The script uses the `.csv` file you specify for the `CollaborationsCreationPath` parameter. The file lists group names, folder IDs, and collaboration roles. For each row, the script checks if a group exists and if it's not already added as a collaborator to the corresponding folder. For example: | GroupName | FolderId | CollaborationRole | | --- | --- | --- | | Group1 | 1111111 | editor | | Group2 | 1111111 | viewer_uploader | | Group2 | 2222222 | viewer | | Group3 | 1111111 | viewer_uploader | If both of these conditions are met, the script assigns the group to a folder using the role defined in the `CollaborationRole` column. Also, if a group already exists, but the `CollaborationRole` changed, the script will update it if you pass the `-UpdateExistingCollabs` flag when running the script. ## Prerequisites ### Windows Install the latest version of [dotnet core](https://dotnet.microsoft.com/download). ### MacOS & Linux Install [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). Run the `pwsh` command to test the installation. ``` pwsh ``` Depending on the directory you are running the command in, the output may differ. For example: ``` PowerShell 7.2.5 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /Users/user/repos/boxcli/examples> ``` If you encounter issues make sure you installed both [dotnet core](https://dotnet.microsoft.com/download) and [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). ### Box CLI To use the script, you will need the Box CLI installed and configured. You can get this done by going through our [quick start guide](g://cli/quick-start/create-oauth-app). The user you use to login with should be the main Box admin or co-admin. ## Configure the script Clone the `boxcli` GitHub repository and cd into this example's folder or download the files from [`examples`](https://github.com/box/boxcli/tree/main/examples) directory. ``` git clone https://github.com/box/boxcli.git boxcli cd boxcli/examples/Mass\ Groups\ \&\ Collaborations\ Update/ ``` Set the path to the `.csv` file with the list of groups and user emails. ``` $UserGroupAdditionPath = "./User_Group_Addition.csv" ``` - `UserEmail` is the primary email address for the user in Box. - `GroupName` is the name of the group. Set your own path to the `.csv` file with the list groups and user emails. ``` $CollaborationsCreationPath = "./Collaborations_Creation.csv" ``` - `GroupName` is name of the group the script will add as a collaborator to the folder. - `FolderId` is the folder ID the collaborator will be added to. - `CollaborationRole` is the name of the role used when creating a collaboration. You can configure the available roles by setting the `AvailableCollaborationRoles` parameter: ``` $AvailableCollaborationRoles = @("editor", "viewer", "previewer", "uploader", "previewer_uploader", "viewer_uploader", "co-owner") ``` ## Run the script Run the Powershell command. ``` pwsh ``` Run the script. ``` ./Mass_Groups_Collabs_Update.ps1 ``` ### Optional flags You can use flags to run run or skip specific parts of the script. If a group already is set as a collaborator for a specific folder but with a role other than defined in the .`csv` file, the script will inform you about it. It will not make any changes to an existing collaboration. If you want to update an existing collaboration with role defined in `.csv` file, set an additional `-UpdateExistingCollabs` flag when running the script. ``` Mass_Groups_Collabs_Update.ps1 -UpdateExistingCollabs ``` To update groups without creating collaborations, add the `-SkipCollabsCreation` boolean flag when running the script: ``` Mass_Groups_Collabs_Update.ps1 -SkipCollabsCreation ``` To create collaborations without any group updates, add the `-SkipGroupsUpdate` boolean flag when running the script: ``` Mass_Groups_Collabs_Update.ps1 -SkipGroupsUpdate ``` ## Logging Logs are stored in the `logs` folder located in the main folder. You have access to these log files: - `Mass_Groups_Collabs_Update_all.txt` that contains all log entries - `Mass_Groups_Collabs_Update_errors.txt` that contains only errors. **Reference:** https://developer.box.com/guides/cli/scripts/manage-groups-collaborations/ --- ## Untitled *Type: guide | Category: CLI * Provision users and folders This script uses the Box CLI to build and create a personal folder structure, create managed users in bulk, and… # Provision users and folders This script uses the Box CLI to build and create a personal folder structure, create managed users in bulk, and provision such new users by adding them to the newly created folder structure as collaborators with viewer or uploader role. For details, see the quick start guide on [using Box CLI and sample scripts](g://cli/quick-start/powershell-script-templates). **Reference:** https://developer.box.com/guides/cli/scripts/provision-users-folders/ --- ## Untitled *Type: guide | Category: CLI * Extract metadata This script extracts metadata details for all the files and folders in any Box folder and saves the result in a CSV… # Extract metadata This script extracts metadata details for all the files and folders in any Box folder and saves the result in a CSV spreadsheet for each metadata template. ## Prerequisites ### Windows Install the latest version of [dotnet core](https://dotnet.microsoft.com/download). ### MacOS & Linux Install [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). Run the `pwsh` command to test the installation. ``` pwsh ``` Depending on the directory you are running the command in, the output may differ. For example: ``` PowerShell 7.2.5 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /Users/user/repos/boxcli/examples> ``` If you encounter issues make sure you installed both [dotnet core](https://dotnet.microsoft.com/download) and [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). ### Box CLI To use the script, you will need the Box CLI installed and configured. You can get this done by going through our [quick start guide](g://cli/quick-start/create-oauth-app). ## Configure the script Clone the `boxcli` GitHub repository and cd into this example's folder or download the files from [`examples`](https://github.com/box/boxcli/tree/main/examples/Metadata%20Extraction) directory. ``` git clone https://github.com/box/boxcli.git cd boxcli/examples/Metadata\ Extraction/ ``` Specify the `folderID` and `userID` parameters to tell the script which folder to scan, and who is the user running the script. ``` [string]$FolderID = "", [string]$UserID = "", ``` If you don't want to specify the parameters directly in the script, you can either pass them as flags or allow the script to prompt you to enter them. A sample command with flags looks as follows: ``` ./Metadata-extraction.ps1 -folderId 123456789 -userId 123456789 ``` ## Run the script Run the Powershell command. ``` pwsh ``` Run the script. ``` ./Metadata-extraction.ps1 -folderId 123456789 -userId 123456789 ``` When the script finishes, you will see the following output or a similar one. ``` Pulling data from Folder ID: 173961139760 metadata as user ID: 20718545815 Reading Item ID: 1016853559790 Metadata saved to: MetadataTemplate_properties.csv ``` ## Logging Logs are stored in a `logs` folder located in the main folder. You have access to these log files: - `Metadata-extraction_all.txt` that contains all log entries. - `Metadata-extraction_errors.txt` that contains only errors. **Reference:** https://developer.box.com/guides/cli/scripts/metadata-extraction/ --- ## Untitled *Type: guide | Category: CLI * Report inactive users This script generates a CSV file with a list of users who have been inactive for a number of days. It performs the… # Report inactive users This script generates a CSV file with a list of users who have been inactive for a number of days. It performs the following steps: Looks for the users who have the role `user`. The script does not consider other roles, such as `AppUser`. Uses [Box Events](resource://event) to check if the user performed any actions for a specified number of days. The default list of event types includes: `LOGIN`,`UPLOAD`,`COPY`,`MOVE`,`PREVIEW`,`DOWNLOAD`,`EDIT`,`DELETE`,`UNDELETE`,`LOCK`,`UNLOCK`, `NEW_USER`. You can modify this list in the script settings. Adds users who didn't perform any actions to a `.csv` file with inactive users. You can use this file as input for other scripts, for example to [deprovision users](g://cli/scripts/deprovision-users). ## Prerequisites ### Windows Install the latest version of [dotnet core](https://dotnet.microsoft.com/download). ### MacOS & Linux Install [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). Run the `pwsh` command to test the installation. ``` pwsh ``` Depending on the directory you are running the command in, the output may differ. For example: ``` PowerShell 7.2.5 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /Users/user/repos/boxcli/examples> ``` If you encounter issues make sure you installed both [dotnet core](https://dotnet.microsoft.com/download) and [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). ### Box CLI To use the script, you will need the Box CLI installed and configured. You can get this done by going through our [quick start guide](g://cli/quick-start/create-oauth-app). The user you use to login with should be the main Box admin or co-admin. ## Configure the script Clone the `boxcli` GitHub repository and cd into this example's folder or download the files from [`examples`](https://github.com/box/boxcli/tree/main/examples/Inactive%20Users%20Report) directory. ``` git clone https://github.com/box/boxcli.git cd boxcli/examples/Inactive\ Users\ Report/ ``` Set the number of days you want the script to scan for user events. If you don't specify this value or leave the default, the script will prompt you to enter it. ``` $daysInactive = "10" ``` (Optional) To change the report output file name, define the `ReportOutputFile` parameter. ``` $ReportOutputFile = $ReportName + ".csv" ``` (Optional) To change event types, define the list for `eventType` parameter. ``` $eventType = "LOGIN,UPLOAD,COPY,MOVE" ``` ## Run the script Run the Powershell command. ``` pwsh ``` Run the script. ``` ./Inactive_Users_Report.ps1 ``` When the script run is completed, you will see the following output or a similar one. ``` Looking for users inactive for more than 3 days. Found 6 users. Found 7 events in last 3 days Enterprise has: 0 App user, 6 regular users. With 1 admin role, 5 user roles. Need to check 5 users (regular user, with user role) for inactive. Found 5 users inactive for more than 3 days. Report is available at InactiveUsers.csv ``` ## Logging Logs are stored in the `logs` folder located in the main folder. You have access to these log files: - `Inactive_Users_Report_all.txt` that contains all log entries - `Inactive_Users_Report_errors.txt` that contains only errors. **Reference:** https://developer.box.com/guides/cli/scripts/report-inactive-users/ --- ## Untitled *Type: guide | Category: CLI * Manage Slack integration folder mappings This script helps manage the folder mappings between Slack and Box if using Box as the content… # Manage Slack integration folder mappings This script helps manage the folder mappings between Slack and Box if using Box as the content store for Slack. It creates a list of current Slack channel and Box folder mappings and can create or update mappings based on input csv. This script will maintain all permissions. For more details, you can checkout the [Github repo](https://github.com/box/boxcli/tree/main/examples/Integration%20Mappings). ## Prerequisites ### Clone script Clone this GitHub repo or download files from the `/examples` directory ``` git clone https://github.com/box/boxcli.git ``` ### Windows Install the latest version of [dotnet core](https://dotnet.microsoft.com/download). ### MacOS & Linux Install [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). Run the `pwsh` command to test the installation. ``` pwsh ``` Depending on the directory you are running the command in, the output may differ. For example: ``` PowerShell 7.2.5 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /Users/user/repos/boxcli/examples> ``` If you encounter issues make sure you installed both [dotnet core](https://dotnet.microsoft.com/download) and [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). ### Box CLI Install Configure and install the Box CLI using the OAuth [CLI Setup Quick Start](g://cli/quick-start). Make sure the user you use is an admin or co-admin. ### Enterprise configuration - Configure and [install Box for Slack](https://support.box.com/hc/en-us/articles/360044195313-Installing-and-Using-the-Box-for-Slack-Integration) in the relevant Slack work spaces and organizations - Box as the [content layer for Slack](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) in enabled ## Run the script Change the directory to the folder containing the script. In this example, it is the `Integration Mappings` folder. ``` rvb@lab:~/box-cli/examples/Integration Mappings$ pwsh PowerShell 7.2.4 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /home/rvb/box-cli/examples/Integration Mappings> ``` Run the script with EXTRACT to extract current mappings: ``` ./integration-mappings.ps1 -Action EXTRACT ``` or Run the script with UPDATE to update current mappings: ``` ./integration-mappings.ps1 -Action UPDATE ``` or Run the script with CREATE to create new mappings: ``` ./integration-mappings.ps1 -Action CREATE -MappingPath ./mapping_create_example.csv ``` By default, the csv file will save to and load from ./mappings.csv. If you wish to change this location, you can pass in a new path like so: ``` ./integration-mappings.ps1 -Action EXTRACT -MappingPath ./mappings_new_location.csv ``` If you don't specify parameters, the script will prompt you to enter them. When the script run is completed, you will see the following output or a similar one. When creating a mapping on a new channel, you must input a Box folder id, Slack channel id and Slack org id. You may use a Slack workspace ID in lieu of the org id. In that case, you would replace the csv column header `SlackOrgId` with `SlackWorkspaceId`. ``` Starting Process Applying new mappings Output [...] All bulk input entries processed successfully. ``` ## Logging Logs are stored in a `logs` folder located in the main folder. You have access to these log files: - `Integration-mappings_all.txt` that contains all log entries. - `Integration-mappings_errors.txt` that contains only errors. ## Disclaimer This project is a collection of open source examples and should not be treated as an officially supported product. Use at your own risk and as a source of example how to use Box CLI. **Reference:** https://developer.box.com/guides/cli/scripts/slack-integration-mappings/ --- ## Untitled *Type: guide | Category: CLI * Update user zones This script provisions users to a specific data residency zone within a Multizone Box tenant. It performs the following… # Update user zones This [script](https://github.com/box/boxcli/tree/main/examples/Mass%20Update%20User%20Zones) provisions users to a specific data residency zone within a Multizone Box tenant. It performs the following steps: 1. It uses admin or co-admin login email address to find the associated enterprise and the zone policy assigned to this enterprise. An assigned zone policy is inherited by all users unless specified otherwise. It is sometimes called the **default zone**. 2. It performs zone assignment based on an input `.csv` file containing user email addresses and zone mappings. Usually, you use the script once to do the initial provisioning of user zones, but you can also use it for subsequent runs to make zone assignment updates. If you would like to use Admin Console for zone assignment, see [this guide](https://support.box.com/hc/en-us/articles/360044193533-Assigning-Zones-through-the-Admin-Console). For more information about Box Zones, see the [official website](https://www.box.com/zones). ## Prerequisites ### Windows Install the latest version of [dotnet core](https://dotnet.microsoft.com/download). ### MacOS & Linux Install [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). Run the `pwsh` command to test the installation. ``` pwsh ``` Depending on the directory you are running the command in, the output may differ. For example: ``` PowerShell 7.2.5 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /Users/user/repos/boxcli/examples> ``` If you encounter issues make sure you installed both [dotnet core](https://dotnet.microsoft.com/download) and [PowerShell](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2). ### Set up application with JWT authentication To use the script, you will need the [Box CLI with JWT authentication](g://cli/cli-docs/jwt-cli) installed and configured. When creating the app, use the **Configuration** tab to configure the following settings: - In **App Access Level**, select `App + Enterprise Access`. - In **Application Scopes** > **Administrative Actions**, select `Manage Enterprise Properties`, `Manage Users`. - In **Advanced Features**, select `Generate user access tokens`. ### Adjust admin settings Make sure Box Admin or Co-Admin has at least `Manage Users` privileges. To check this setting: 1. Go **Users & Groups** section in the Admin Console. 2. Click the user account you want to verify. 3. Go to **Edit User Access permissions** section to grant the administrative privileges for users and groups. ## Prepare the .csv file The `.csv` file must have two columns with the following headers: **Email** and **Region**. **Email** contains the primary email address of a Box user. **Region** contains the user-friendly name for the zone to which the script will assign the user. This name is provided by the [ZonesTable](https://github.com/box/boxcli/blob/main/examples/Mass%20Update%20User%20Zones/Mass_Update_User_Zones.ps1#L23) that is a hash table used to define zones. The keys are the zone's user-friendly names, and the corresponding value is the global ID of the zone. ``` $ZonesTable = @{ US = "100001" #US GermanyIreland = "100002" #Germany/Ireland with in region uploads/downloads/previews Australia = "100003" #Australia Japan = "100004" #Japan with in region uploads/downloads/previews Canada = "100005" #Canada JapanSingapore = "100007" #Japan/Singapore with in region uploads/downloads/previews UKGermany = "100008" #UK/Germany UK = "100009" #UK with in region uploads/downloads/previews France = "100012" #France } ``` Consult the Box Consulting or Customer Success manager to get the IDs corresponding to the zones enabled in a specific enterprise. A sample input `.csv` file containing emails and zone names is provided with this script. Its content looks as follows: | Email | Region | | --- | --- | | betty@company.com | US | | roger@company.com | France | | sally@company.com | JapanSingapore | ## Configure the script Set the `UserZonesUpdatePath` to point to your `.csv` file. ``` $UserZonesUpdatePath = "./your_file_name.csv" ``` Update the `adminEmail` to the admin or `co-admin` login email address of the account the script will use to make zone assignments. If you don't specify this value, the script will prompt you for it. ``` $adminEmail = "john@box.com" ``` ## Run the script Run the Powershell command. ``` pwsh ``` Run the script. ``` ./Mass_Update_User_Zones.ps1 ``` ### Optional flags To run the script in a simulation mode, add the `DryRun` boolean flag. Dry run doesn't mean that API calls won't be made, but that any create/update/delete calls will be skipped. ``` ./Mass_Update_User_Zones.ps1 -DryRun ``` ## Logging Logs are stored in a `logs` folder located in the main folder. You have access to these log files: - `Mass_Update_User_Zones_all.txt` that contains all log entries. - `Mass_Update_User_Zones_errors.txt` that contains only errors. **Reference:** https://developer.box.com/guides/cli/scripts/user-zones-mass-update/ --- ## Untitled *Type: guide | Category: Collaborations * Remove a previously allowed domain for collaboration Deleting a domain from the list of allowed collaboration domains will remove the… # Remove a previously allowed domain for collaboration Deleting a domain from the list of allowed collaboration domains will remove the ability for collaborations to be created between your enterprise and users in that domain. To remove a domain from the allowed list, supply the ID of the list entry to the delete request. This ID is returned when [allowing a new domain](guide://collaborations/allowed-domains/create) or [listing the allowed domains in the enterprise](guide://collaborations/allowed-domains/list); **Reference:** https://developer.box.com/guides/collaborations/allowed-domains/delete/ --- ## Untitled *Type: guide | Category: Collaborations * Allow a domain for collaboration An enterprise that normally restricts creating collaborations can add domains, such as example.com, to a… # Allow a domain for collaboration An enterprise that normally restricts creating collaborations can add domains, such as `example.com`, to a list for which collaborations may be created within the enterprise. The [endpoint](endpoint://post_collaboration_whitelist_entries) will require the `domain` to allow the collaborations between, and a `direction`, which may be set to: - `inbound`: Whether external users may be collaborated in on content in your enterprise. - `outbound`: Whether your enterprise managed users may be collaborated in on content owned within an external enterprise. - `both`: Both of the above. Supply both parameter to set up the new allowed domain. **Reference:** https://developer.box.com/guides/collaborations/allowed-domains/create/ --- ## Untitled *Type: guide | Category: Collaborations * Allowed collaboration domains Within the content and sharing settings for an enterprise, an admin can specify collaboration restrictions for… # Allowed collaboration domains Within the content and sharing settings for an enterprise, an admin can specify [collaboration restrictions](https://support.box.com/hc/en-us/articles/4404822772755-Enterprise-Settings-Content-Sharing-Tab) for the enterprise. These settings include the ability to limit collaborations to only a series of allowed domains. The allowed domain APIs are available to allow applications with appropriate permissions to add, fetch, and delete these allowed domains programmatically for the enterprise. **Reference:** https://developer.box.com/guides/collaborations/allowed-domains/ --- ## Untitled *Type: guide | Category: Collaborations * List allowed domains for collaboration Listing the domains that are allowed for collaboration will return all domains that permit… # List allowed domains for collaboration Listing the domains that are allowed for collaboration will return all domains that permit collaborations to be created with the current enterprise. There are no required parameters for the request, but `limit` and `market` parameters may optionally be set to limit and page through the full result set. **Reference:** https://developer.box.com/guides/collaborations/allowed-domains/list/ --- ## Untitled *Type: quick-start | Category: Collaborations * Configure Slack The first step in this guide is to create and configure a Slack application. This Slack application will act as a bot that… # Configure Slack The first step in this guide is to create and configure a Slack application. This Slack application will act as a bot that listens for user events in Slack channels, and responds to **slash commands** by users in those channels - allowing them to share Box files and folders with the group. This section will take you through the following steps. - Create a minimal Slack application within the Slack API dashboard - Configure the Slack application to send notifications to our application whenever a user joins or leaves the channel - allowing our code to update the Box Box group. - Configure a `/boxadd` **slash command** that will allow users to share a Box file or folder with all the users in the channel. ## Create a minimal Slack app Go to the **[Slack apps page](https://api.slack.com/apps)** and click **Create an App**. Add an **App Name**, select your **Development Slack Workspace** from the dropdown list where the bot will be deployed to, then click **Create App**. Once created, you will be redirected to the basic information section of the application. You may adjust the icon and description of your app within the **Display Information** section at the bottom to customize the application in your workspace. ## Configure the Slack app's event listener Setting up an event listener for our Slack app will allow us to monitor for events within the channel. For this bot, we want to monitor three [Slack events](https://api.slack.com/events) in order to perform actions within Box. - [`bot_added`](https://api.slack.com/events/bot_added): When the bot is first added to a channel, it will get a list of all users in the channel, then create a Box group for those users. We can then use this group later on to add that group to any content that is shared with the **slash command**. - [`member_joined_channel`](https://api.slack.com/events/member_joined_channel): When a new user joins a Slack channel they will be added to the Box group. - [`member_left_channel`](https://api.slack.com/events/member_left_channel): When a user leaves a Slack channel, or the user is removed, they will be removed from the Box group. To set up a notification URL to which these Slack event payloads will be sent, Slack requires a verification step. When you set an event listener URL for your bot application code, Slack will immediately send a challenge to that URL to verify that it's valid. This will be an HTTP POST with a payload that looks something like the following: ``` { "token": "Jhj5dZrVaK7ZwHHjRyZWjbDl", "challenge": "3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P", "type": "url_verification" } ``` To set up the URL for the event listener, that URL that is set needs to respond with a verification payload containing the challenge value back to Slack during this step. The payload will look similar to the following. ``` HTTP 200 OK Content-type: application/json {"challenge":"3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P"} ``` To do this we will deploy a small bit of code to respond to the challenge event. Choose your preferred language / framework below to get started. # Node (Express Framework) # Java (Spring Boot Framework) Within the project directory, run `npm install express --save` to install the Express dependency, then deploy the following code to your public endpoint along with the appropriate Node modules. ``` const express = require('express'); const app = express(); const port = process.env.PORT || 3000; app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.post('/event', (req, res) => { if ( req.body && req.body.challenge && req.body.type === 'url_verification' ) { res.send({ challenge: req.body.challenge }); } else { res.status(400).send({ error: "Unrecognized request" }); } }); app.listen(port, function(err) { console.log("Server listening on PORT", port); }); ``` [`Spring Initializr`](https://start.spring.io/) is a useful service for auto-generating a new Spring boot application with all dependencies defined. This may be used instead of creating a blank Java application. - From Eclipse, create a new project. When prompted, select a Gradle project. - Enter a unique name for the project, we used `slack.box` for this guide. - Open your `build.gradle` file and add the following. Ensure that the group matches the group that you used for the application. Once saved, refresh the Gradle project. ``` plugins { id 'org.springframework.boot' version '2.3.1.RELEASE' id 'io.spring.dependency-management' version '1.0.9.RELEASE' id 'java' } group = 'com.box' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' testImplementation('org.springframework.boot:spring-boot-starter-test') { exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' } compile 'com.box:box-java-sdk:2.44.1' } test { useJUnitPlatform() } ``` - Within your `src/main/java` path, create a new Java class file named `Application.java`. - Open the file, add the following code, and save. ``` package com.box.slack.box; import org.jose4j.json.internal.json_simple.JSONObject; import org.jose4j.json.internal.json_simple.parser.JSONParser; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration public class Application { @PostMapping("/event") public JSONObject challenge(@RequestBody String data) throws Exception { JSONObject returnJSON = new JSONObject(); Object dataObj = new JSONParser().parse(data); JSONObject inputJSON = (JSONObject) dataObj; String challenge = (String) inputJSON.get("challenge"); String type = (String) inputJSON.get("type"); if (type.equals("url_verification")) { returnJSON.put("challenge", challenge); } else { System.err.println("Invalid input"); } return returnJSON; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` # Incomplete previous step Please select a preferred language / framework above to get started. Now that we have the code to respond to the Slack challenge when adding an event URL, we can configure that within the Slack application. From your Slack application **Basic Information** tab, under **Add features and functionality**, click on the button titled **Event Subscriptions** and do the following. - Toggle **Enable Events** to **On**. - Under **Request URL** add in the public URL that you deployed the above code to, and be aware that we are listening at `{YOUR_APP_DOMAIN}/event` (such as `https://myapp.com/event`). Once you add the URL and click outside the field, Slack will immediately send the challenge to the URL that you were hosting the code at above. If the code responds correctly, you will see a green verified note beside the **Request URL** header. - Expand the **Subscribe to bot events** section and click on the **Add Bot User Event** button. - Add `member_joined_channel` and `member_left_channel` to the events the bot is subscribed to. These will send events when anyone new is added to the channel. - Click the **Save Changes** button at the bottom of the page. ## Configure the Slack app slash command To provide every user in a Slack channel access to a file or folder in Box, we can use a Slack **"slash commands"**. A slash command will allow any person in the channel to share content they own in Box with the rest of the channel. Through this command, a channel member will be able to type `/boxadd [file / folder] [id]`, for example `boxadd file 1459732312`, into the channel to share the file / folder with every user in the channel. To do this, the file is automatically collaborated with the Box group of users that are in that channel. From the **Basic Information** tab of your application, under Add features and functionality, click on the button titled **Slash Commands**. In the page that comes up, click **Create New Command** and input the following: - **Command**: This is the command that a channel user will use to share a Box file / folder ID with the channel. Use `/boxadd` for this quick start. - **Request URL**: The URL that is listening for and responding to slash commands in our Slack bot. In this quick start we use the same event URL that was used for the app event listener section above. - **Short Description**: A description of what the Slash command will do. - **Usage Hint**: Additional parameters that may be passed to the command. In our case, that's the Box file / folder ID and type of content. Click **Save** to add the command to our Slack app. ## Add Additional Scopes When slash commands or notifications are sent to our application from Slack they will contain a Slack user ID, which relates to the person that took or was affected by the action. To translate that ID to a Box user we need to get the Slack user's email, which we can then use to associate that Slack user to a corresponding Box user. This action requires two extra scopes in the Slack application configuration. From your Slack application configuration, click on **OAuth & Permissions** in the left menu, then do the following. - Scroll down to the **Scopes** section. - Click on the **Add an OAuth Scope** button under **Bot Token Scopes**.. - Search for and add `users:read` and `users:read.email`. ## Deploy Bot to Slack Workspace The last step is to install the application into your Slack workspace. From the **Basic Information** page of the app, expand the **Install your app to your workspace** section. Click the button to **Install App to Workspace**. Once the **Allow** button is clicked you should see a success message. Your bot is now installed within the workplace. ## Summary - You've created your Slack application. - You've configured user event notifications, slash commands, and additional scoping. - You've deployed your Slack bot to your workspace. I have my local application set up **Reference:** https://developer.box.com/guides/collaborations/connect-slack-to-group-collabs/configure-slack/ --- ## Untitled *Type: quick-start | Category: Collaborations * Connect Bot to Box We're now handling and processing events coming from Slack, then obtaining all information needed to connect with Box… # Connect Bot to Box We're now handling and processing events coming from Slack, then obtaining all information needed to connect with Box users and groups. We now need to connect that functionality to Box functions. In this step we'll expand several functions from the last step to incorporate new Box features. - Instantiate a Box client. - Add a Box user to a Box group. - Remove a Box user from a Box group. - Fetch a Box group ID from a group name. - Add content that is shared to a group. ## Instantiate a Box Client To make calls to the Box APIs, you'll first need to set up a Box client. Within `process.js`, replace the `// INSTANTIATE BOX CLIENT` comment at the top with the following. ``` const boxConfig = require("./boxConfig.json"); const sdk = box.getPreconfiguredInstance(boxConfig); const client = sdk.getAppAuthClient("enterprise"); ``` The `boxConfig` assignment line will use the `boxConfig.json` file you downloaded from your Box app at the end of [step 2](g://collaborations/connect-slack-to-group-collabs/configure-box). The sample above is assuming that you have it stored in the same folder as `process.js`. If that's not the case, change the path to point to where your `boxConfig.json` file is, and what it may be named. The last `client` assignment line is creating a Box client object which may be used to make API calls. At this point it is scoped to the [service account](page://platform/user-types/#service-account/) of the application, and not a specific user. Within `Application.java`, replace the `// INSTANTIATE BOX CLIENT` comment within the `processEvent` method with the following. ``` this.fileReader = new FileReader("boxConfig.json"); this.boxConfig = BoxConfig.readFrom(fileReader); this.boxAPI = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig); ``` The `boxConfig` assignment line will use the `boxConfig.json` file you downloaded from your Box app at the end of [step 2](g://collaborations/connect-slack-to-group-collabs/configure-box). The sample above is assuming that you have it stored at the root of the Java project. If that's not the case, change the path in the `fileReader` assignment to point to where your `boxConfig.json` file is, and what it may be named. The last `boxAPI` assignment line is creating a Box client object which may be used to make API calls. At this point it is scoped to the [service account](page://platform/user-types/#service-account/) of the application, and not a specific user. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Add a Box user to a group Let's add a function that adds a Box user to a group. When a bot is added to a channel and needs to create a Box group with all users of the channel, or when a single user joins the channel after that action, this function will perform that task. Replace the `addGroupUser` function with the following. ``` function addGroupUser(groupId, email) { client.enterprise.getUsers({ filter_term: email }).then((users) => { if (users.entries.length > 0) { const userId = users.entries[0].id; const groupRole = client.groups.userRoles.MEMBER; client.groups .addUser(groupId, userId, { role: groupRole }) .then((membership) => { if (membership.id) { console.log(`Member added with membership ID: ${membership.id}`); } else { console.log(`Member not added`); } }) .catch(function (err) { console.log(err.response.body); }); } else { console.log("No Box user found to add to group"); } }); } ``` Replace the `addGroupUser` method with the following. ``` public void addGroupUser(String groupId, String userEmail) { Iterable<BoxUser.Info> users = BoxUser.getAllEnterpriseUsers(this.boxAPI, userEmail); for (BoxUser.Info user : users) { if (user.getLogin().toUpperCase().equals(userEmail.toUpperCase())) { try { BoxGroup group = new BoxGroup(boxAPI, groupId); BoxUser boxUser = new BoxUser(this.boxAPI, user.getID()); BoxGroupMembership.Info groupMembershipInfo = group.addMembership(boxUser); } catch (Exception ex) { System.err.println("User already present"); } } } } ``` # Incomplete previous step Please select a preferred language / framework in step 1 to get started. Since we're matching a Slack user to a Box user via their email address, we first find a matching Box user using the Slack profile email. If found, a call is made to add that user to the channel group. The group was created when the bot was first added. The Box [Get User](endpoint://get-users-id) endpoint only permits user lookup by user ID. To lookup a user by email address, use the [List Enterprise Users](endpoint://get-users) endpoint and set the `filter_term` option to the email address you're searching for. ## Remove a Box user to a group When a user leaves or is removed from a Slack channel, we also want to remove them from the Box group so that they can no longer access the shared group content. Replace the `removeGroupUser` function with the following. ``` function removeGroupUser(groupId, email) { client.groups.getMemberships(groupId).then(memberships => { for (let i = 0; i < memberships.entries.length; i++) { if (memberships.entries[i].user.login === email) { client.groups .removeMembership(memberships.entries[i].id) .then(() => { console.log('Group user removed') }); break; } } }); } ``` Replace the `removeGroupUser` method with the following. ``` public void removeGroupUser(String groupId, String userEmail) { BoxGroup boxGroup = new BoxGroup(this.boxAPI, groupId); Iterable<BoxGroupMembership.Info> memberships = boxGroup.getAllMemberships(); for (BoxGroupMembership.Info membershipInfo : memberships) { if (membershipInfo.getUser().getLogin().toUpperCase().equals(userEmail.toUpperCase())) { BoxGroupMembership membership = new BoxGroupMembership(this.boxAPI, membershipInfo.getID()); membership.delete(); } } } ``` # Incomplete previous step Please select a preferred language / framework in step 1 to get started. This code will take the group ID, which will be the Slack channel ID, and get all members of the group. If a matching member is found for the person that left the Slack channel, based on email address, that person is removed from the group using their membership ID. # Improving performance with a data store While looking up group memberships to obtain a membership ID negates the need to store membership IDs in a local data store (like a database), this code can be made more efficient by having a data store that saves the Box membership ID with the user record. By using a local data store, the membership ID can be retrieved from the data store rather than having to call the Box API repeatedly to search for the membership ID. ## Fetch a Box group ID for a group name The next Box function we need has two main purposes. - Return the Box group ID of an existing group. - If a group doesn't exist, create the Box group and return the ID. Replace the `getGroupId` function with the following. ``` function getGroupId(groupName, callback) { client.groups.getAll().then((groups) => { const group = groups.entries.filter((g) => g.name === groupName)[0]; if (!group) { client.groups .create(groupName, { description: "Slack channel collaboration group", invitability_level: "all_managed_users", }) .then((group) => { callback(group.id); }); } else { callback(group.id); } }); } ``` Replace the `getGroupId` method with the following. ``` public String getGroupId(String groupName) { String groupId = new String(); Iterable<BoxGroup.Info> groups = BoxGroup.getAllGroups(this.boxAPI); for (BoxGroup.Info groupInfo : groups) { if (groupInfo.getName().toUpperCase().equals(groupName)) { groupId = groupInfo.getID(); } } if (groupId.isEmpty()) { BoxGroup.Info groupInfo = BoxGroup.createGroup(boxAPI, groupName); groupId = groupInfo.getID(); } return groupId; } ``` # Incomplete previous step Please select a preferred language / framework in step 1 to get started. The code fetches all the groups in the enterprise, and then tries to match the Slack channel ID to the group name. If any of the groups matches, the group ID is returned. If there are no matches, a new Box group is created and the ID of the group is returned for use. The group will be named after the Slack channel ID since that is a constant that is returned with both slash commands and user events, making it easier to lookup without additional functions. ## Add shared content to a group Finally, the main purpose of our whole application is to allow users to share files and folders from their own Box accounts with everyone else in the group. Building upon all previous functionality, the following function performs that task. Replace the `processContent` function with the following. ``` function processContent(user, channel, itemType, itemId) { getGroupId(channel, function (groupId) { const email = user.profile.email; client.enterprise.getUsers({ filter_term: email }).then((users) => { if (users.entries.length > 0) { client.asUser(users.entries[0].id); const collabRole = client.collaborationRoles.VIEWER; const collabOptions = { type: itemType }; client.collaborations .createWithGroupID(groupId, itemId, collabRole, collabOptions) .then((collaboration) => { console.log( `Content added with collaboration ID ${collaboration.id}` ); }) .catch(function (err) { console.log( util.inspect(err.response.body, { showHidden: false, depth: null, }) ); }); } }); }); } ``` Replace the `processContent` method with the following. ``` public void processContent(JSONObject userResponse, String channel, String fType, String fId) { String groupId = getGroupId(channel); JSONObject userObj = (JSONObject) userResponse.get("user"); JSONObject userProfile = (JSONObject) userObj.get("profile"); String userEmail = (String) userProfile.get("email"); Iterable<BoxUser.Info> users = BoxUser.getAllEnterpriseUsers(this.boxAPI, userEmail); for (BoxUser.Info user : users) { if (user.getLogin().toUpperCase().equals(userEmail.toUpperCase())) { String uid = user.getID(); boxAPI.asUser(uid); BoxCollaborator collabGroup = new BoxGroup(boxAPI, groupId); try { if (fType.equals("file")) { BoxFile file = new BoxFile(boxAPI, fId); file.collaborate(collabGroup, BoxCollaboration.Role.VIEWER, false, false); } else if (fType.equals("folder")) { BoxFolder folder = new BoxFolder(boxAPI, fId); folder.collaborate(collabGroup, BoxCollaboration.Role.VIEWER); } } catch (Exception ex) { System.err.println("Collaboration failed"); } boxAPI.asSelf(); } } } ``` # Incomplete previous step Please select a preferred language / framework in step 1 to get started. The code starts by capturing the Box group ID for the Slack channel, which is where content will be shared to. Since we want to share files and folders from the Box account of the person who sent the slash command, we next capture their Box user profile based on their email address. Lastly, we make a call to collaborate content with the group via the group ID. ## Summary - You've instantiated a Box client - You've created Box group user add and remove functions. - You've created a function to share content with the group. I've set up my Box functions **Reference:** https://developer.box.com/guides/collaborations/connect-slack-to-group-collabs/connect-box-functions/ --- ## Untitled *Type: quick-start | Category: Collaborations * Configure Box We will need to set up a Box application to manage Box groups and add collaborators to files and folders in Box. Set up a Box… # Configure Box We will need to set up a Box application to manage Box groups and add collaborators to files and folders in Box. ## Set up a Box app # Create a new Box app Create and configure a new Box JWT application to use for this integration. # Use an existing approved app Use one of your existing admin-approved Box JWT applications from the Box developer console. # Create a new Box app To create a new Box application that can be used to call the Box APIs, use the following steps. 1. Go to the [Developer Console](https://cloud.app.box.com/developers/console) 2. Select **Create New App** 3. Select **Platform App** as the type of application to create, and click **Next** 4. Select **OAuth 2.0 with JWT** as the authentication method, and click **Next** 5. Give your Box app a unique name and click **Create App** 6. Go to the app's configuration by clicking **View Your App**. 7. Scroll down to **Application Access** and ensure that **Enterprise** is selected. 8. Scroll to the **Application Scopes** section of the same screen and ensure that at least the following scopes are enabled: **Read and write all files and folders stored in Box**, **Manage users**, and **Manage groups**. 9. Under **Advanced Features** ensure that **Perform Actions as Users** is enabled to perform actions on behalf of Box users. 10. At the top of the page click the button to **Save Changes** # App approval Once the application is created it will still need to be approved by an enterprise admin before you will be able to make calls to the Box APIs. Follow [this guide](g://authorization/custom-app-approval) to have the application approved in your enterprise. # Use an Existing JWT Box application If you have an existing JWT based Box application in your [developer console](https://cloud.app.box.com/developers/console) that you would like to use, ensure that the following options are set in the **Configuration** section of your application. Authentication Method: Should be set to OAuth 2.0 with JWT (Server Authentication). Application Scopes: Set at least the following scopes. - Read and write all files and folders stored in Box - Manage users - Manage groups Advanced Features: Both options should be enabled to perform actions as users and generate user access tokens. # App approval Once the application is updated it will need to be re-approved by an enterprise admin before you will be able to make calls to any of the Box APIs that need any of the new permissions. Follow [this guide](g://authorization/custom-app-approval) to have the application approved in your enterprise. ## Download app configuration To begin working with the Box SDKs used in this tutorial, you will need the application configuration file from the **Configuration** page of your application. This will include all information needed to verify your application to start making API requests with the Box SDKs. Within the **Add and Manage Public Keys** section of the **Configuration** page, click to **Generate a Public/Private Keypair**. This will send you through 2FA verification before downloading the configuration file for your application. Store that file as `boxConfig.json` in a location accessible by your application. ## Summary - You created a new, or are using an existing, Box app which is approved by an enterprise admin. - You downloaded your application configuration file and stored it in a location accessible by your application. I downloaded my application configuration file **Reference:** https://developer.box.com/guides/collaborations/connect-slack-to-group-collabs/configure-box/ --- ## Untitled *Type: quick-start | Category: Collaborations * Connect Slack to Box Group Collaborations Slack is a popular communication and productivity tool, allowing for real-time coordination when… # Connect Slack to Box Group Collaborations Slack is a popular communication and productivity tool, allowing for real-time coordination when working with individuals or groups in and outside of the company. When connected to a custom Box application, the Slack channel structure, along with the [slash command](https://api.slack.com/apps/A0155185TT3/slash-commands) and [event API](https://api.slack.com/events-api) systems, can be used to provide a logical grouping and collaboration system for Box files and folders. ## Overview This quick start guide will walk you through all the steps needed to group Box users based on the channels they are in within a Slack workspace, and then permit individuals within those Slack channels to share Box files and folders with that group using a Slack slash command. At the end of this tutorial you will have a Slack bot that will be deployed to a channel in your workspace. This bot will create a Box group containing all the people present in the channel, and then listen for a `/boxadd` command in the channel. It will then parse that command and automatically collaborate the Box fie or folder with the entire group of users in the channel. This guide will take you through the following steps. 1. [Setup and configure your Slack app](g://collaborations/connect-slack-to-group-collabs/configure-slack) to handle the event notification and Slash command structures. 2. [Setup and configure your Box application](g://collaborations/connect-slack-to-group-collabs/configure-box) to connect the web application to Box. 3. [Listen for Slack events and commands](g://collaborations/connect-slack-to-group-collabs/scaffold-application-code) when users join and leave channels, or share a Box file or folder with the group. 4. [Structure Box groups and file / folder collaborations](g://collaborations/connect-slack-to-group-collabs/handle-slack-events) based on the Slack events or slash commands. 5. [And finally, deploy the application to your workspace](g://collaborations/connect-slack-to-group-collabs/connect-box-functions) and invite the Slack app bot to your channels to begin listening for events. ## Requirements This quick start guide has two requirements that are worth noting before we proceed. 1. **User emails need to match between Box and Slack**: We are connecting a Slack user account to a Box user account by comparing the Slack user email address. Therefore, a matching Box user account using the same email address must be present in your Box enterprise. 2. **You must have a publicly accessible server**: Slack will need to send event and command notification data to a public URL for your application. This guide assumes that you have a public location where your application code will be hosted, such as `https://mysite.com/`. If you don't have access to any public hosting then application platforms like [Heroku](https://heroku.com/), serverless options like [AWS lambda](https://aws.amazon.com/lambda/), or exposing localhost with services like [ngrok](https://ngrok.com/) are all options that you might want to consider. I am ready to get started **Reference:** https://developer.box.com/guides/collaborations/connect-slack-to-group-collabs/ --- ## Untitled *Type: quick-start | Category: Collaborations * Handle Slack Events With the application scaffold in place, the next step is to build the handling and processing functionality for user… # Handle Slack Events With the application scaffold in place, the next step is to build the handling and processing functionality for user events, as well as the handling of slash commands coming from Slack. Each one of these will eventually be passed to a Box API endpoint to perform group and content collaboration tasks. In this step we'll expand the empty functions we wrote in the last step. These functions will perform the following tasks. - Listen for new events and slash commands from Slack. - Process those events and commands to route to the appropriate function. - Process all Slack users in a channel to be added to a Box group when the bot is first added to a channel. - Fetch profile information for a Slack user to get their email. ## Listen for Slack events When the Slack application was configured, it was instructed to send events to our application code for three events. - When a user joins a channel. - When a user leaves a channel. - When a user enters a `/boxadd` Slash command. Our application needs to have a public route that listens for those messages from Slack. The payloads of these messages will like something like this. ``` { "token": "cF1PwB1eIMcRHZWwFHJR1tgs", "team_id": "T932DQSV12P", "team_domain": "slacktest", "channel_id": "C078N43MFHU", "channel_name": "bottest", "user_id": "U016JCDPN56", "user_name": "testuser", "command": "/boxadd", "text": "file 123456", "response_url": "https://hooks.slack.com/commands/T541DQSV12P/3977594927231/ankvsRb42WKnKPRp002FeyTx", "trigger_id": "1189442196855.1183332180295.cca20c3ca1ea193dab432ad8e9e95431" } ``` ``` { "token": "cF1PwB1eIMcRHZWwFHJR1tgs", "team_id": "T932DQSV12P", "api_app_id": "A321V573PQT", "event": { "type": "member_joined_channel", "user": "U0431JM4RLZ", "channel": "C078N43MFHU", "channel_type": "C", "team": "T932DQSV12P", "inviter": "U016JCDPN56", "event_ts": "1592858788.000700" }, "type": "event_callback", "event_id": "Ev032NRJYASJ", "event_time": 1592858788, "authed_users": [ "U0431JM4RLZ" ] } ``` ``` { "token": "cF1PwB1eIMcRHZWwFHJR1tgs", "team_id": "T932DQSV12P", "api_app_id": "A321V573PQT", "event": { "type": "member_left_channel", "user": "U0431JM4RLZ", "channel": "C078N43MFHU", "channel_type": "C", "team": "T932DQSV12P", "event_ts": "1593033236.000600" }, "type": "event_callback", "event_id": "Ev032NRJYASJ", "event_time": 1593033236, "authed_users": [ "U0431JM4RLZ" ] } ``` To start processing these events, load `process.js` in your preferred editor and replace the `app.post("/event" ...` listener with the following. ``` app.post("/event", (req, res) => { if (req.body.token !== slackConfig.verificationToken) { res.send("Slack Verification Failed"); } handler.process(res, req.body); }); ``` When an event comes through, the listener verifies that the message came from Slack, using the verification token from our Slack application. If it's a valid request, the event payload is sent to our event process function. Load `Application.java` in your preferred editor, then replace the `@PostMapping("/event")` block with the following. ``` @PostMapping("/event") @ResponseBody public void handleEvent(@RequestBody String data, @RequestHeader("Content-Type") String contentType, HttpServletResponse response) throws Exception { int code = HttpServletResponse.SC_OK; java.io.PrintWriter wr = response.getWriter(); response.setStatus(code); if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) { wr.write("Adding content to group"); } else { wr.print(response); } wr.flush(); wr.close(); if (! contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) { JSONObject returnJSON = new JSONObject(); String[] inputParts = data.split("&"); for (String part: inputParts) { String[] keyval = part.split("="); try { keyval[1] = java.net.URLDecoder.decode(keyval[1], StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { System.err.println(e); } returnJSON.put(keyval[0], keyval[1]); } data = returnJSON.toString(); } processEvent(data); } ``` When an event comes through, the handler will send an immediate 200 response back before code processing. Slash commands will be sent as URL encoded strings, while member join / leave events will be sent as JSON. If a slash command is encountered we respond with a processing message, otherwise we send the `HttpServletResponse` response. In this example we send a `HTTP 200` response before the event is fully processed. This is done because Slack requires a response to an event within 3 seconds from dispatch. When the code execution takes longer than 3 seconds then duplicate event will be dispatched by Slack. To make event processing easier, we want to standardize all event objects as JSON. If a content type isn't JSON it'll be the URL encoded string. If that's encountered the string is converted into a JSON object before being sent to `processEvent`. Replace `processEvent` with the following. ``` @Async public void processEvent(String data) throws Exception { Object dataObj = new JSONParser().parse(data); JSONObject inputJSON = (JSONObject) dataObj; String token = (String) inputJSON.get("token"); if (token.equals(slackConfig.verificationToken)) { // INSTANTIATE BOX CLIENT process(inputJSON); } else { System.err.println("Invalid event source"); } } ``` This method will convert the JSON event string to a JSON object, then verify that the event came from Slack by comparing the verification token. If valid, the event is routed to `process`. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Process Slack events Next, we will want to determine what event was received and pass this on to the right part of our application. Replace the `process` function with the following. ``` function process(res, data) { if (data.type && data.type === "event_callback") { const eventType = data.event.type; const channel = data.event.channel; const userId = data.event.user; getSlackUser(userId, function (user) { processUser(user, eventType, channel); }); res.send(); } else if (data.command && data.command === "/boxadd") { const [itemType, itemId] = data.text.split(" "); if (["file", "folder"].includes(itemType) && !isNaN(itemId)) { const userId = data.user_id; getSlackUser(userId, function (user) { processContent(user, data.channel_id, itemType, itemId); }); res.send("Adding content"); } else { res.send("Invalid input. Example usage: /boxadd file 123456"); } } else { res.send("Invalid action"); } } ``` The purpose of this function is to figure out if the payload from Slack is a user event or a Slash command, fetch any needed information, then route to the appropriate function to process the results. If the payload is a user event, denoted by `data.type` being set to `event_callback`, we extract a few pieces of information. - `eventType`: The type of event to determine if a user is leaving (`member_left_channel`) or joining (`member_joined_channel`) the channel. - `channel`: The channel ID, which will be used as the Box group name. - `userId`: The ID of the user, to look up their profile email which will bind to a user profile in Box that uses the same email. The process function then fetches the profile of the user by calling `getSlackUser`, and once obtained that user profile is sent to the `processUser` function to add or remove them from the Box group. If the payload is a slash command, denoted by `data.command` being set to `/boxadd`, the content of the command that represents the Box ID and whether it's a file or folder, such as `file 1234`, is extracted and split to get the individual values. Those values are validated for proper content. Once validated, the profile of the Slack user is obtained to get the email, then the user profile is sent to `processContent` to collaborate the Box content in with the Box group so that everyone has access. The reason for fetching the Slack user's email in this step is because the file or folder is owned by the user, not by the application's service account. When we share content (by creating a collaboration) the action will need to be performed by a user who has sharing permissions on that file or folder. For this reason, we need to match the Slack user's email address against a Box user's email address so that we can create the collaboration on their behalf. Replace the `process` method with the following. ``` public void process(JSONObject inputJSON) throws Exception { if (inputJSON.containsKey("event")) { JSONObject event = (JSONObject) inputJSON.get("event"); String eventType = (String) event.get("type"); String eventUserId = (String) event.get("user"); String eventChannel = (String) event.get("channel"); processUser(getSlackUser(eventUserId), eventType, eventChannel); } else if (inputJSON.containsKey("command")) { String eventCommand = (String) inputJSON.get("command"); if (eventCommand.equals("/boxadd")) { String eventChannelId = (String) inputJSON.get("channel_id"); String eventUserId = (String) inputJSON.get("user_id"); String cInput = (String) inputJSON.get("text"); String[] cInputParts = cInput.split(" "); if (cInputParts[0].matches("file|folder")) { processContent(getSlackUser(eventUserId), eventChannelId, cInputParts[0], cInputParts[1]); } } } else { System.err.println("Invalid event action"); } } ``` The purpose of this method is to figure out if the payload from Slack is a user event or a Slash command, fetch any needed information, then route to the appropriate method to process the results. If the payload is a user event, denoted by the event node being present in the JSON payload, we extract a few pieces of information. - `eventType`: The type of event to determine if a user is leaving (`member_left_channel`) or joining (`member_joined_channel`) the channel. - `eventUserId`: The ID of the user, to look up their profile email which will bind to a user profile in Box that uses the same email. - `eventChannel`: The channel ID, which will be used as the Box group name. We then route to `processUser`, passing in the return value from the `getSlackUser` method (a user object), the type of event, and the channel. If the payload is a slash command, denoted by the `command` node being present in the JSON payload, we extract a few pieces of information. - `eventChannelId`: The Slack channel ID, to be used as the Box group name. - `eventUserId`: The ID of the user who issued the command. - `cInputParts`: The type and ID of the command input, from a string such as `file 1234`. We then route to `processContent`, passing in the return value from the `getSlackUser` method (a user object), the channel ID, the content type (file or folder), and the content ID for the file or folder stored in Box. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Process Slack user Next, we need to define how user events should be processed. There are three events that we need to account for: - The bot was added to the channel. - A regular user joined the channel. - A regular user left the channel. Replace the `processUser` function with the following. ``` function processUser(user, event, channel) { getGroupId(channel, function (groupId) { // if bot was added, add all channel users if (user.is_bot) { processSlackChannel(channel, groupId); } else if ( user.profile && user.profile.email && event === "member_joined_channel" ) { addGroupUser(groupId, user.profile.email); } else if ( user.profile && user.profile.email && event === "member_left_channel" ) { removeGroupUser(groupId, user.profile.email); } }); } ``` Replace the `processUser` method with the following. ``` public void processUser(JSONObject userResponse, String event, String channel) throws Exception { String groupId = getGroupId(channel); JSONObject userObj = (JSONObject) userResponse.get("user"); Boolean isBot = (Boolean) userObj.get("is_bot"); JSONObject userProfile = (JSONObject) userObj.get("profile"); String userEmail = (String) userProfile.get("email"); if (isBot) { processSlackChannel(channel, groupId); } else if (event.equals("member_joined_channel")) { addGroupUser(groupId, userEmail); } else if (event.equals("member_left_channel")) { removeGroupUser(groupId, userEmail); } } ``` # Incomplete previous step Please select a preferred language / framework in step 1 to get started. The code starts by fetching the Box group ID for the channel, which will be defining in the next step. Once obtained, it processes users as follows. - If the user is a bot, it needs to initialize the Box group and add all current users of the channel as Box users in the group. This is to account for the bot being added to existing channels, and this is ignored if the bot is being re-added to a channel that they were already present in previously. - If the user joined the channel it needs to add them to the group. - If the user left the channel it needs to remove them from the group. ## Process Slack channel users When a bot is first added to a channel, it needs to list all users currently in the channel and create a Box group with those people in order to create a baseline for the channel. Replace the `processSlackChannel` function with the following. ``` function processSlackChannel(channel, groupId) { const limit = 100; const channelUsersPath = `https://slack.com/api/conversations.members?token=${slackConfig.botToken}&channel=${channel}&limit=${limit}`; axios.get(channelUsersPath).then((response) => { response.data.members.forEach((uid) => { getSlackUser(uid, function (user) { if (user.profile.email && !user.is_bot) { addGroupUser(groupId, user.profile.email); } }); }); }); } ``` Replace the `processSlackChannel` method with the following. ``` public void processSlackChannel(String channel, String groupId) throws Exception { String limit = "100"; String channelUsersPath = String.format("%s/conversations.members?token=%s&channel=%s&limit=%s", slackConfig.slackApiUrl, slackConfig.botToken, channel, limit); JSONObject channelUserList = sendGETRequest(channelUsersPath); JSONArray channelUserIds = (JSONArray) channelUserList.get("members"); @SuppressWarnings("rawtypes") Iterator i = channelUserIds.iterator(); while(i.hasNext()) { String uid = (String)i.next(); JSONObject userResponse = (JSONObject) getSlackUser(uid.toString()); JSONObject userObj = (JSONObject) userResponse.get("user"); JSONObject userProfile = (JSONObject) userObj.get("profile"); Boolean isBot = (Boolean) userObj.get("is_bot"); String userEmail = new String(); if (!isBot) { userEmail = (String) userProfile.get("email"); } if (!userEmail.isEmpty() && !isBot) { addGroupUser(groupId, userEmail); } } } ``` # Incomplete previous step Please select a preferred language / framework in step 1 to get started. This code runs a number of actions in sequence. - First, it calls the Slack APIs to fetch all members of the channel. The - `limit` can be adjusted to collect more users in the channel. - For every user that is found, it calls `getSlackUser` to get their profile, allow it to map their email address to a Box user's email address. - Each user is then sent to `addGroupUser` to add them into the group. ## Fetch Slack user profile The last Slack related function is a utility mechanism used by the other functions. It calls the Slack API to fetch the user profile given the user ID provided by either Slack event / command or when fetching a list of channel users. Since we're matching Slack users to Box users via their email address, that is the field that we care about from the user profile lookup. Email addresses in Box are unique and cannot be used for multiple accounts, meaning that they can be used effectively for user account lookup. Replace the `getSlackUser` function with the following. ``` function getSlackUser(userId, callback) { const userPath = `https://slack.com/api/users.info?token=${slackConfig.botToken}&user=${userId}`; axios.get(userPath).then((response) => { if (response.data.user && response.data.user.profile) { callback(response.data.user); } else { console.log("No user data found"); } }); } ``` This function makes a call to the Slack user profile endpoint, then sends the user profile information (if valid) to the specified callback. Replace the `getSlackUser` method with the following. ``` public JSONObject getSlackUser(String userId) throws Exception { String usersPath = String.format("%s/users.info?token=%s&user=%s", slackConfig.slackApiUrl, slackConfig.botToken, userId); return sendGETRequest(usersPath); } ``` This method sends a request to Slack to capture the user profile, then returns the response from that request, which should be a user profile JSON object. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Summary - You've verified incoming events and forwarded them to be processed. - You've processed events and routed to the appropriate function. - You've implemented functions for processing all users in a channel and for fetching the Slack profile of a single user. I've set up my Slack functions **Reference:** https://developer.box.com/guides/collaborations/connect-slack-to-group-collabs/handle-slack-events/ --- ## Untitled *Type: quick-start | Category: Collaborations * Scaffold application code With our Slack and Box applications configured, we're ready to write the code for our application which will… # Scaffold application code With our Slack and Box applications configured, we're ready to write the code for our application which will listen for incoming slash commands and events from Slack. This application will be split up into three parts: - Set up the initial application skeleton and configuration information. - Set up the handlers for Slack events and slash commands. - Connect those handlers to the required functions in Box. ## Add dependencies and scaffold code Let's start by scaffolding the files and minimal code needed to run the application. - Either create a new local directory for your application or load the existing code created for the Slack event URL challenge from [step 1](g://collaborations/connect-slack-to-group-collabs/configure-slack). - Create a new `package.json` file, or update the existing one, inside the local directory, open it in your preferred editor, copy / paste the following into it, and save / exit the file. ``` { "name": "box-slack", "version": "1.0.0", "description": "Box Slack integration", "main": "process.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node process.js" }, "author": "Box", "license": "ISC", "dependencies": { "axios": "^0.19.2", "body-parser": "^1.19.0", "box-node-sdk": "^1.33.0", "express": "^4.17.1" } } ``` - Run `npm install` from the terminal / console to install the dependencies. - Create two files, `process.js` and `slackConfig.json` in the local directory. - Open `slackConfig.json` and save the following default configuration. ``` { "verificationToken": "TOKEN", "botToken": "TOKEN" } ``` There are two values above that will need to be replaced with details from your Slack application. Replace the `TOKEN` strings with the appropriate values. - `verificationToken`: Load up your Slack application configuration page. Within the **Basic Information** page, scroll down to the **App Credentials** section. The **Verification Token** string will be available there. - `botToken`: Within your Slack application, go to the **OAuth & Permissions** page. The **Bot User OAuth Access Token** string is available at the top and was auto-populated once the bot was added to your Slack workspace. Open up the blank `process.js` file, copy and paste the following code, and save the file. ``` const box = require("box-node-sdk"); const slackConfig = require("./slackConfig.json"); const boxConfig = require("./boxConfig.json"); const express = require("express"); const app = express(); const axios = require("axios"); const util = require("util"); app.use(express.urlencoded({ extended: true })); app.use(express.json()); // INSTANTIATE BOX CLIENT app.post('/event', (req, res) => { //HANDLE INCOMING EVENTS }); const handler = (() => { function process(res, data) { // PROCESS EVENTS } function processUser(user, event, channel) { // PROCESS USER ADD / REMOVE REQUEST } function addGroupUser(groupId, email) { // ADD USER TO BOX GROUP } function removeGroupUser(groupId, email) { // REMOVE USER FROM BOX GROUP } function processContent(user, channel, type, fid) { // COLLABORATE CONTENT WITH GROUP } function processSlackChannel(channel, gid) { // ADD ALL SLACK CHANNEL USERS TO GROUP } function getSlackUser(userId, _callback) { // GET SLACK USER PROFILE } function getGroupId(groupName, _callback) { // GET AND CREATE BOX GROUP } return { process }; })(); const port = process.env.PORT || 3000; app.listen(port, function(err) { console.log("Server listening on PORT", port); }); ``` This code contains all of the main functions that will be needed to handle and process the communication between Slack and Box. From top to bottom, the functions are: - `/event` handler: Captures all incoming Slack traffic, verifies the content, and routes them to the `process` function. - `process`: Parses the Slack event and routes the event to either Box group processing (user channel events) or to add Box content to the group (slash commands). - `processUser`: Handles user events, either adding or removing a user from a Box group by routing to the appropriate functions. - `addGroupUser`: Adds a user to a Box group. - `removeGroupUser`: Removes a user from a Box group. - `processContent`: Collaborates Box content with the Box group. - `processSlackChannel`: Adds all Slack channel users to a Box group. - `getSlackUser`: Utility function to fetch a Slack user's profile from their Slack user ID. - `getGroupId`: Utility function to fetch a Box group ID from a Box group name. A configuration file needs to be created to house our Slack credentials and URLs. - Within your `src/main/java` path, where your `Application.java` file is located, create a new Java class file named `slackConfig.java`. - Open the file and save the following into it. ``` package com.box.slack.box; public class slackConfig { public static String verificationToken = "TOKEN"; public static String botToken = "TOKEN"; public static String slackApiUrl = "https://slack.com/api"; } ``` There are two values above that will need to be replaced with details from your Slack application. Replace the `TOKEN` strings with the appropriate values. - `verificationToken`: Load up your Slack application configuration page. Within the **Basic Information** page, scroll down to the **App Credentials** section. The **Verification Token** string will be available there. - `botToken`: Within your Slack application, go to the **OAuth & Permissions** page. The **Bot User OAuth Access Token** string is available at the top and was auto-populated once the bot was added to your Slack workspace. Open up the `Application.java` file that was created for the previous Slack event challenge setup and replace the content of the file with the following. ``` package com.box.slack.box; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Iterator; import javax.servlet.http.HttpServletResponse; import org.jose4j.json.internal.json_simple.JSONArray; import org.jose4j.json.internal.json_simple.JSONObject; import org.jose4j.json.internal.json_simple.parser.JSONParser; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.http.MediaType; import org.springframework.scheduling.annotation.Async; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.box.sdk.BoxAPIConnection; import com.box.sdk.BoxCollaborator; import com.box.sdk.BoxCollaboration; import com.box.sdk.BoxConfig; import com.box.sdk.BoxDeveloperEditionAPIConnection; import com.box.sdk.BoxFile; import com.box.sdk.BoxFolder; import com.box.sdk.BoxGroup; import com.box.sdk.BoxGroupMembership; import com.box.sdk.BoxUser; @RestController @EnableAutoConfiguration public class Application extends slackConfig { private Reader fileReader; private BoxConfig boxConfig; private BoxAPIConnection boxAPI; @PostMapping("/event") @ResponseBody public void handleEvent(@RequestBody String data, @RequestHeader("Content-Type") String contentType, HttpServletResponse response) throws Exception { // HANDLE EVENTS } @Async public void processEvent(String data) throws Exception { // VERIFY EVENTS } public void process(JSONObject inputJSON) throws Exception { // PROCESS EVENTS } public void processUser(JSONObject userResponse, String event, String channel) throws Exception { // PROCESS USER ADD / REMOVE REQUEST } public void addGroupUser(String groupId, String userEmail) { // ADD USER TO BOX GROUP } public void removeGroupUser(String groupId, String userEmail) { // REMOVE USER FROM BOX GROUP } public void processContent(JSONObject userResponse, String channel, String fType, String fId) { // COLLABORATE CONTENT WITH GROUP } public void processSlackChannel(String channel, String groupId) throws Exception { // ADD ALL SLACK CHANNEL USERS TO GROUP } public JSONObject getSlackUser(String userId) throws Exception { // GET SLACK USER PROFILE } public String getGroupId(String groupName) { // GET AND CREATE BOX GROUP } public JSONObject sendGETRequest(String reqURL) throws Exception { StringBuffer response = new StringBuffer(); URL obj = new URL(reqURL); HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection(); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); String inputLine; while ((inputLine = in .readLine()) != null) { response.append(inputLine); } in .close(); } else { System.err.println("GET request failed"); } Object dataObj = new JSONParser().parse(response.toString()); JSONObject outputJSON = (JSONObject) dataObj; return outputJSON; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` This code contains all of the main functions that will be needed to handle and process the communication between Slack and Box. From top to bottom, the functions are: - `handleEvent`: Captures all incoming Slack traffic and responds with an HTTP 200 response to notify Slack that the event was received. Since slash commands will transmit their payload as `application/x-www-form-urlencoded` rather than `application/json`, we convert those payloads to JSON objects to standardize the input. - `processEvent`: Verifies that the event is from Slack, instantiates a Box client, and routes for processing. - `process`: Parses the Slack event and routes to either Box group processing (user channel events) or to add Box content to the group (slash commands). - `processUser`: Handles user event requirements to either add or remove a user to a Box group by routing to the appropriate functions. - `addGroupUser`: Adds a user to a Box group. - `removeGroupUser`: Removes a user from a Box group. - `processContent`: Collaborates Box content with the Box group. - `processSlackChannel`: Adds all Slack channel users to a Box group. - `getSlackUser`: Utility function to fetch a Slack user profile from a Slack user ID. - `getGroupId`: Utility function to fetch a Box group ID from a Box group name. - `sendGETRequest`: Utility function to send an HTTP GET request. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Summary - You created a minimal application scaffold, and provided the basic configuration details. - You installed all the project dependencies. I have my local application set up **Reference:** https://developer.box.com/guides/collaborations/connect-slack-to-group-collabs/scaffold-application-code/ --- ## Untitled *Type: quick-start | Category: Collaborations * Test the bot In this last section we'll test the full range of functionality of the Slack bot. Group creation: When a bot is added to a… # Test the bot In this last section we'll test the full range of functionality of the Slack bot. - **Group creation**: When a bot is added to a channel, a new Box group should be created with all of the current channel participants. Only those people in the channel with matching Box accounts (based on email address matching) should be added. - **User event functions**: When a user enters or leaves a channel, they should be added or removed from the channel group. - **Content add functions**: When a user enters a valid `/boxadd` slash command, that content should be shared with the group through a new collaboration. If you haven't done so already, ensure that all the code we've written so far is deployed as an application that is publicly accessible. ## Testing group creation When a bot is first added to a channel, there are a number of expectations. - A new group is created with a name that matches the Slack channel ID. - All people currently in the channel are added to the group, as long as their Slack email address matches an enterprise account with the same email. When the Slack bot was configured in [step 1](g://collaborations/connect-slack-to-group-collabs/configure-slack), we installed it within the Slack workspace. To test group creation we need to add it to a channel. From any Slack channel, invite the Slack bot, either through the Slack UI or using a `/invite @bot_app_name` command. Once added, verify that the group is created in Box and members have been added. From a Box enterprise admin account, go to the **[Users and Groups](https://app.box.com/master/groups)** section of the admin console. If successful, you will see a group with an random alpha-numeric string as the group name. This is the Slack channel ID, which is mirrored in the group name. Under the **Members** column, you should also see a number indicating the number of Box users with matching email addresses that were found in the enterprise and added to the group during group creation. If you see your group and members, this step is a success. If you see no members added to the group, and no errors being returned from the bot application, the most likely cause is email mismatch. Ensure that the email addresses used by the accounts in Slack match the emails used by users in your Box enterprise. ## Testing user event functions Keep the **[Users and Groups](https://app.box.com/master/groups)** section of the Box admin console open and take note of the number in the **Members** column beside your Slack group. From the Slack channel with the bot invited, add or remove someone other than the bot from the channel. Refresh the users and groups section of the Box admin console and you should see the members number drop or increase depending on if you added or removed a user. If the number of members changes, this step is a success. ## Testing content add functions To test the functionality of sharing content with the group, you will need access to two users in the channel, one person to share the content from their Box account, and another person in the group to view their list of files to verify that the content was shared. From the Slack channel with the bot invited, type in the slash command to share files or folders with the group, in the format of `/boxadd [file/folder] [ID of file/folder]`, such as `/boxadd folder 324554221`. The file or folder ID specified needs to be content within the Box account of the person sharing it. To find the ID of a file or folder in a Box account, load up the file or folder within [the Box site](https://box.com), then look at the URL. The ID will be the last string in the URL, often right after a section which includes either `/file/` or `/folder/`. Once the command is typed in, go to the [the Box site](https://box.com) account of another person within the Slack channel and Box group. The content that was shared should now be available to that account. If the shared content is available to others in the group, this step is a success. ## Next Steps With our minima bot deployed we can now think about ways to improve the experience on top of what we've created so far. Next steps in this journey may include any number of different expansion areas. - Add new slash commands for [creating shared links](g://shared-links/create-or-update) for the files and folders shared with the group, allowing you to share the content with others who are not in the group and people outside your enterprise. - [Creating retention policies](e://post-retention-policies) and [assigning them](e://post-retention-policy-assignments) to any content shared with the group, allowing you to control the lifespan and governance of shared content. - Adding new slash commands for allowing people in the channel to [comment on the files](e://post-comments) that are shared with the group. **Reference:** https://developer.box.com/guides/collaborations/connect-slack-to-group-collabs/test-bot/ --- ## Untitled *Type: guide | Category: Events * Migrating From History To Stream Box recommends that applications subscribing to live events through admin_logs migrate to admin_logs… # Migrating From History To Stream Box recommends that applications subscribing to live events through `admin_logs` migrate to `admin_logs_streaming`. `admin_logs_streaming` provides lower and more consistent latency, as well as ensures that late arriving events will not be missed. Events can be deduplicated between `admin_logs` and `admin_logs_streaming` by their event IDs. ## Enterprise stream_type comparison ### Benefits of admins_logs_streaming - Ensures late arriving events are not missed by your subscribing application - Provides 80% lower latency (during normal operations) - Has much more consistent latency (during normal operations) - Recovers much more gracefully from a fault, because your service no longer has to manage backfilling late events ### Differences between admin_logs and admin_logs_streaming - Provides two weeks of event history (i.e. retention) - Does not support the `created_after` and `created_before` filter parameters - May contain duplicates (provides an 'at least once' guarantee) - No longer returns events in chronological order (events are returned in roughly the order they are processed) ### Similarities between admin_logs and admin_logs_streaming - Shares the same [`GET /events`](e://events) API endpoint - Returns the same events payload (events can be deduplicated across the two stream types by event ID) - Enables filtering by `event_type` - Allows paginating through events via a `stream_position` ## How to migrate from admin_logs to admin_logs_streaming ### 1. Existing requests will look something like the below ``` curl https://api.box.com/2.0/events?stream_type=admin_logs&stream_position=1632893855 \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ### 2. Begin overlapping existing requests with admin_logs_streaming Start two weeks ago and backfill: ``` curl https://api.box.com/2.0/events?stream_type=admin_logs_streaming&stream_position=0 \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` or Start now and run in parallel: ``` curl https://api.box.com/2.0/events?stream_type=admin_logs_streaming&stream_position=now \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ### 3. Paginate through results until now and deduplicate with admin_logs events ``` curl https://api.box.com/2.0/events?stream_type=admin_logs_streaming&stream_position=1632893855 \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ### 4. Continue to overlap until confident ### 5. Turn off old admin_logs requests **Reference:** https://developer.box.com/guides/events/enterprise-events/migrate-to-stream/ --- ## Untitled *Type: guide | Category: Events * Get Enterprise Events To get a enterprise's events, make a call to the GET /events API with the stream_type set to admin_logs or admin_logs… # Get Enterprise Events To get a enterprise's events, make a call to the [`GET /events`](e://get_events) API with the `stream_type` set to `admin_logs` or `admin_logs_streaming`. This API requires the user to be an enterprise admin or co-admin with the permission to **Run new reports and access existing reports**. ## Stream Types | Stream Type | | | --- | --- | | admin_logs | Enables querying historical events up to one year | | admin_logs_streaming | Enables subscribing to live events in near real time | ## Live Monitoring To monitor recent events that have been generated within Box across the enterprise, set the `stream_type` to `admin_logs_streaming`. This is also known as the Enterprise Event Stream API. The emphasis for this feed is on low latency rather than chronological accuracy, which means that Box may return events more than once and out of chronological order. Events are returned via the API in near real time after they are processed by Box. A small delay/buffer ensures that new events are not written after your cursor position. Only two weeks of events are available via this `stream_type`. ## Historical Querying To query historical events across the enterprise up to one year old, set the `stream_type` to `admin_logs`. This is also known as the Enterprise Event History API. The emphasis for this feed is on completeness over latency, which means that Box will deliver admin events in chronological order and without duplicates, but with higher latency than the user or `admin_logs_streaming` feed. Consuming events in near real time may lead to missed events as events can arrive later than your filtering window. ## Anonymous Users In some cases, the event feed might list a user with an ID of `2`. This is Box's internal identifier for anonymous users. An anonymous user is a user that is not logged in. This can happen any time a user interacts with content and they aren't asked to log in first. An example would be when a user downloads a file through an open shared link. ## Limitations The enterprise event feed does not support long polling. Box does not store events indefinitely. Two weeks of enterprise events are available when `stream_type` is set to `admin_logs_streaming`. One year of enterprise events are available when `stream_type` is set to `admin_logs`. Seven years of enterprise events are available via the Box Admin Console’s [exported reports](https://support.box.com/hc/en-us/articles/360043696534-Running-Reports). The emphasis of the `admin_logs_streaming` feed is to return the complete results quickly, which means that Box may return events more than once and out of order. Duplicate events can be identified by their event IDs. ## Filter by Event Type The enterprise event feed supports filtering by event type. A full list of event types can be found below. ## Event Types The following events can be triggered for an enterprise. This list is not exhaustive, so it is possible events appear that are not listed. | Event name | Description | | --- | --- | | ACCESS_GRANTED | A user has granted Box support access to their account | | ACCESS_REVOKED | A user has revoked Box support access to their account | | ADD_DEVICE_ASSOCIATION | Added device association | | ADD_LOGIN_ACTIVITY_DEVICE | A user is logging in from a device we have not seen before | | ADMIN_LOGIN | Admin console used to log in to a managed user's account | | ANNOTATIONV2_CREATE | An annotation is created | | ANNOTATIONV2_DELETE | An annotation is deleted | | ANNOTATIONV2_EDIT | An annotation is edited | | APPLICATION_CREATED | A new application is created in the Box Developer Console | | APPLICATION_PUBLIC_KEY_ADDED | An application public key is added. | | APPLICATION_PUBLIC_KEY_DELETED | An application public key is deleted. | | BOX_AI_USER_REQUEST | User asks Box AI a question or makes a request | | BOX_AI_USER_FAILED_REQUEST | The question or request returns an error | | CHANGE_ADMIN_ROLE | When an admin role changes for a user | | CHANGE_FOLDER_PERMISSION | Edit the permissions on a folder | | COLLABORATION_ACCEPT | Accepted invites | | COLLABORATION_EXPIRATION | Set collaborator expiration | | COLLABORATION_INVITE | Invited | | COLLABORATION_REMOVE | Removed collaborators | | COLLABORATION_ROLE_CHANGE | Changed user roles | | COLLECTION_CREATE | A collection is created | | COLLECTION_DELETE | A collection is deleted | | COLLECTION_UPDATE | A collection is updated | | COLLECTION_ITEM_CREATE | An item is added to a collection | | COLLECTION_ITEM_DELETE | An item is removed from a collection | | COLLECTION_ITEM_UPDATE | An item in a collection is updated | | COMMENT_CREATE | A comment is created on a file | | COMMENT_DELETE | A comment is deleted on a file | | CONTENT_ACCESS | A file is accessed by an authorized end user or programmatically by a Box application | | CONTENT_RECOVERY_REPORT_CREATE | A Content Recovery report is created | | CONTENT_RECOVERY_REPORT_DELETE | A Content Recovery report is deleted | | CONTENT_RECOVERY_REPORT_INITIATE | A Content Recovery report is initiated | | CONTENT_WORKFLOW_ABNORMAL_DOWNLOAD_ACTIVITY | A policy set in the Admin console is triggered | | CONTENT_WORKFLOW_AUTOMATION_ADD | An automation is added | | CONTENT_WORKFLOW_AUTOMATION_DELETE | An automation is deleted | | CONTENT_WORKFLOW_POLICY_ADD | A content policy is added | | CONTENT_WORKFLOW_SHARING_POLICY_VIOLATION | There is a sharing policy violation. | | CONTENT_WORKFLOW_UPLOAD_POLICY_VIOLATION | A collaborator violated an admin-set upload policy | | COPY | Copied | | DATA_RETENTION_CREATE_RETENTION | Retention is created | | DATA_RETENTION_REMOVE_RETENTION | Retention is removed | | DELETE | Deleted | | DELETE_USER | Deleted user | | DEVICE_TRUST_CHECK_FAILED | Device Trust check failed | | DISABLE_MULTI_FACTOR_AUTH | When multifactor authentication has been disabled | | DOWNLOAD | Downloaded | | EDIT | Edited | | EDIT_USER | Edited user | | EDR_CROWDSTRIKE_DEVICE_DETECTED | Device detected by the CrowdStrike Falcon platform | | EDR_CROWDSTRIKE_NO_BOX_TOOLS | Box Tools package not detected on device with CrowdStrike Falcon platform support | | EDR_CROWDSTRIKE_BOX_TOOLS_OUTDATED | Box Tools package outdated on device with CrowdStrike Falcon platform support | | EDR_CROWDSTRIKE_DRIVE_OUTDATED | Box Drive application outdated on device with CrowdStrike Falcon platform support | | EDR_CROWDSTRIKE_ACCESS_ALLOWED_NO_CROWDSTRIKE_DEVICE | Access allowed to a device not identified by the CrowdStrike Falcon platform | | EDR_CROWDSTRIKE_ACCESS_REVOKED | Access revoked to a device identified by the CrowdStrike Falcon platform | | EMAIL_ALIAS_CONFIRM | A user email alias is confirmed | | EMAIL_ALIAS_REMOVE | A user email alias is removed | | ENABLE_MULTI_FACTOR_AUTH | When multifactor authentication has been enabled | | ENTERPRISE_APP_AUTHORIZATION_UPDATE | When a JWT application has been authorized or reauthorized | | EXTERNAL_COLLAB_SECURITY_SETTINGS | Changes in external collaboration security settings | | FAILED_LOGIN | Failed login | | FILE_MARKED_MALICIOUS | Virus found on a file. Event is only received by enterprises that have opted in to be notified. | | FILE_WATERMARKED_DOWNLOAD | A watermarked file is downloaded | | GROUP_ADD_ITEM | An item is added to a group | | GROUP_ADD_USER | Added user to group | | GROUP_ADMIN_CREATED | Group admin is created | | GROUP_ADMIN_DELETED | Group admin is deleted | | GROUP_ADMIN_PERMISSIONS_UPDATED | Group admin permissions are updated | | GROUP_CREATION | Created new group | | GROUP_DELETION | Deleted group | | GROUP_EDITED | Edited group | | GROUP_REMOVE_ITEM | Folders were removed from a group in the Admin console | | GROUP_REMOVE_USER | Removed user from group | | ITEM_EMAIL_SEND | An email is sent to a collaborator on an item | | ITEM_MODIFY | Item is modified | | ITEM_OPEN | Item is opened | | ITEM_SHARED_UPDATE | Share links settings updated | | ITEM_SYNC | Synced folder | | ITEM_UNSYNC | Unmarked folder for synced | | LEGAL_HOLD_ASSIGNMENT_CREATE | A legal hold assignment is created | | LEGAL_HOLD_ASSIGNMENT_DELETE | A legal hold assignment is deleted | | LEGAL_HOLD_POLICY_CREATE | A legal hold policy is created | | LEGAL_HOLD_POLICY_DELETE | A legal hold policy is deleted | | LEGAL_HOLD_POLICY_UPDATE | A legal hold policy is updated | | LOCK | Locked | | LOGIN | Login | | METADATA_INSTANCE_CREATE | Creation of metadata instance | | METADATA_INSTANCE_DELETE | Deletion of metadata instance | | METADATA_INSTANCE_UPDATE | Update of metadata instance | | METADATA_TEMPLATE_CREATE | Creation of metadata template | | METADATA_TEMPLATE_UPDATE | Update of metadata template | | METADATA_TEMPLATE_DELETE | Deletion of metadata template | | MOVE | Moved | | NEW_USER | Created user | | OAUTH2_ACCESS_TOKEN_REVOKE | An OAuth 2.0 access token has been revoked | | PREVIEW | Previewed | | REMOVE_DEVICE_ASSOCIATION | Removed device association | | REMOVE_LOGIN_ACTIVITY_DEVICE | We invalidated a user session associated with an app | | RENAME | A file or folder name or description is changed | | RETENTION_POLICY_ASSIGNMENT_ADD | A retention policy assignment is added | | SHARE | Enabled shared links | | SHARE_EXPIRATION | Set shared link expiration | | SHARED_LINK_SEND | An email is sent with a shared link and an optional message | | SHARED_LINK_REDIRECT_OUT_OF_SHARED_CONTEXT | Shared link causes a redirect | | SHIELD_ALERT | Shield detected an anomalous download, session, location, or malicious content based on enterprise Shield rules. See shield alert events for more information. | | SHIELD_DOWNLOAD_BLOCKED | End user blocked from downloading a file based on a shield access policy | | SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED | Access to an external collaboration is blocked | | SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED_MISSING_JUSTIFICATION | Access to an external collaboration is blocked due to missing a justification | | SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED | An invite to externally collaborate is blocked | | SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION | An invite to externally collaborate is blocked due to missing a justification | | SHIELD_EXTERNAL_COLLAB_INVITE_JUSTIFIED | An invite to externally collaborate is justified | | SHIELD_JUSTIFICATION_APPROVAL | A Shield justification is approved | | SHIELD_SHARED_LINK_ACCESS_BLOCKED | Access to a shared link is blocked | | SHIELD_SHARED_LINK_STATUS_RESTRICTED_ON_CREATE | A shared link is created and access to the content is restricted | | SHIELD_SHARED_LINK_STATUS_RESTRICTED_ON_UPDATE | A shared link is updated and access to the content is restricted | | SHIELD_INFORMATION_BARRIER_ENABLED | A Shield information barrier is enabled | | SHIELD_INFORMATION_BARRIER_DISABLED | A Shield information barrier is deactivated | | SHIELD_INFORMATION_BARRIER_PENDING | A Shield information barrier is not yet active | | SHIELD_INFORMATION_BARRIER_GROUP_ADD_USER_BLOCKED | Adding user blocked due to information barrier restrictions | | SHIELD_INFORMATION_BARRIER_COLLAB_BLOCKED | Creating collaborations for users blocked due to information barrier restrictions | | SHIELD_INFORMATION_BARRIER_SHARED_ITEM_ACCESS_BLOCKED | Access to shared items blocked for users due to information barrier restrictions | | SHIELD_INFORMATION_BARRIER_ITEM_MOVE_BLOCKED | Moving items blocked due to information barrier restrictions | | SHIELD_INFORMATION_BARRIER_ITEM_COPY_BLOCKED | Copying items blocked due to information barrier restrictions | | SHIELD_INFORMATION_BARRIER_ITEM_OWNER_TRANSFER_BLOCKED | Transferring items blocked due to information barrier restrictions | | SIGN_DOCUMENT_ASSIGNED | A sign request was sent to a signer | | SIGN_DOCUMENT_CANCELLED | A sign request was cancelled via API or UI | | SIGN_DOCUMENT_COMPLETED | A sign request was signed by all signers | | SIGN_DOCUMENT_CONVERTED | A sign request was converted to a .pdf for signing | | SIGN_DOCUMENT_CREATED | A sign request was created via API or UI. The document is not yet sent to signers | | SIGN_DOCUMENT_DECLINED | A sign request was declined by a signer | | SIGN_DOCUMENT_EXPIRED | A sign request expired with incomplete signatures | | SIGN_DOCUMENT_SIGNED | A sign request was signed by a signer | | SIGN_DOCUMENT_VIEWED_BY_SIGNER | A signer clicked on Review Document in the signer email or visited the signing URL | | SIGNER_DOWNLOADED | A signer downloaded the signing document | | SIGNER_FORWARDED | A signer forwarded the signing document | | STORAGE_EXPIRATION | Set file auto-delete | | TASK_ASSIGNMENT_UPDATE | Update of a task assignment | | TASK_ASSIGNMENT_CREATE | A task assignment is created | | TASK_ASSIGNMENT_DELETE | A task assignment is deleted | | TASK_CREATE | A task is created. | | TASK_UPDATE | A task's comment is edited | | TERMS_OF_SERVICE_ACCEPT | Accepted terms | | TERMS_OF_SERVICE_REJECT | Rejected terms | | UNDELETE | Restored | | UNLOCK | Unlocked | | UNSHARE | Shared link removed | | UPDATE_COLLABORATION_EXPIRATION | Extend collaborator expiration | | UPDATE_SHARE_EXPIRATION | Extend shared link expiration | | UPLOAD | Uploaded | | USER_AUTHENTICATE_OAUTH2_ACCESS_TOKEN_CREATE | An OAuth 2.0 access token has been created | | WATERMARK_LABEL_CREATE | A watermark is added to a file | | WATERMARK_LABEL_DELETE | A watermark is removed from a file | **Reference:** https://developer.box.com/guides/events/enterprise-events/for-enterprise/ --- ## Untitled *Type: guide | Category: Events * Enterprise Events Enterprise events provide an event feed for all users and content in an enterprise Box instance. Depending upon the stream… # Enterprise Events Enterprise events provide an event feed for all users and content in an enterprise Box instance. Depending upon the `stream_type` your application can either subscribe to live events or query historical events. Access to these stream types is limited to users with admin permissions to **Run new reports and access existing reports**. **Reference:** https://developer.box.com/guides/events/enterprise-events/ --- ## Untitled *Type: guide | Category: Events * Shield Alert Events Box Shield must be purchased and enabled on a Box enterprise to take advantage of the advanced security offerings… # Shield Alert Events [Box Shield](https://www.box.com/shield) must be purchased and enabled on a Box enterprise to take advantage of the advanced security offerings outlined below. ## Threat detection alerts Shield [threat detection](https://support.box.com/hc/en-us/articles/360044196113-Using-Threat-Detection) delivers context-rich alerts on potential threats, such as compromised accounts and data theft, based on anomalous user behavior. The possible alerts produced by Shield are for: 1. Suspicious locations 2. Suspicious sessions 3. Anomalous downloads 4. Malicious content All Shield threat detection alert events are produced within the [enterprise event](g://events/enterprise-events/for-enterprise) stream. These events follow the standard event object schema and the `event_type` value is set to `SHIELD_ALERT`. ``` { "source": null, "created_by": { "type": "user", "id": "2", "name": "Unknown User", "login": "" }, "action_by": null, "created_at": "2019-12-20T11:38:56-08:00", "event_id": "97f1b31f-f143-4777-81f8-1b557b39ca33", "event_type": "SHIELD_ALERT", "ip_address": "10.1.2.3", "type": "event", "session_id": null, "additional_details": { "..." } } ``` The `additional_details` object provides information about the specific type of shield alert that triggered the event. ### Suspicious locations alert A suspicious locations alert is produced when Shield detects a user accessing content from an unusual, excluded geographic location, or 'host' IP address. It can be identified by the `Suspicious Locations` value within `additional_details.shield_alert.rule_category`. The `additional_details` payload will provide the following details: ``` "additional_details": { "shield_alert": { "rule_category": "Suspicious Locations", "rule_id": 123, "rule_name": "Suspicious Location", "rule_response_action": { "restrict_user": true }, "risk_score": 60, "alert_summary": { "alert_activities": [ { "occurred_at": "2019-12-20T11:37:05-08:00", "event_type": "Download", "item_name": "xyz.txt", "item_type": "file", "item_id": "127", "item_path": "ABC/DEF", "ip_info": { "ip": "1.2.3.4", "latitude": "37.5555", "longitude": "-120.6789", "registrant": "Microsoft Corporation", "country_code": "US", "city_name": "San Jose", "region_name": "California" }, "service_name": "Box Excel Online Previewer" } ] }, "alert_id": 2398, "priority": "medium", "user": { "id": 2320, "name": "Some name", "email": "some@email.com" }, "link": "https://app.box.com/master/shield/alerts/2398", "created_at": "2019-12-20T11:37:15-08:00" } } ``` ### Suspicious sessions alert A suspicious sessions alert is produced when Shield detects a user accessing content in a session characterized by unusual user-agent strings, unusual IDs, uncommon types of applications, new IP addresses, and an improbably rapid change in the person's log-in location. It can be identified by the `Suspicious Sessions` value within `additional_details.shield_alert.rule_category`. The `additional_details` payload will provide the following details: ``` "additional_details": { "shield_alert": { "rule_category": "Suspicious Sessions", "rule_id": 123, "rule_name": "Suspicious Session", "rule_response_action": null, "risk_score": 77, "alert_summary": { "description": "First time in prior month user connected from ip 2.3.4.5 First time user agent Some User Agent (Some UA 4.5.6) appeared for user within prior month Apparent distance 9580.0 km between events 59 seconds apart is faster than possible", "sessions": [ { "session_type": "suspicious", "activities": [ { "occurred_at": "2019-12-19T11:37:00-08:00", "event_type": "Set shared link expiration", "item_name": "xyz.txt", "item_type": "file", "item_id": "123456", "item_path": "ABC/DEF", "ip_info": { "ip": "2.3.4.5", "latitude": "37.5555", "longitude": "-120.6789", "registrant": "Microsoft Corporation", "country_code": "US", "city_name": "San Jose", "region_name": "California" }, "service_name": "ServiceName" } ] }, { "session_type": "typical", "activities": [ { "occurred_at": "2019-12-19T11:37:59-08:00", "event_type": "Item Modified", "item_name": "abc.boxnote", "item_type": "file", "item_id": "123123", "item_path": "folder/sub folder", "ip_info": { "ip": "4.5.6.7", "latitude": "37.5555", "longitude": "-20.6789", "country_code": "US", "city_name": "Some City", "region_name": "XYZ" }, "service_name": "Box Notes" } ] } ] }, "alert_id": 500, "priority": "medium", "user": { "id": 50500, "name": "A b c", "email": "a@b.c" }, "link": "https://cloud.app.box.com/master/shield/alerts/500", "created_at": "2019-12-20T11:38:16-08:00" } } ``` ### Anomalous download alert An anomalous download alert is produced when Shield detects an account holder who may be stealing sensitive content. It can be identified by the `Anomalous Download` value within `additional_details.shield_alert.rule_category`. The `additional_details` payload will provide the following details: ``` "additional_details": { "shield_alert": { "rule_category": "Anomalous Download", "rule_id": 123, "rule_name": "Anomalous Download Rule", "rule_response_action": null, "risk_score": 77, "alert_summary": { "description": "Significant increase in download content week over week, 9200% (25.04 MB) more than last week 12 additional files downloaded week over week)", "download_delta_size": "25 Mb", "download_delta_percent": 9200, "historical_period": { "date_range": { "start_date": "2019-12-01T01:01:00-08:00", "end_date": "2019-12-08T01:01:00-08:00" }, "download_size": "0 Mb", "downloaded_files_count": 1 }, "anomaly_period": { "date_range": { "start_date": "2019-12-08T01:01:00-08:00", "end_date": "2019-12-15T01:01:00-08:00" }, "download_size": "25 Mb", "downloaded_files_count": 13 }, "download_ips": [ { "ip": "1.2.3.4" } ] }, "alert_id": 444, "priority": "medium", "user": { "id": 567, "name": "Some user", "email": "some@user.com" }, "link": "https://cloud.app.box.com/master/shield/alerts/444", "created_at": "2019-12-20T11:38:16-08:00" } } ``` ### Malicious content alert A malicious content alert is produced when Shield detects potential malware in content uploading to an account. It can be identified by the `Malicious Content` value within `additional_details.shield_alert.rule_category`. The `additional_details` payload will provide the following details: ``` "additional_details": { "shield_alert": { "rule_category": "Malicious Content", "rule_id": 123, "rule_name": "Viruses and stuff", "rule_response_action": null, "risk_score": 100, "alert_summary": { "upload_activity": { "occurred_at": "2019-12-20T11:37:05-08:00", "event_type": "Upload", "item_name": "virus.exe", "item_type": "file", "item_id": "127", "item_path": "ABC/DEF", "sha1_hash": "", "ip_info": { "ip": "1.2.3.4", "latitude": "37.5555", "longitude": "-120.6789", "registrant": "Microsoft Corporation", "country_code": "US", "city_name": "San Jose", "region_name": "California" }, "service_name": "Service name" } }, "malware_info": { "file_id": 127, "file_name": "malware.exe", "file_version": 4239023, "file_created": "2019-12-20T11:37:05-08:00", "file_created_by": { "id": 1010, "name": "Bob", "email": "bob@enterprise.com" }, "file_hash": "d869db7fe62fb07c25a0403ecaea55031744b5fb", "file_hash_type": "SHA-1", "file_size_bytes": 51345, "file_version_uploaded": "2019-12-20T11:37:05-08:00", "file_version_uploaded_by": { "id": 1011, "name": "Jane", "email": "jane@enterprise.com" }, "status": "Malicious", "categories": [ "Adware", "SpyWare" ], "tags": [ "FILE_MALICIOUS_EXECUTION", "FILE_OTHER_TAG" ], "description": "This is a really bad file", "detail_link": "https://some.link/xyz", "malware_name": "BadMalware", "first_seen": "2019-12-19T11:37:05-08:00", "last_seen": "2019-12-20T11:37:05-08:00", "family": "MalwareBot4000" }, "alert_id": 2398, "priority": "medium", "user": { "id": 2320, "name": "Some Name", "email": "some@email.com" }, "link": "https://app.box.com/master/shield/alerts/2398", "created_at": "2019-12-20T11:37:15-08:00" } } ``` **Reference:** https://developer.box.com/guides/events/event-triggers/shield-alert-events/ --- ## Untitled *Type: guide | Category: Events * Event Source If a user or item triggers an event, The response of the GET /events endpoint contains an event source object. User Source… # Event Source If a user or item triggers an event, The response of the [`GET /events`](e://get_events) endpoint contains an event source object. ## User Source Object If a user triggers an event, the source object will be the standard representation of the [user resource](e://resources/user). ``` { "source": { "id": 11446498, "type": "user", "address": "900 Jefferson Ave, Redwood City, CA 94063", "avatar_url": "https://www.box.com/api/avatar/large/181216415", "created_at": "2012-12-12T10:53:43-08:00", "job_title": "CEO", "language": "en", "login": "ceo@example.com", "max_upload_size": 2147483648, "modified_at": "2012-12-12T10:53:43-08:00", "name": "Aaron Levie", "notification_email": { "email": "notifications@example.com", "is_confirmed": true }, "phone": 6509241374, "space_amount": 11345156112, "space_used": 1237009912, "status": "active", "timezone": "Africa/Bujumbura" } } ``` ## Item Source Object If an item triggers an event, the source object will be the [event source resource](e://resources/event-source). The below example contains a `classification` object. This does not appear if the item does not have a classification set. Also, it does not appear for every event type. ``` { "source": { "item_type": "file", "item_id": "8903212345", "item_name": "example.docx", "parent": { "type": "folder", "name": "All Files", "id": "0" }, "owned_by": { "type": "user", "id": "11446498", "name": "Aaron Levie", "login": "notifications@example.com" }, "classification": { "name": "Top Secret" } } } ``` **Reference:** https://developer.box.com/guides/events/event-triggers/event-source/ --- ## Untitled *Type: guide | Category: Events * Event Triggers Events appear in the event stream based on upon actions committed by users, items, or other resources. The response of the… # Event Triggers Events appear in the event stream based on upon actions committed by users, items, or other resources. The response of the [`GET /events`](e://get_events) endpoint changes based upon the event that triggered the event. **Reference:** https://developer.box.com/guides/events/event-triggers/ --- ## Untitled *Type: guide | Category: Events * Shield Information Barrier Events Information barrier prevents exchanges or communication that could lead to conflicts of interest or… # Shield Information Barrier Events Information barrier prevents exchanges or communication that could lead to conflicts of interest or potential legal issues. For example, admins can use information barrier to separate teams based on projects to prevent collaboration on content restricted to specific groups. ## Events triggered when information barrier is configured Configuring information barrier produces events in the [enterprise event](g://events/enterprise-events/for-enterprise/) stream. For example, activating or deactivating the barrier triggers an event. These events follow the standard event object schema with the `event_type` value set to one of the following: - `SHIELD_INFORMATION_BARRIER_ENABLED` - `SHIELD_INFORMATION_BARRIER_PENDING` - `SHIELD_INFORMATION_BARRIER_DISABLED` ### Shield information barrier enabled A `SHIELD_INFORMATION_BARRIER_ENABLED` event is triggered when the information barrier is enabled for a file or folder. For example: ``` { "chunk_size": 1, "next_stream_position": "1152923169537420243", "entries": [ { "source": { "barrier_id": 123456, "barrier_status": "ENABLED", "barrier_segments": [ { "name": "8", "member_count": 1 }, { "name": "9", "member_count": 1 } ] }, "created_by": { "type": "user", "id": "12345667", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-04T17:42:53-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_ENABLED", "ip_address": "Unknown IP", "type": "event", "session_id": null, "additional_details": null } ] } ``` ### Shield information barrier pending A `SHIELD_INFORMATION_BARRIER_PENDING` event is triggered when the information barrier is not yet enabled for a particular file or folder. The activation process was triggered, but the information barrier is not yet in place. For example: ``` { "chunk_size": 1, "next_stream_position": "1152923169531664551", "entries": [ { "source": { "barrier_id": 123456, "barrier_status": "PENDING", "barrier_segments": [ { "name": "8", "member_count": 1 }, { "name": "9", "member_count": 1 } ] }, "created_by": { "type": "user", "id": "12345667", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-04T16:06:57-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_PENDING", "ip_address": "Unknown IP", "type": "event", "session_id": null, "additional_details": null } ] } ``` ### Shield information barrier deactivated A `SHIELD_INFORMATION_BARRIER_DISABLED` event is triggered when the information barrier is deactivated for a particular file or folder. For example: ``` { "chunk_size": 1, "next_stream_position": "1152923169767928414", "entries": [ { "source": { "barrier_id": 1234567, "barrier_status": "DISABLED", "barrier_segments": [ { "name": "8", "member_count": 1 }, { "name": "9", "member_count": 1 } ] }, "created_by": { "type": "user", "id": "123435567", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-07T09:44:41-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_DISABLED", "ip_address": "Unknown IP", "type": "event", "session_id": null, "additional_details": null } ] } ``` ## Events triggered by restricted actions When the information barrier is set up, each user attempt to perform restricted actions or access restricted data also results in events. These events follow the standard event object schema with the `event_type` value set to one of the following: - `SHIELD_INFORMATION_BARRIER_GROUP_ADD_USER_BLOCKED` - `SHIELD_INFORMATION_BARRIER_COLLAB_BLOCKED` - `SHIELD_INFORMATION_BARRIER_ITEM_OWNER_TRANSFER_BLOCKED` - `SHIELD_INFORMATION_BARRIER_SHARED_ITEM_ACCESS_BLOCKED` - `SHIELD_INFORMATION_BARRIER_ITEM_MOVE_BLOCKED` - `SHIELD_INFORMATION_BARRIER_ITEM_COPY_BLOCKED` ### Adding user blocked A `SHIELD_INFORMATION_BARRIER_GROUP_ADD_USER_BLOCKED` event is triggered when the information barrier prohibits adding a user to a specific group. The `additional_details` payload provides details of the restricted groups. ``` { "source": { "type": "user", "id": "123456677", "name": "Unknown User", "login": "user@email.com" }, "created_by": { "type": "user", "id": "12345666", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-07T09:26:50-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_GROUP_ADD_USER_BLOCKED", "ip_address": "10.1.2.3", "type": "event", "session_id": null, "additional_details": { "group_id": "12345678", "group_name": "Support" } } ``` ### Collaboration blocked A `SHIELD_INFORMATION_BARRIER_COLLAB_BLOCKED` event is triggered when the information barrier prohibits adding collaborations for users that have restricted access to a file or folder. The `additional_details` payload provides details of the restricted collaboration. ``` { "source": { "folder_id": "12334556", "folder_name": "Contracts", "user_id": "1234567", "user_name": "Unknown User", "parent": { "type": "folder", "name": "All Files", "id": "0" }, "owned_by": { "type": "user", "id": "12345678", "name": "Unknown User", "login": "user@email.com" } }, "created_by": { "type": "user", "id": "16335351460", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-05T14:15:14-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_COLLAB_BLOCKED", "ip_address": "Unknown IP", "type": "event", "session_id": null, "additional_details": { "type": "box://event/additional_details/collaboration", "collab_id": "0", "is_performed_by_admin": false } } ``` ### Shared item access blocked A `SHIELD_INFORMATION_BARRIER_SHARED_ITEM_ACCESS_BLOCKED` event is triggered when the information barrier prohibits accessing a file or folder using the shared link. The `additional_details` payload provides details of the shared link and additional security information. ``` { "source": { "item_type": "folder", "item_id": "123456789", "item_name": "Contracts", "parent": { "type": "folder", "name": "All Files", "id": "0" }, "owned_by": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" } }, "created_by": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-06T13:27:58-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_SHARED_ITEM_ACCESS_BLOCKED", "ip_address": "Unknown IP", "type": "event", "session_id": null, "additional_details": { "shared_link_id": "abcdefghijklm", "security_information": { "accessFromSharedObject": { "sharedId": 123456789, "sharedName": "abcdefghijklmnop", "passwordSet": false, "accessLevel": "open", "createdAt": "2022-10-06T13:27:21-07:00" } } } } ``` ### Moving item blocked A `SHIELD_INFORMATION_BARRIER_ITEM_MOVE_BLOCKED` event is triggered when the information barrier prohibits moving an item (a file or a folder) to a a folder the user has no access to. The `additional_details` payload provides details of the folder. ``` { "source": { "item_type": "folder", "item_id": "123456789", "item_name": "Contracts", "parent": { "type": "folder", "name": "All Files", "id": "0" }, "owned_by": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" } }, "created_by": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-06T13:26:58-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_ITEM_MOVE_BLOCKED", "ip_address": "Unknown IP", "type": "event", "session_id": null, "additional_details": { "destination_folder": { "item_type": "folder", "item_id": "123456789", "item_name": "Contracts Signed" } } } ``` ### Copying item blocked A `SHIELD_INFORMATION_BARRIER_ITEM_COPY_BLOCKED` event is triggered when the information barrier prohibits copying an item (a file or a folder) to a a folder the user has no access to. The `additional_details` payload provides details of the destination folder. ``` { "source": { "item_type": "folder", "item_id": "123456789", "item_name": "Contracts", "parent": { "type": "folder", "name": "All Files", "id": "0" }, "owned_by": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" } }, "created_by": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-05T14:25:15-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_ITEM_COPY_BLOCKED", "ip_address": "Unknown IP", "type": "event", "session_id": null, "additional_details": { "destination_folder": { "item_type": "folder", "item_id": "123456789", "item_name": "Contracts Signed" } } } ``` ### Item transfer ownership blocked A `SHIELD_INFORMATION_BARRIER_ITEM_OWNER_TRANSFER_BLOCKED` event is triggered when the information barrier prohibits transferring the item ownership to a user that is subject to restrictions. The `additional_details` payload provides details of the user that cannot be set as the new owner. ``` { "source": { "item_type": "folder", "item_id": "", "item_name": "All Files", "parent": { "type": "folder", "name": "", "id": "" }, "owned_by": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" } }, "created_by": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" }, "action_by": null, "created_at": "2022-10-07T09:29:20-07:00", "event_id": "f82c3ba03e41f7e8a7608363cc6c0390183c3f83", "event_type": "SHIELD_INFORMATION_BARRIER_ITEM_OWNER_TRANSFER_BLOCKED", "ip_address": "10.1.2.3", "type": "event", "session_id": null, "additional_details": { "restricted_user": { "type": "user", "id": "123456789", "name": "Unknown User", "login": "user@email.com" }, "service_id": "123456789", "service_name": "App" } } ``` **Reference:** https://developer.box.com/guides/events/event-triggers/shield-information-barrier-events/ --- ## Untitled *Type: guide | Category: Events * Shield Smart Access Events Smart Access enables Box Admins to define and enforce classification-based access policies to control access and… # Shield Smart Access Events [Smart Access](https://support.box.com/hc/en-us/articles/7711416297747-About-Smart-Access) enables Box Admins to define and enforce classification-based access policies to control access and prevent the unintentional leakage of sensitive content. Smart Access policies can be configured in [enforced or monitoring mode](https://support.box.com/hc/en-us/articles/14596333776403-Shield-Access-Policy-Settings). In all event types, a field named `controlMode` appears to say whether the policy is in `enforced` or `monitoring` mode. ## Download and Print Restriction If an admin creates a Shield access policy that enforces download or print restriction and an end user is blocked from downloading or printing a file, an event is produced within the [enterprise event](g://events/enterprise-events/for-enterprise) stream. If the access policy is set to monitor potential download and print violations, events will also be generated when a user is viewing a folder with a file restricted from download or print, viewing a file in preview that is restricted from download or print, and when a user requests to download a file through the API that is restricted from download or print. These events follow the standard event object schema and the `event_type` value set to `SHIELD_DOWNLOAD_BLOCKED`. If downloading is blocked, the `additional-details` payload of the `SHIELD_DOWNLOAD_BLOCKED` event will provide the below details. For the Box Web App, the `additional_details` payload will provide the following details: ``` "additional_details": { "shield_download_enforcement": { "item": { "type": "file", "id": 987654321, "name": "testFile.docx", "file_version_id": 38495726173, "size": 370, "sha1": "db0a61e73b5e6985d190134e0a4b9982c716afeb" }, "access_user": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "service": null, "additional_info": "", "created_at": "2022-02-22T10:35:08-08:00", "classification": "Confidential", "controlMode": "enforced" } } ``` For the Box Desktop App, the `additional_details` payload will provide the following details: ``` "additional_details": { "shield_download_enforcement": { "item": { "type": "file", "id": 123456789, "name": "testFile.docx", "file_version_id": 987654321, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "access_user": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "service": { "service": 254429, "name": "Box Drive" }, "additional_info": "", "created_at": "2022-02-22T10:38:58-08:00", "classification": "Confidential", "controlMode": "enforced" }, "service_id": "254429", "service_name": "Box Drive" } ``` For Box Mobile apps, the `additional_details` payload will provide the following details: ``` "additional_details": { "shield_download_enforcement": { "item": { "type": "file", "id": 987654321, "name": "testFile.docx", "file_version_id": 38495726173, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "access_user": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "service": { "service": 4715, "name": "Box for Android" }, "additional_info": "", "created_at": "2022-01-18T14:51:37-08:00", "classification": "Confidential", "controlMode": "monitoring" }, "service_id": "4715", "service_name": "Box for Android" } ``` ## External collaboration restriction If an external collaboration invitation is restricted, an event is produced within the [enterprise event](g://events/enterprise-events/for-enterprise) stream. These events follow the standard event object schema, with the `event_type` value set to: `SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION`, `SHIELD_EXTERNAL_COLLAB_INVITE_JUSTIFIED`, `SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED` `SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED_MISSING_JUSTIFICATION`, or `SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED`. If an external collaboration invitation is blocked, the `additional-details` payload of the `SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED` or `SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION` event will provide the following details: ``` "additional_details": { "shield_external_collab_enforcement": { "item": { "type": "file", "id": 987654321, "name": "testFile.docx", "file_version_id": 987654321, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "inviter": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "invitee": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "accessUser": null, "service": null, "additionalInfo": "", "createdAt": null, "justification": null, "classification": "Confidential", "controlMode": "enforced" } } ``` If an external collaboration invitation is justified, the `additional_details` payload of the `SHIELD_EXTERNAL_COLLAB_INVITE_JUSTIFIED` event will provide the following details: ``` "additional_details": { "shield_external_collab_enforcement": { "item": { "type": "file", "id": 123456789, "name": "testFile.docx", "file_version_id": 123456789, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "inviter": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "invitee": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "accessUser": null, "service": null, "additionalInfo": "", "createdAt": null, "justification": { "justification_id": "17786127", "request_at": 1644874023, "requested_by": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "request_type": "EXTERNAL_COLLAB", "item": { "type": "file", "id": 987654321, "name": "testFile.docx", "file_version_id": 941051265322, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "user": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "title": "Approved", "description": "", "additional_info": null, "approved_by": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "action": "APPROVED", "action_at": 1644874023, "details": null }, "classification": "Confidential", "controlMode": "enforced" } } ``` If external collaboration access is blocked, the `additional_details` payload of the `SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED` or `SHIELD_EXTERNAL_COLLAB_ACCESS_BLOCKED_MISSING_JUSTIFICATION` event will provide the following details: ``` "additional_details": { "shield_external_collab_enforcement": { "item": { "type": "file", "id": 987654321, "name": "testFile.docx", "file_version_id": 987654321, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "inviter": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "invitee": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "accessUser": null, "service": null, "additionalInfo": "", "createdAt": null, "justification": null, "classification": "Confidential", "controlMode": "enforced" } } ``` If a Shield justification is approved, an event is produced within the [enterprise event](g://events/enterprise-events/for-enterprise) stream. These events follow the standard event object schema and the `event_type` value set to `SHIELD_JUSTIFICATION_APPROVAL`. The `additional_details` payload will provide the following details: ``` "additional_details": { "shield_justification": { "justification_id": "18428718", "request_at": 1645556286, "requested_by": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "request_type": "EXTERNAL_COLLAB", "item": { "type": "file", "id": 987654321, "name": "testFile.docx", "file_version_id": 987654321, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "user": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "title": "Partner Project", "description": "", "additional_info": null, "approved_by": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "action": "APPROVED", "action_at": 1645556286, "details": null } } ``` Admins, please note that you may see two enterprise events instead of one when a justification is chosen from the share modal. For example, one `SHIELD_EXTERNAL_COLLAB_INVITE_BLOCKED_MISSING_JUSTIFICATION` event and one `SHIELD_EXTERNAL_COLLAB_INVITE_JUSTIFIED` event. ## Integration Restriction If a 3rd-party application, including published platform applications with which your organization is integrated, is restricted from downloading a file or a folder, an event is produced within the [enterprise event](g://events/enterprise-events/for-enterprise) stream. These events follow the standard event object schema, with the `event_type` value set to `SHIELD_DOWNLOAD_BLOCKED`. For 3rd-party applications, the `additional_details` payload will provide the following details: ``` "additional_details": { "shield_download_enforcement": { "item": { "type": "file", "id": 875644956551, "name": "blaha.docx", "file_version_id": 941051265322, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "access_user": { "type": "user", "id": 11754686560, "name": "Ming Feng", "login": "mfeng+demo@boxdemo.com" }, "service": "docusign", "additional_info": "", "created_at": "2022-01-18T14:53:53-08:00", "classification": "Confidential", "controlMode": "enforced" } ``` For platform applications, the `additional_details` payload will provide the following details: ``` "additional_details": { "shield_download_enforcement": { "item": { "type": "file", "id": 123456789, "name": "testFile.docx", "file_version_id": 987654321, "size": 11640, "sha1": "368acd076a89ce82e62cac004fa27ea9ce3019d7" }, "access_user": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "service": { "service": 123456, "name": "CustomApp" }, "additional_info": "", "created_at": "2022-01-18T13:31:25-08:00", "classification": "Confidential", "controlMode": "enforced" }, "service_id": "123456", "service_name": "CustomApp" } ``` ## FTP Restriction If download of a file or folder is restricted via the FTP protocol, an event is produced within the [enterprise event](g://events/enterprise-events/for-enterprise) stream. These events follow the standard event object schema, with the `event_type` value set to `SHIELD_DOWNLOAD_BLOCKED`. The `additional_details` payload will provide the following details: ``` "additional_details": { "shield_download_enforcement": { "item": { "type": "file", "id": 123456789, "name": "textFile.txt", "file_version_id": 987654321, "size": 3606, "sha1": "ab7a79ff8e2a6b576e1c62d850290a09312fb387" }, "access_user": { "type": "user", "id": 123456789, "name": "Some Name", "login": "somename@box.com" }, "service": { "service": 4082, "name": "Box FTP Server" }, "additional_info": "", "created_at": "2022-01-18T14:19:51-08:00", "classification": null, "controlMode": "enforced" }, "service_id": "4082", "service_name": "Box FTP Server" } ``` **Reference:** https://developer.box.com/guides/events/event-triggers/shield-smart-access-events/ --- ## Untitled *Type: guide | Category: Events * Sign Events Audit Box Sign events using the enterprise events stream. To learn more about Box Sign, visit our guide. The status provided… # Sign Events Audit Box Sign events using the enterprise events stream. To learn more about Box Sign, visit our [guide](g://box-sign). The status provided below in each `additional_details` payload may differ from the example based on the specific sign request details. For example, if the requester is the only signer, the status of the `SIGN_DOCUMENT_CREATED` event will immediately be `viewed`. ## Document Events ### Created A `SIGN_DOCUMENT_CREATED` `event_type` is produced when a sign request is created via API or UI. At this stage the sign request is not sent to signers yet. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "sent", "signer_ip_address": null, "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": null, "template": { "id": "987abC5423", "template_type": "Signing", "name": "Work Contact" }, "batch_send": { "id": "W23YVL46" }, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "sender_message": { "subject": "Can you please sign this document?", "message": "This document shows the terms agreed to on the phone." }, "forward": null } } ``` ### Converted A `SIGN_DOCUMENT_CONVERTED` `event_type` is produced when a sign request is converted to a `.pdf` for signing. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "created", "signer_ip_address": null, "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": null, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "sender_message": { "subject": "", "message": "" }, "forward": null } } ``` ### Completed A `SIGN_DOCUMENT_COMPLETED` `event_type` is produced when all signers have successfully signed the document. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "signed", "signer_ip_address": null, "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": null, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "sender_message": { "subject": "", "message": "" }, "forward": null } } ``` ### Cancelled A `SIGN_DOCUMENT_CANCELLED` `event_type` is produced when a sign request is cancelled by the requester via API or UI. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "cancelled", "signer_ip_address": null, "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": null, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "sender_message": { "subject": "", "message": "" }, "forward": null } } ``` ### Expired A `SIGN_DOCUMENT_EXPIRED` `event_type` is produced when a sign request expired with incomplete signatures. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "expired", "signer_ip_address": null, "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": null, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "sender_message": { "subject": "", "message": "" }, "forward": null } } ``` ## Signer Events ### Assigned A `SIGN_DOCUMENT_ASSIGNED` `event_type` is produced when a sign request is successfully sent to a signer. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "sent", "signer_ip_address": "", "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": { "id": "246813579", "type": "user", "name": "Jane Doe", "login": "janedoe@example.com" }, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "ready_sign_link": { "id": "aaae45bb-e89b-12d3-a456-426614174000" }, "sender_message": { "subject": "", "message": "" }, "forward": null } } ``` ### Viewed by Signer A `SIGN_DOCUMENT_VIEWED_BY_SIGNER` `event_type` is produced when a sign request signer clicks on **Review Document** in the signing email or visits the signing URL. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "viewed", "signer_ip_address": "", "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": { "id": "246813579", "type": "user", "name": "Jane Doe", "login": "janedoe@example.com" }, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "ready_sign_link": { "id": "aaae45bb-e89b-12d3-a456-426614174000" }, "sender_message": { "subject": "", "message": "" }, "forward": null } } ``` ### Downloaded A `SIGNER_DOWNLOADED` `event_type` is produced when a signer downloads the signing document. ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "viewed", "signer_ip_address": "", "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": { "id": "246813579", "type": "user", "name": "Jane Doe", "login": "janedoe@example.com" }, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "ready_sign_link": { "id": "aaae45bb-e89b-12d3-a456-426614174000" }, "sender_message": { "subject": "", "message": "" }, "forward": { "forwarded_to_email": "janedoe@box.com", "forwarded_reason": "Please sign", "forwarded_at": "2022-03-03T12:04:20-10:00" } } } ``` ### Forwarded A `SIGNER_FORWARDED` `event_type` is produced when a signer downloads the signing document. ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "viewed", "signer_ip_address": "", "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": { "id": "246813579", "type": "user", "name": "Jane Doe", "login": "janedoe@example.com" }, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "ready_sign_link": { "id": "aaae45bb-e89b-12d3-a456-426614174000" }, "sender_message": { "subject": "Can you please sign this document?", "message": "This document shows the terms agreed to on the phone." }, "forward": { "forwarded_to_email": "somename@box.com", "forwarded_reason": "I need to forward to my business partner.", "forwarded_at": "2022-02-03T10:04:52-08:00", }, } } ``` ### Signed A `SIGN_DOCUMENT_SIGNED` `event_type` is produced when a signer completes the sign request. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "signed", "signer_ip_address": "", "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": { "id": "246813579", "type": "user", "name": "Jane Doe", "login": "janedoe@example.com" }, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "ready_sign_link": { "id": "aaae45bb-e89b-12d3-a456-426614174000" }, "sender_message": { "subject": "Can you please sign this document?", "message": "This document shows the terms agreed to on the phone." }, "forward": null } } ``` ### Declined A `SIGN_DOCUMENT_DECLINED` `event_type` is produced when a sign request signer declines the request. The`additional_details` payload will provide the following details: ``` "additional_details": { "sign_request": { "sign_request_id": "123e4567-e89b-12d3-a456-426614174000", "sign_request_short_id": "426614174000", "status": "declined", "signer_ip_address": "", "requestor_ip_address": "", "files": [ { "id": "1234567890", "type": "file", "name": "example_doc.pdf", "parent": { "id": "987654321", "type": "folder" } } ], "expires": null, "requestor": { "id": "13579246", "type": "user", "name": "John Doe", "login": "johndoe@box.com" }, "signer": { "id": "246813579", "type": "user", "name": "Jane Doe", "login": "janedoe@example.com" }, "template": null, "batch_send": null, "redirection": { "redirect_url": "https://www.google.com", "declined_redirect_url": "https://www.googledecline.com" }, "ready_sign_link": { "id": "aaae45bb-e89b-12d3-a456-426614174000" }, "sender_message": { "subject": "", "message": "" }, "forward": null } } ``` **Reference:** https://developer.box.com/guides/events/event-triggers/sign-events/ --- ## Untitled *Type: guide | Category: Events * Event Stream Parameters The GET /events endpoint can take in several parameters. stream_type and stream_position are described in more… # Event Stream Parameters The [`GET /events`](e://get_events) endpoint can take in several parameters. `stream_type` and `stream_position` are described in more detail in this section's guides. **Reference:** https://developer.box.com/guides/events/parameters/ --- ## Untitled *Type: guide | Category: Events * Stream Types Stream Types Scope Purpose Description Retention Access Pattern admin_logs A single enterprise (for authorized admins… # Stream Types | Stream Types | Scope | Purpose | Description | Retention | Access Pattern | | --- | --- | --- | --- | --- | --- | | admin_logs | A single enterprise (for authorized admins) | Historical Queries | Enables querying historical events up to one year | 365 Days | Filter by time frame, then paginate through the response by stream_position | | admin_logs_streaming | A single enterprise (for authorized admins) | Near real time subscriptions | Enables subscribing to live events in near real time | 14 Days | Poll using the stream_position | | all (default) | A single user (for any user) | Near real time subscriptions | Returns everything for a user | 21 Days | Poll or long-poll using the stream_position | | changes | A single user (for any user) | Near real time subscriptions | Returns events that may cause file tree changes such as file updates or collaborations | 21 Days | Poll or long-poll using the stream_position | | sync | A single user (for any user) | Near real time subscriptions | Is similar to changes but only applies to synced folders | 31 Days | Poll or long-poll using the stream_position | **Reference:** https://developer.box.com/guides/events/parameters/stream-types/ --- ## Untitled *Type: guide | Category: Events * Stream Position Pagination Paginating the event stream works through the use of the stream_position parameter. First, send a request to the… # Stream Position Pagination Paginating the event stream works through the use of the `stream_position` parameter. First, send a request to the [`GET /events`](e://get_events) API without a `stream_position` query parameter. ``` curl https://api.box.com/2.0/events \ -H "authorization: Bearer ACCESS_TOKEN" ``` The API will return all available events beginning with the oldest. The response will also include a `next_stream_position` value that can be used to make the next API call for the next place in the stream. ``` curl https://api.box.com/2.0/events?stream_position=388720462721 \ -H "authorization: Bearer ACCESS_TOKEN" ``` The `stream_position` can also be set to `now` to return the most recent stream position. ``` curl https://api.box.com/2.0/events?stream_position=now \ -H "authorization: Bearer ACCESS_TOKEN" ``` In this case, the API returns an empty list and a `next_stream_position` that can be used for the next call. **Reference:** https://developer.box.com/guides/events/parameters/pagination/ --- ## Untitled *Type: guide | Category: Events * User Events User Events provides a low latency stream of events relevant to the currently authenticated user. This event stream is how Box… # User Events User Events provides a low latency stream of events relevant to the currently authenticated user. This event stream is how Box keeps Box Drive up to date, but is also made available for developer use. **Reference:** https://developer.box.com/guides/events/user-events/ --- ## Untitled *Type: guide | Category: Events * Get User Events To get a user's events, authenticate as any user and make a call to the GET /events API. The events returned will only be… # Get User Events To get a user's events, authenticate as any user and make a call to the [`GET /events`](e://get_events) API. The events returned will only be for the user who's access token the API was made with. To get the event feed for a different user either use the `as-user` header or an actual access token for that user. ## Stream Types The user event stream support 3 types of stream. | Stream Type | | | --- | --- | | all | Returns everything for a user (default) | | changes | Returns events that may cause file tree changes such as file updates or collaborations. | | sync | Is similar to changes but only applies to synced folders | ## Anonymous Users In some cases, the event feed might list a user with an ID of `2`. This is Box's internal identifier for anonymous users. An anonymous user is a user that is not logged in. This can happen any time a user interacts with content and they aren't asked to log in first. An example would be when a user downloads a file through an open shared link. ## Limitations Box does not store events indefinitely. User events are stored for between two weeks and two months, after which the user events are removed. Enterprise events are accessible for one year via the API and seven years via exported reports in the Box Admin Console. The emphasis of this feed is to return the complete results quickly, which means that Box may return events more than once or out of order. Duplicate events can be identified by their event IDs. ## Long Polling The user event stream supports long-polling [through the `OPTIONS /events` API](g://events/user-events/polling). ## Event Types The following events can be triggered for a user. This list is not exhaustive, so it is possible events appear that are not listed. The following events are available in all feeds. | Event name | Description | | --- | --- | | ITEM_CREATE | A folder or File was created | | ITEM_UPLOAD | A folder or File was uploaded | | ITEM_MOVE | A file or folder was moved | | ITEM_COPY | A file or folder was copied | | LOCK_CREATE | A file was locked | | LOCK_DESTROY | A file was unlocked. If a locked file is deleted, the source file will be null. | | ITEM_TRASH | A file or folder was marked as deleted | | ITEM_UNDELETE_VIA_TRASH | A file or folder was recovered out of the trash | | COLLAB_ADD_COLLABORATOR | A collaborator was added to a folder | | COLLAB_ROLE_CHANGE | A collaborator had their role changed | | COLLAB_INVITE_COLLABORATOR | A collaborator was invited on a folder | | COLLAB_REMOVE_COLLABORATOR | A collaborator was removed from a folder | | ITEM_SYNC | A folder was marked for sync | | ITEM_UNSYNC | A folder was unmarked for sync | | ITEM_RENAME | A file or folder was renamed | | ITEM_MAKE_CURRENT_VERSION | A previous version of a file was promoted to the current version | | GROUP_ADD_USER | Added user to group | | GROUP_REMOVE_USER | Removed user from group | The following events are only available in the `all` feed. | Event name | Description | | --- | --- | | COMMENT_CREATE | A comment was created on a folder, file, or other comment | | COMMENT_DELETE | A comment was deleted on folder, file, or other comment | | ITEM_DOWNLOAD | A file or folder was downloaded | | ITEM_PREVIEW | A file was previewed | | TASK_ASSIGNMENT_CREATE | A task was assigned | | TASK_CREATE | A task was created | | ITEM_SHARED_CREATE | A file or folder was enabled for sharing | | ITEM_SHARED_UNSHARE | A file or folder was disabled for sharing | | ITEM_SHARED | A folder was shared | | TAG_ITEM_CREATE | A Tag was added to a file or folder | | ENABLE_TWO_FACTOR_AUTH | 2 factor authentication enabled by user | | MASTER_INVITE_ACCEPT | Free user accepts invitation to become a managed user | | MASTER_INVITE_REJECT | Free user rejects invitation to become a managed user | | ACCESS_GRANTED | Granted Box access to account | | ACCESS_REVOKED | Revoke Box access to account | ## Event notifications To reduce the noise of the event stream and optimize event consumption, the event types listed in the table trigger a limited number of notifications. | Event type | Notification behavior | | --- | --- | | COLLAB_ADD_COLLABORATOR, COLLAB_REMOVE_COLLABORATOR, COLLAB_INVITE_COLLABORATOR, COLLAB_ROLE_CHANGE | When these events take place, the content owner on the changes event stream is notified. Collaborators see an additional event that matches what they see on the all stream. | | ITEM_DOWNLOAD | When an item is downloaded, only the content owner gets the notification. Collaborators are not notified. | | ITEM_PREVIEW | When an item is previewed, only the content owner gets the notification. Collaborators are not notified. | **Reference:** https://developer.box.com/guides/events/user-events/for-user/ --- ## Untitled *Type: guide | Category: Events * Long-Poll Events To get real-time notification of activity in a Box account you can use the long poll feature of the OPTIONS /events API… # Long-Poll Events To get real-time notification of activity in a Box account you can use the long poll feature of the [`OPTIONS /events`](e://options_events) API. Long polling is only available for user events. Enterprise events do not support long polling. ## Long Polling Long polling involves opening an HTTP request and keeping it open until the server sends a response, then repeating the process over and over to receive updated responses. The SDKs have built-in support for turning the event feeds into an event stream by long polling for new events. ### Long Poll URL To use long polling, first send an request to the [`OPTIONS /events`](e://options_events) API to retrieve the long poll URL. ``` curl -X OPTIONS https://api.box.com/2.0/events \ -H "authorization: Bearer ACCESS_TOKEN" ``` ``` { "chunk_size": 1, "entries": [ { "type": "realtime_server", "url": "http://2.realtime.services.box.net/subscribe?channel=cc807c9c4869ffb1c81a&stream_type=all", "ttl": 10, "max_retries": 10, "retry_timeout": 610 } ] } ``` ### Real-Time Servers Next, make a `GET` request to the provided URL to begin listening for events. If an event occurs in an account that is being monitored the application will receive a response with the value `new_change`. The response contains no other details. This single response serves as a prompt to take further action such as sending a request to the `GET /events` endpoint with the last known `stream_position`. ### Disconnect & Reconnect After the server sends this response it closes the connection. The application must now repeat the long poll process to begin listening for events again. If no events occur for a while after the application connects to the real-time server the connection will close with a `reconnect` value. When this happens the application should make a new call to `OPTIONS /events` to restart the process. ### Timeouts & Retries If the application receive no events in `retry_timeout` seconds then the application can reconnect to the real-time server. This might be necessary in due to network errors. If the application receive a `max_retries` error when making a `GET` request to the real-time server then it must restart the process by making an `OPTIONS` call to the `/events` API. **Reference:** https://developer.box.com/guides/events/user-events/polling/ --- ## Untitled *Type: guide | Category: Embed Box * Best Practices Rotate App Tokens See our guide on rotating App Tokens. Use Downscope Tokens App Tokens are a set of two tokens (Primary and… # Best Practices ## Rotate App Tokens See our guide on [rotating App Tokens](g://authentication/app-token/rollover). ## Use Downscope Tokens App Tokens are a set of two tokens (Primary and Secondary) that hold elevated privileges over the content managed by your application. App Tokens can be used by your application to upload, download, preview and modify any Box content. We strongly recommend that you use a [downscoped](g://authentication/tokens/downscope) version of the original App Token if you need to make the token available on the client side for any reason. This is because of the elevated privileges granted to these tokens, if you need. An example of when this would be needed is if you are using the Box Preview UI Element. **Reference:** https://developer.box.com/guides/embed/box-view/best-practices/ --- ## Untitled *Type: guide | Category: Embed Box * Create File Preview Once a file is uploaded to an App Token application, it can be previewed using two different methods: Direct embed: A… # Create File Preview Once a file is uploaded to an App Token application, it can be previewed using two different methods: - Direct embed: A standard HTML `<iframe>` component with a custom embed link. - Customized previewer: A fully customized preview widget using Box [UI Elements](g://embed/ui-elements). ## Direct Embed (iframe) The direct embed link provides limited options to customize the preview experience in your application. Due to the light-weight nature of the method, the API doesn't give you options to respond to client-side actions such as scrolling in the case of documents, play/pause interactivity for videos, rotating an image, etc. There are two steps to create a direct `<iframe>` embed for Box View: 1. Generate an embed URL for the file 2. Add the embed URL to an `<iframe>` ### Generate an embed URL for the file To create a public file preview URL for a file that was uploaded to the App Token application, you may either use a direct SDK method or make the request directly to the APIs. When generating the embed URL directly from the APIs, use the [Get File Information endpoint](e://get_files_id) and request `expiring_embed_link` via the `fields` parameter. ``` curl https://api.box.com/2.0/files/FILE_ID?fields=expiring_embed_link \ -H "authorization: Bearer [APP_TOKEN]" ``` ``` String fileId = "12345678"; Uri embedUri = await client.FilesManager.GetPreviewLinkAsync(id: fileId); ``` ``` String fileID = "12345678"; BoxFile file = new BoxFile(api, fileID); URL embedLink = file.getPreviewLink(); ``` ``` file_id = '12345678' embed_url = client.file(file_id).get_embed_url() ``` ``` const fileId = '12345678'; client.files.getEmbedLink(fileId).then(embedURL => { // ... }); ``` Within the response object will be a public embed URL like the following: ``` https://app.box.com/preview/expiring_embed/gvoct6FE!YT_X1LauQ8ulDTad96hTl9xLCRYJ 5iU6O61KxiduxFIgX9HSWMcCWf7zju1XkEsf6-Ul2qtKXeaFeKPT4SysQJQdxrc144KgTIBuoI3bWMf4 cfhp3jdLYrK5hnr6KMq5H6r-AW31AcFtDJi1lnT0M4b3bvvZUaE2RRJGGINMauvS6MAT2luae5PvbFSx Ctqqx6XlN6QrqbhfJc0UeJF9qwMv3-O8q5fWn0qr8OTY4lkeYidtTs3Ux... ``` For security reasons, the generated embed link will expire after 1 minute and should be immediately embedded in the app once generated. ### Add the embed URL to an <iframe> Within the HTML of your application, create an `iframe` elements with the `src` attribute set to generated embed URL. ``` <iframe src="https://app.box.com/preview/expiring_embed/gvoct6FE!ixgtCKQAziW 9tHPm-jueq4cmS4GnL9RTJRcVEsK_3W8xcxtVo_v6gKpoXY45odgG1QrcjBVYZMrriUyGvcoSM SX8s-smpaFFYQik0R-PCKFtwvbv0lonid6ZfYNbuNFl2j9hOIqBccvHrdVor7i6WvOm6zELzTY 4EWshcyYYBhDbJmYMrq61RtU_kvBe5P..."></iframe> ``` ## Customized Previewer (UI Elements) To leverage advanced preview customization and event handling capabilities, use the Box [UI Preview Element](guide://embed/ui-elements/preview). To set up the Preview Element, start by installing the required components. Install Box Elements and Preview The basic code will resemble the below when adding the JavaScript code to display a new previewer. ``` var preview = new Box.Preview(); preview.show("FILE_ID", "ACCESS_TOKEN", { container: ".preview-container", showDownload: true }); ``` Replace the placeholders in the code sample with the following: - `FILE_ID`: The ID of the file uploaded to the App Token application, which can be obtained from the object returned when uploading the file. - `ACCESS_TOKEN`: The primary Access Token set up when configuring the application or a downscoped version of the token. Due to the elevated privileges of the primary access token it's highly recommended that you use a downscoped version of the token in the Javascript code. See [best practices for downscoping](guide://embed/box-view/best-practices#use-downscoped-tokens). **Reference:** https://developer.box.com/guides/embed/box-view/create-preview/ --- ## Untitled *Type: guide | Category: Embed Box * Setup Before uploading files to Box and previewing them using Box View, a Box application must be created and an access token be generated… # Setup Before uploading files to Box and previewing them using Box View, a Box application must be created and an access token be generated for that application. ## Create App Token App Box View uses an authentication mechanism called **App Token Auth** to store files directly within the account of the application as opposed to a specific Box user. This permits the previewing of files without having to associate the content with a user. The first step is to create the application and authorize it through your admin to begin making API requests to Box. Setup and authorize App Token app App Token apps need to be authorized by the Box admin, otherwise you will receive permission errors when making API requests. To go through app authorization, follow [this guide](guide://authorization/custom-app-approval). ## Generate Access Token With your application loaded, click on the **Configuration** option in the left navigation menu. The configuration page for your application should look like the following. Click on the **Generate Key** button within the **Primary Access Token** section. If you don't have 2FA setup for your developer account, you will be prompted to set up 2FA before you can successfully generate App Tokens. Follow the prompt to set up 2FA. Choose the expiration time for your token, either 30 days, 60 days, or set the token to never expire. Once the app token is generated, copy and store it securely. It won’t be displayed once the page is reloaded since Box stores a one-way hash of the tokens instead of the actual token and cannot retrieve the original token again. **Reference:** https://developer.box.com/guides/embed/box-view/setup/ --- ## Untitled *Type: guide | Category: Embed Box * FAQ How does Box View work? To get started with the New Box View, follow our guide here. Which Preview method, Embed Link or UI Element, is… # FAQ **How does Box View work?** To get started with the New Box View, follow our guide [here](guide://embed/box-view/setup). **Which Preview method, Embed Link or UI Element, is right for me?** Please follow our guide [here](guide://embed/box-view/create-preview) to choose the best method for your use case. **What file types are supported by Box View?** Supported [file types](https://support.box.com/hc/en-us/articles/360043695794-Viewing-Different-File-Types-Supported-in-Box-Content-Preview) can be found in our support article. **Which file types are not supported on mobile with Box View?** - All documents supported on web preview are supported on mobile browsers (Safari for iOS and Chrome). - Full annotations support is available for mobile via the [Content Preview UI Element](guide://embed/ui-elements/preview), which leverages Box Annotations. - Mobile SDKs (for iOS and Android) do not support 360 Videos/Images, and 3D. - Mobile SDKs (for iOS and Android) do not support annotations (both read and write). **What are annotations?** [Annotations](g://embed/ui-elements/annotations) are markup notes on a file rendering and allow developers to provide collaboration capabilities right from within the embedded Box preview in their application. **After uploading a file, how can my application get file representations?** [Box Representations](guide://representations) let you get the digital assets created for files stored in Box. You can use these endpoints to get PDF, text, image, and thumbnail representations for a file. **Can I use Box View with storage providers other than Box?** Currently, Box View is only compatible with files that are stored in Box. You can delete the files from Box once you no longer need to display them. However, you would need to re-upload them again in order to generate the preview. For this reason, we recommend keeping the files stored in Box for at least as long as you want to be able to display them. **How do I fix the CORS error Box gives me when I embed a Box UI Element?** To fix the [CORS](g://security/cors) error, add each domain you wish to allow to make CORS requests via the application's configuration page. Wildcards are supported for the subdomain (`https://*.domain.com`). See the [CORS guide](g://security/cors) for more information. **How can I replace the Box logo that shows up on preview?** See this guide for information on customizing the logo within a [Preview UI Element](g://embed/ui-elements/logo). **Reference:** https://developer.box.com/guides/embed/box-view/faq/ --- ## Untitled *Type: guide | Category: Embed Box * Box View Box View is an embeddable service that allows developers to upload, convert, and display files in their web and mobile apps via a… # Box View Box View is an embeddable service that allows developers to upload, convert, and display files in their web and mobile apps via a high-fidelity, interactive file viewer. ## Features ### View any file Embed documents, images, videos, 360-degree videos and images, 3D models, and dozens of other files in any web or mobile app using a standard `<iframe>`. ### Ease of use Upload files to Box via a secure API and receive an embeddable HTML5 snippet to place into your application's UI. ### Collaboration in context Allow end users to collaborate and mark up documents, presentations, and images with annotations. Users can highlight text or comment on specific areas of a file rendering. ## How does Box View work 1. Upload files into Box using our [secure upload API](e://post-files-content). All content is stored in Box's secure cloud storage infrastructure with virus scanning and 256 bit encryption. 2. Upon upload, files are converted into HTML5 compatible assets, which are designed to render crisply and responsively. 3. An embeddable URL is requested to access the file rendering. Previews can be embedded directly in your application using an `<iframe>` URL. ## Customize your experience with Box Content Preview [Box Content Preview](g://embed/ui-elements/preview) may be used to create customized client-side experiences with the converted files. ## Use cases - Convert and display PDF resumes in a recruiter application - Convert and display course materials, including documents, videos, and PDFs in a student portal - Convert and display HD video in a media room - Convert and display sales collateral, including documents, videos, PDFs, and 3D models in a field sales enablement application **Reference:** https://developer.box.com/guides/embed/box-view/ --- ## Untitled *Type: guide | Category: Embed Box * Upload Files To generate a preview embed link for a file, the file must be uploaded to Box. For most file types, conversion is triggered… # Upload Files To generate a preview embed link for a file, the file must be uploaded to Box. For most file types, conversion is triggered automatically upon upload. However, for video and 3D files, it is triggered upon first preview. No explicit action is required by the user to begin conversion. In either case, conversion is triggered only once per file, and the generated assets are available for as long as the original file is stored in Box. ## Uploading a File To upload a file using the [Box SDKs](pages://sdks-and-tools) or directly with the APIs, you need to use the client ID and App Token that are generated during [application setup](guide://embed/box-view/setup) to authenticate your application. Authenticate your application Once an authenticated client has been created, it may be used to upload files directly to the App Token application for conversion. Upload files to Box **Reference:** https://developer.box.com/guides/embed/box-view/upload-file/ --- ## Untitled *Type: guide | Category: Embed Box * Content Explorer - metadata view With Content Explorer you can also display files based on their metadata. The metadata view uses metadata… # Content Explorer - metadata view With Content Explorer you can also display files based on their metadata. The metadata view uses [metadata template](r://get-metadata-templates-id) and [metadata query](g://metadata/queries) to find the data you want to display. ## Prerequisites - Read the [Content Explorer](g:///embed/ui-elements/explorer) guide. - Check the [metadata terminology](g://metadata/#metadata-terminology). - Check the information on [metadata queries](g://metadata/queries). ## Create and configure an app 1. [Create a Box app](g:///applications/app-types). Add the local development address in the CORS Domains: 2. Generate a [developer token](g://authentication/tokens/developer-tokens). ## Create a metadata template The next step is to create a metadata template. 1. Use [Metadata API](g:///metadata/templates/create) or [Admin Console](https://support.box.com/hc/en-us/articles/360044194033-Customizing-Metadata-Templates) to create the template. 2. Apply an already created template to a Box folder. Make sure you enable the cascade policy. For detailed instructions, see [instructions on customizing and applying templates](https://support.box.com/hc/en-us/articles/360044196173-Using-Metadata). You can also apply a metadata template to a file. ### Display name and key parameters - The `displayName` parameter is the display name of the template visible in the Admin Console. - The `templateKey` parameter is a unique identifier of the template. It needs to be unique across the enterprise for which you create the metadata template. If you don't provide the `templateKey` parameter, API creates a unique one based on the value in `displayName`. - The `[fields].displayName` parameter is the display name of the field as it is shown to the user in the web and mobile apps. - The `[fields].key` parameter is a unique identifier for a specific field in the template. The identifier must be unique within the template to which it belongs. ## Display metadata view Proceed to fill in the necessary properties passed to the Content Explorer. To make things easier, you can use a [sample project](https://github.com/box-community/content-explorer-metadata/tree/main) based on a basic React app to launch metadata view. 1. Clone the metadata sample project. 2. Update the placeholders in [`App.js`](https://github.com/box-community/content-explorer-metadata/blob/main/src/App.js) with actual values: | Parameter | Description | | --- | --- | | DEVELOPER_TOKEN | Developer token generated in the the Developer Console. | | ENTERPRISE_ID | Enterprise ID copied from the General Settings tab of your Box application. | | METADATA_TEMPLATE_NAME | templateKey of your already created metadata template. Note: To make sure you provided the proper name, use the metadata API to retrieve the name, or copy it from the URL in the Admin Console. If you decide to change the template name in the UI, you change the display name only. The name to use in the component is always the one you provided at the beginning. | | METADATA_SOURCE | Source of your metadata. It's a string that combines the scope, enterprise ID, and metadata key. | | ROOTFOLDER_ID | ID of a Box folder to which you want to apply the metadata query and display filtered files. | The `defaultView`, `fieldsToShow`, and `metadataQuery` parameters are already defined in the sample project. Examples of these parameters are available in the sample project. | Parameter | Description | | --- | --- | | defaultView | A required prop to paint the metadata view. If it's not provided, you get the regular file view. | | fieldsToShow | Add or hide specific metadata columns to display in the Content Explorer. | | metadataQuery | Provides a way to find files by searching for the metadata attached to them. For additional information on metadata queries, see this guide. | 1. Pass the required parameters to the Content Explorer component. A sample code for a React component including the Content Explorer metadata view would look as follows: ``` function App() { const token = "<DEVELOPER_TOKEN>"; const rootFolderID = "<ROOTFOLDER_ID>"; const EID = "<ENTERPRISE_ID>"; const templateName = "<METADATA_TEMPLATE_NAME>"; const metadataSource = `enterprise_${EID}.${templateName}`; const metadataSourceFieldName = `metadata.${metadataSource}`; const metadataQuery = { from: metadataSource, query: "key = :arg1", query_params: { arg1: "value" }, ancestor_folder_id: 0, fields: [ `${metadataSourceFieldName}.name`, `${metadataSourceFieldName}.last_contacted_at`, `${metadataSourceFieldName}.industry`, `${metadataSourceFieldName}.role`, ], }; const fieldsToShow = [ // canEdit propetry determines if the user can edit the metadata directly from Content Explorer component { key: `${metadataSourceFieldName}.name`, canEdit: false }, // displayName alows to change the label on metadata column { key: `${metadataSourceFieldName}.industry`, canEdit: false, displayName: "alias" }, { key: `${metadataSourceFieldName}.last_contacted_at`, canEdit: true }, { key: `${metadataSourceFieldName}.role`, canEdit: true }, ]; const defaultView = "metadata"; return ( <IntlProvider locale="en"> <div className="App"> <header className="App-header"> <h2>Metadata view in Content Explorer</h2> </header> <section> <div className="metadata-based-view"> <ContentExplorer rootFolderId={rootFolderID} token={token} metadataQuery={metadataQuery} fieldsToShow={fieldsToShow} defaultView={defaultView} /> </div> </section> </div> </IntlProvider> ); } export default App; ``` ## Metadata keys To decide which fields to show, the Content Explorer uses metadata [field keys](e://post-metadata-templates-schema/#param-fields-key), not the [display names](e://post-metadata-templates-schema/#param-fields-displayName). You can see the display names in the Admin Console and user view, but you can obtain the field keys through the API. The field keys are not changing, even if you change the metadata display name. This ensures that the functionality works properly, despite any changes to the metadata in UI view. ### Metadata keys sanitization [Keys](e://post-metadata-templates-schema/#param-fields-key) are restricted to alphanumeric characters only: - No hyphens `-` or underscores `_` are permitted. - Only letters (`a-z, A-Z`) and numbers (`0-9`) are allowed. **Non-Latin characters:** If keys contain characters from non-Latin alphabets (such as Cyrillic, Arabic, Chinese, etc.) they are automatically renamed to generic identifiers: - `field` for the first occurrence - `field1`, `field2`, and so on for subsequent occurrences Keys are based on the display names. **TIP**: For a detailed flow, see [Metadata view blog post](https://medium.com/box-developer-blog/metadata-view-in-box-content-explorer-4978e47e97e9). **Reference:** https://developer.box.com/guides/embed/ui-elements/explorer-metadata/ --- ## Untitled *Type: guide | Category: Embed Box * Box Edit Custom Domains In order to integrate a third party web application with Box Tools, you will need to explicitly add your application… # Box Edit Custom Domains In order to integrate a third party web application with Box Tools, you will need to explicitly add your application's URL. On Windows, this is achieved by adding a registry key. On MacOS, you will need to run few terminal commands to add and remove domains. Adding domains to a safelist was added in **Box Tools version 4.5.0**. ## Safelisting on Windows Before starting the domain safelisting installation, please download the required scripts from the provided `.rar` [here](https://cloud.box.com/s/kvc9cysgq1y2yldpvciwlpt7093ho78l). ### Per User Installation Open `Add_OpenWith_WhiteListed_Domain.reg` in a text editor. Additional entries can be added on a new line. Close the file (save changes), open a command prompt with admin privileges, and navigate to the .reg file and type the following command. ``` reg import "Add_OpenWith_WhiteListed_Domain.reg" ``` ### Per Machine Installation Open the following file in a text editor: - `x64`: `Per Machine\64 bit\Add_OpenWith_WhiteListed_Domain.reg` - `x86`: `Per Machine\32 bit\Add_OpenWith_WhiteListed_Domain.reg` Replace the placeholder domain with the domain you would like allow. Additional entries may be added on a new line. Close the file (save changes), open a  command prompt with admin privileges, and navigate the .reg file and type the following command: ``` reg import "Add_OpenWith_WhiteListed_Domain.reg" ``` Restart the Windows service: **Box Local Com Service** (`Box Edit.exe`) using one of the following methods. #### Via the command prompt In a command prompt, enter: - `net stop "Box Local Com Service"` - `net start "Box Local Com Service"` #### Via the UI Press `Windows + R` and type `services.msc`. Restart `Box Edit.exe` by finding `Box Edit` in the system tray. Right click and select **Quit**. Open `%programfiles%\Box\Box Edit` and run `Box Edit.exe`. ### Removing - Run `Remove_ALL_OpenWith_WhiteListed_Domain.reg` to remove all domains at once - Run `Remove_OpenWith_WhiteListed_Domain.reg` to remove specific domains. Use the instructions above to add domains to this .reg, which will remove domains. ## Safelisting on MacOS ### Steps Download the bash script [here](https://cloud.box.com/s/z5qhc7rts6mzrhzfx6cpxeb5ed4ve5u6). Open the Terminal, go to the folder where the bash script was downloaded, and add the right permissions by running this command: ``` chmod u+rx OpenWith.sh ``` To **add** domains, run the following command in a terminal: ``` ./OpenWith.sh -a domain1 domain2 ... ``` To **remove** domains, run the following command in a terminal: ``` ./OpenWith.sh -r domain1 domain2 ... ``` To **clear all** domains, run the following command in a terminal: ``` ./OpenWith.sh -c ``` To **list** all domains, run the following command in a terminal: ``` ./OpenWith.sh -l ``` ### Notes - When safelisting domains ensure you are entering the domains without the HTTP protocol (for example without `https://`) or any trailing path like `yourdomain.com/page/3`. - All requests most come from a secure origin via HTTPS. - Safelisting subdomains and ports is possible as the wildcard `*` is supported. For example, all subdomains could be safelisted by adding `*.yourdomain.com` to your list. ## Uninstalling When Box Tools is uninstalled, all domains will be removed. **Reference:** https://developer.box.com/guides/embed/ui-elements/custom-domains/ --- ## Untitled *Type: guide | Category: Embed Box * Browser Support Box UI elements are supported in the following browsers. Chrome, Firefox, Safari, and Edge (latest 2 versions) Mobile Chrome… # Browser Support Box UI elements are supported in the following browsers. - Chrome, Firefox, Safari, and Edge (latest 2 versions) - Mobile Chrome and Safari **Reference:** https://developer.box.com/guides/embed/ui-elements/browser/ --- ## Untitled *Type: guide | Category: Embed Box * Annotations Box Annotations allow developers to provide collaboration capabilities right from within the embedded Box preview in their… # Annotations Box Annotations allow developers to provide collaboration capabilities right from within the embedded Box preview in their application. Box Annotations fit a wide range of use cases and can be used to draw the previewer's attention and/or provide feedback on specific parts of a document or images. Learn more about Content Preview Box Content Preview currently supports four annotation types - highlight comment, highlight only, draw, and point annotation. Box Annotations are today supported on documents and image previews only. You can find the full list of supported file types for Box Content Preview [here](https://support.box.com/hc/en-us/articles/360043695794-Viewing-Different-File-Types-Supported-in-Box-Content-Preview). ## Browser support [Learn more about browser support](g://embed/ui-elements/browser) for Box UI element. ## Usage Box Annotations can be used by pulling from our NPM package. ## Initialization ``` /* global BoxAnnotations */ const boxAnnotations = new BoxAnnotations(); const annotatorConf = boxAnnotations.determineAnnotator( options, disabledAnnotationTypes ); // Construct and init annotator const annotator = new annotatorConf.CONSTRUCTOR(options); annotator.init(scale); ``` Where `disabledAnnotationTypes` is a string of valid annotation types to disable. See below for more details on viewer specific annotation configurations. ## Authentication The UI Elements are designed in an authentication agnostic way so whether you are using UI Elements for users who have Box accounts (Managed Users) or non-Box accounts (App Users), UI Elements should work out of the box. The reason for this is that UI Elements only expect a "token" to be passed in for authentication, and Box provides two different ways to generate tokens - OAuth and JWT. Learn about selecting an authentication method If your application requires the end user to only be able to access a subset of the Annotations functionality, you can use [Downscoping](g://authentication/tokens/downscope) to appropriately downscope your Access Token to a resulting token that has the desired set of permissions, and can thus, be securely passed to the end user client initializing Annotations. Below are a set of new Annotation-specific scopes to go alongside Downscoping. These allow developers to enable/disable functionality on Box Annotations by configuring the appropriate scopes on the downscoped token. To learn more, see Dedicated scopes for the Box UI Elements. ## Parameters & Options ``` const annotator = new annotatorConf.CONSTRUCTOR({ annotator, apiHost, token, container, file: { id, file_version: { id }, permissions }, isMobile, hasTouch, locale, modeButtons: { // Annotation mode buttons, i.e. point, draw, etc point: { // Accessibilty message for the point annotation mode button title: "Point annotation mode", // CSS selector for the point annotation mode button selector: ".bp-btn-annotate-point" } } }); ``` | Parameter | Default | Description | | --- | --- | --- | | annotator | | Viewer-specific annotator configurations object | | apiHost | | Host for Box API calls for example https://app.box.com/api | | fileId | | Box file ID | | token | | A string auth token, see below for details on how to generate annotator tokens with appropriate scopes | | container | | DOM node or selector where Preview should be placed | | file | | File metadata object | | file.id | | String Box_File id | | file.file_version.id | | String Box_File_Version id | | file.permissions | | File permissions object, see below on how to scope permissions | | Option | Default | Description | | --- | --- | --- | | modeButtons | | Object containing a CSS selector and accessibility message for the annotation mode button, see parameters and options example above | | isMobile | false | Whether the user's browser is on a mobile device | | hasTouch | false | Whether the mobile browser has touch enabled | | locale | en-US | Shared link URL | ### Base Scope | Scope Name | What permissions does it grant? | | --- | --- | | base_preview | Allows preview access to a file or files in a folder based on user/file/token permissions | ### Feature Scopes | Scope Name | What permissions does it grant? | | --- | --- | | item_download | Allows files/folders contents to be downloaded | | annotation_view_self | Allows user to view their own annotations | | annotation_view_all | Allows user to view all annotations on the file | | annotation_edit | Allows user to edit their own annotations (includes annotation_view_self) | ### Sample Scenarios | Scenario | Scope Combinations | | --- | --- | | User wants basic preview functionality + ability to edit own annotations | base_preview + annotation_edit | | User wants basic preview functionality + ability to edit own annotations + ability to select text on documents | base_preview + annotation_edit + item_download | | User wants basic preview functionality + ability to view all annotations + ability to edit own annotations | base_preview + annotation_view_all + annotation_edit | | User wants basic preview functionality + ability to view only their own annotations | base_preview + annotation_view_self | ## Enabling/Disabling Annotations and Annotation Types Annotation types can be selectively turned off through preview options. Viewer options override global `showAnnotations` value, for that viewer. See Box Content Preview for more details on how to set up the Preview instances that are used with Box Annotations here. ``` preview.show(..., { showAnnotations: Boolean }); ``` Combined with the following: ``` preview.show(..., { viewers: { VIEWER_NAME: { annotations: { enabled: Boolean, enabledTypes: String[] | null } } } }); ``` This turns the annotations on if `enabled` is set to `true`. This respects the `showAnnotations` value if empty. The `enabledTypes` value is a list of annotation types to enable for this viewer. If empty, will respect default types for that annotator. ### Example Enable all annotations, turn off for Image Viewers, and enable only point annotations on Document viewer: ``` preview.show(fileId, token, { showAnnotations: true, viewers: { Image: { annotations: { enabled: false } }, Document: { annotations: { enabled: true, enabledTypes: ["point"] } } } }); ``` ## Annotators The name of an annotator can be one of the following `DocAnnotator` or `ImageAnnotator`. Call `boxAnnotations.getAnnotators()` to get the list of possible annotators. ## Additional Methods - `annotator.init()` initializes the annotator. - `annotator.isModeAnnotatable(/* String */ type)` returns whether or not the current annotation mode is enabled for the current viewer/annotator. - `annotator.showModeAnnotateButton(/* String */ currentMode)` shows the annotate button for the specified annotation mode. - `annotator.getAnnotateButton(/* String */ annotatorSelector)` gets the annotation button element. - `annotator.showAnnotations()` fetches and shows saved annotations. - `annotator.hideAnnotations()` hides annotations. - `annotator.hideAnnotationsOnPage(/* number */ pageNum)` hides annotations on a specified page. - `annotator.setScale()` sets the zoom scale. - `annotator.toggleAnnotationHandler()` toggles annotation modes on and off. When an annotation mode is on, annotation threads will be created at that location. - `annotator.disableAnnotationMode(/* String */ mode, /* HTMLElement */ buttonEl)` disables the specified annotation mode. - `annotator.enableAnnotationMode(/* String */ mode, /* HTMLElement */ buttonEl)` enables the specified annotation mode. - `annotator.getAnnotatedEl(/* HTMLElement */ containerEl)` determines the annotated element in the viewer. - `annotator.createAnnotationThread(/* Annotation[] */ annotations, /* Object */ location, /* String */ [annotation type])` creates the proper type of annotation thread, adds it to the in-memory map, and returns it. ## Events Events can be bound to the annotator object with `addListener` and removed with `removeListener`. Event listeners should be bound before `showAnnotations()` is called, otherwise events can be missed. ``` /* global BoxAnnotations */ const boxAnnotations = new BoxAnnotations(); const annotatorConf = boxAnnotations.determineAnnotator( options, disabledAnnotationTypes ); // Construct and init annotator const annotator = new annotatorConf.CONSTRUCTOR(options); var listener = value => { // Do something with value }; // Attach listener before calling show otherwise events can be missed annotator.addListener(EVENTNAME, listener); // Initialize a annotator annotator.showAnnotations(); // Remove listener when appropriate annotator.removeListener(EVENTNAME, listener); ``` `EVENTNAME` can be one of the following - `annotator` event will be triggered when we have the annotator instance first available. Box Annotations trigger this event before `load` so that clients can attach their listeners before the `load` event is triggered from Box Content Preview. - `annotationsfetched` event will be triggered when annotations have been fetched from the Box API. - `annotationmodeenter` event will be triggered on when an annotation mode is entered. The event data will contain: ``` { // Annotation mode that was entered mode: 'point', // Optional CSS selector for the container's header headerSelector: '.bp-preview-header', } ``` `annotationmodeexit` event will be triggered on when an annotation mode is exited. The event data will contain: ``` { // Annotation mode that was exited mode: 'point', // Optional CSS selector for the container's header headerSelector: '.bp-preview-header', } ``` `annotationerror` event will be triggered when an annotation error has occurred. The event data will contain: ``` { message: 'message', // Error message to show } ``` `annotationpending` event will be triggered when an annotation thread was created but has not yet been saved on the server. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` `annotationthreadsaved` event will be triggered when an annotation thread was saved on the server. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` `annotationthreaddeleted` event will be triggered when an annotation thread was deleted on the server. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` `annotationsaved` event will be triggered when an annotation is added and saved to an existing annotation thread on the server. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` `annotationdeleted` event will be triggered when an annotation is deleted from an existing thread on the server. The entire annotation thread is not deleted. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` `annotationcanceled` event will be triggered when an annotation is canceled from posting on either a new or existing thread. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` `annotationdeleteerror` event will be triggered when an error occurs while deleting an annotation on either a new or existing thread. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` `annotationcreateerror` event will be triggered when an error occurs while posting an annotation on either a new or existing thread. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` `annotatorevent` Each annotator will trigger its own sets of events. For example, the Image Annotator will trigger `rotate` or `resize`, etc. while other annotator may trigger another set of events. The Annotator wrapper will also re-emit events at the Preview level in Box Content Preview, with event data containing: ``` { event: EVENTNAME, // Event name data: DATA, // Event data object annotatorName: ANNOTATORNAME, // Name of the annotator fileVersionId: fileVersionId // The file version id fileId: fileId // The file id } ``` ### Example event usage ``` preview.addListener("annotator", viewer => { annotator.addListener("annotationsfetched", () => { // Do something when annotations are fetched on a preview }); }); // Event listeners can be attached to viewers preview.addListener("load", data => { var viewer = data.viewer; viewer.addListener("annotationsfetched", () => { // Do something when annotations are fetched on a preview }); }); // Event listeners can be attached to annotators preview.addListener("load", data => { var annotator = data.viewer.annotator; annotator.addListener("annotationsfetched", () => { // Do something when annotations are fetched on a preview }); }); preview.addListener("annotatorevent", data => { if (data.event === "annotationsfetched") { // Do something when annotations are fetched on a preview } else if (data.event === "annotationerror") { // Do something different when an annotation error has occurred } else { } }); preview.addListener("annotatorevent", data => { if (data.viewerName === "Image") { if (data.event === "annotationsfetched") { // Do something when annotations are fetched on an image preview } } else if (data.viewerName === "MultiImage") { if (data.event === "annotationsfetched") { // Do something different when annotations are fetched on a multi-page image } } else { } }); preview.addListener("annotationsfetched", data => { if (data.viewerName === "Image") { // Do something when annotations are fetched on an image preview } else if (data.viewerName === "MultiImage") { // Do something different when annotations are fetched on a multi-page image } else { } }); ``` ## Annotation Thread ### Thread Methods The following methods are available for the annotation threads. | Method Name | Explanation | Method Parameters | | --- | --- | --- | | createDialog | Creates the dialog for the thread | | | show | Shows the annotation indicator | | | hide | Hides the annotation indicator | | | reset | Resets thread state to 'inactive' | | | showDialog | Shows the appropriate dialog for this thread | | | hideDialog | Hides the appropriate indicator for this thread | | | saveAnnotation | Saves an annotation locally and on the server | {string} annotation type, {text} text of annotation to save | | deleteAnnotation | Deletes an annotation | {string} annotation ID, {boolean} whether or not to delete on server, default true | ### Thread Events All annotation threads trigger the following events. The event data will contain: ``` { data: { type: 'point', // Annotation type threadID: '123abc', userId: '456def', threadNumber: '1' // Thread number from Annotations API } } ``` | Event Name | Explanation | | --- | --- | | annotationpending | An annotation thread was created but has not yet been saved on the server. | | annotationthreadsaved | An annotation thread was saved on the server. | | annotationthreaddeleted | An annotation thread was deleted on the server. | | annotationsaved | An annotation thread was added and saved to an existing annotation thread on the server | | annotationdeleted | An annotation thread was deleted from an existing thread on the server. The entire annotation thread is not deleted. | | annotationcanceled | An annotation thread was canceled from posting on either a new or existing thread. | | annotationdeleteerror | An error occurs while deleting an annotation on either a new or existing thread. | | annotationcreateerror | An error occurs while posting an annotation on either a new or existing thread. | See the **Events** section above for example event usage. ## Annotation Dialog ### Dialog Methods The following methods are available for the annotation dialog. | Method Name | Explanation | Method Parameters | | --- | --- | --- | | show | Positions and shows the dialog | | | hide | Hides the dialog | | | hideMobileDialog | Hides and resets the shared mobile dialog | | | addAnnotation | Adds an annotation to the dialog | {Annotation} annotation to add | | removeAnnotation | Removes an annotation from the dialog | {string} annotation ID | | postAnnotation | Posts an annotation in the dialog | {string} annotation text to post | | position | Positions the dialog | | ## Supported Annotation Types Point annotations are supported on both document and image formats. Highlight comment, highlight only, and draw annotations are only supported on document formats. Supported document file extensions: `pdf`, `doc`, `docx`, `ppt`, `pptx`, `xlsx`, `xls`, `xlsm`. Supported image file extensions: `ai`, `bmp`, `dcm`, `eps`, `gif`, `idml`, `indd`, `indt`, `inx``png`, `ps`, `psd`, `svs`, `tga`, `tif`, `tiff`. **Reference:** https://developer.box.com/guides/embed/ui-elements/annotations/ --- ## Untitled *Type: guide | Category: Embed Box * Customize Access Motivation Box UI Elements are initialized on the client and make API calls directly to Box. Thus, a valid access token… # Customize Access ## Motivation Box UI Elements are initialized on the client and make API calls directly to Box. Thus, a valid access token must live on the client because all Box API requests need to be authenticated. [Token Exchange](g://authentication/tokens/downscope) is a mechanism to exchange a "parent token" (a token for your managed or app user, service account, or application) to a "child token" which is scoped down to the minimum set of required permissions so it can be securely sent down to the client without elevating client privileges. The Box UI Elements are designed to adapt to the permissions on the token, so an additional advantage of using Token Exchange with them is that front-end developers won't have to manually toggle UI controls on/off as long as the correct set of permissions are present on the client token. This behavior mimics the experience in the Box application as well. For example, if a user with "Preview only" permissions to a folder does not see the "Download" button present in the UI. This blueprint covers how to use Token Exchange with UI Elements in your application and example use cases. - **Making API calls from client more secure:** As a general security practice, we recommend generating and sending downscoped tokens per every action performed by the user to limit exposure on the client. For example, even if a user should have preview and share access to a file, instead of sending the user token to the client which would give them complete user-level access, we suggest downscoping the token using Token Exchange and sending them a "preview only" token when they wish to preview a file and a "share" token when they want to share a file. - **Creating a custom permissions model:** If you are building an application using UI Elements and the default Box access levels don't fit your permission model, you can start out with a fully scoped token for all your users and trim them down using Token Exchange on the fly to map to your custom permissions model. - **Using Box services transactionally (no Box user accounts):** If you are not creating users in Box and are using Box services transactionally, you won't have access to user level tokens. In such cases, you can use Token Exchange to scope down the Service Account token to an appropriately scoped token. - **Creating a user only to give them access to another user's content:** If you need to provide an end user "one time" access to another app/managed user's content, Token Exchange can be used to downscope the app/managed user token to the specific permissions and file/folders you want to give the end user access to, and pass it down to UI Elements to give them access to that content. For example, using Token Exchange, you can downscope a user token to have read-only access to content and pass it down to another user. ## Implementation The solution for all of the above is using Token Exchange to exchange a parent token for a downscoped token and initializing the UI Element using that token. Token Exchange takes in the "parent token", "list of scopes" and optionally a file/folder ID as the input arguments, and returns a token that is scoped down to those exact set of scopes and the respective file/folder ID, if present in the input arguments. # Dedicated scopes designed for UI Elements We have designed a set of scopes that work seamlessly with the UI Elements. While token exchange works with all Box scopes, we recommend using these scopes along with UI Elements since they include the exact set of permissions required for base functionality as well as incremental permissions for added functionality. ## Developer Flow Now that you understand the different scopes, let's walk through a scenario for using Token Exchange with a UI Element. **Scenario:** Provide a user with the ability to browse a folder tree using the Box Content Explorer UI Element and allow them to preview and download files. Sharing should be turned off. **Steps:** Create a Managed User, App User or Service Account depending on your use case. You will use this user or application's token as the parent token for Token Exchange. To generate the user token follow: - Authentication with OAuth guide if you would like to create a Managed User - Authentication with JWT guide if you would like to create an App User or Service Account Add the user you created above as a Collaborator to the content using the Create Collaborator API as shown below. This step gives the user access to the content if not already under the user's account. If the file/folder was created under this user's account, then the user by default has "Owner" access to the folder so you can skip the collaboration step. ``` curl https://api.box.com/2.0/collaborations \ -H "authorization: Bearer [ACCESS_TOKEN]" \ -d '{"item": { "id": "123456", "type": "folder"}, "accessible_by": { "id": "USER_ID", "type": "user" }, "role": "editor"}' \ -X POST ``` # Access Levels in Box There are [7 different access levels](https://community.box.com/t5/How-To-Guides-for-Sharing/What-Are-The-Different-Access-Levels-For-Collaborators/ta-p/144) that a Box user can be collaborated as on a file/folder in Box. If the file/folder was created under this user's account, then the user has "Owner" access to the folder by default so you can skip the collaboration step. - Use the Token Exchange API to exchange the parent token for a child token that contains the base scope for Content Explorer (`base_explorer`), `item_download` and `item_preview` scopes enabled for the specific `folder_id` `123456`. We strongly recommend performing this step on the application server. ### Request ``` curl https://api.box.com/oauth2/token \ -d 'subject_token=ACCESS_TOKEN' \ -d 'subject_token_type=urn:ietf:params:oauth:token-type:access_token' \ -d 'scope=item_upload item_preview base_explorer' \ -d 'resource=https://api.box.com/2.0/folders/123456' \ -d 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \ -X POST ``` ### Response ``` { "access_token": "CHILD_TOKEN", "expires_in": 4247, "token_type": "bearer", "restricted_to": [ { "scope": "base_explorer", "object": { "type": "folder", "id": "123456", "sequence_id": "0", "etag": "0", "name": "FOLDER_NAME" } }, { "scope": "item_download", "object": { "type": "folder", "id": "123456", "sequence_id": "0", "etag": "0", "name": "FOLDER_NAME" } }, { "scope": "item_preview", "object": { "type": "folder", "id": "123456", "sequence_id": "0", "etag": "0", "name": "FOLDER_NAME" } } ], "issued_token_type": "urn:ietf:params:oauth:token-type:access_token" } ``` The `CHILD_TOKEN` obtained above is scoped down to only include download and preview permissions for folder id `123456` and its children. Use this `CHILD_TOKEN` in your Content Explorer UI Element. To see a quick demo, you can use our Content Explorer UI Element CodePen Sample and replace the access token and folder id values in the JS Tab. Click "Run". You should see the Content Explorer initialized at the folder you specified. Also, notice that your Content Explorer no longer shows the "Share" button as it would have with the parent (user) token. ## When NOT to use Token Exchange **Does not replace Users or Groups in Box:** We recommend not using Token Exchange as a replacement to creating users in Box. One way to determine whether you should create Box users, is by doing an assessment to determine if it makes logical sense for every end user of your application to have a copy of their own content. Here are some benefits of maintaining user level accounts in Box, which you wouldn't get by using Token Exchange alone. - **Content isolation/security:** It's better to have user level accounts since in the case of the parent token accidentally leaking, you would only be compromising the content of a single user vs. all users of your enterprise. - **Performance:** Creating users/groups in Box is also useful as your application does not have to determine the appropriate permissions at the time of accessing content since that is likely to affect the performance of your application. - **User level tracking/auditing:** Several Box features such as auditing, access stats, retention, etc. leverage Box's user model. If it is essential for you to use those features for you then you would have to create user-level accounts. **Does not replace Collaborations in Box:** Collaborations is a more standard and easier to scale way to provide Box users with access to content. Also, managing content access through collaborations in Box requires your application to manage lesser code/data on which user should have access to what content. If you are using Token Exchange as a replacement to Collaborations, you will need to keep a mapping of every user -> every file and folder that they should have access to and that could get out of control pretty quickly. **Caching the downscoped tokens:** If performance is critical to your application, you should pre-cache downscoped tokens on the server side. If you are pre-caching tokens, we recommend implementing retries as the tokens expire within 1 hour. # Token Lifespan The lifespan of parent and child tokens are not mutually dependent, for example when generating a child token doesn't render the parent token inactive. Similarly, generating more child tokens doesn't impact the previous child tokens in any way. ## Example Scenarios ### Scenario #1: More secure client API calls An equity-investment firm is building out a partner/investor portal to broadcast information (view-only access) to investors published by the employees. They create app users for each of their external customers and employees have provisioned Box accounts which they used to publish content. All app users are collaborated on published content as Viewer Uploader, so they can both preview as well as upload content in their account as needed. Once an investor/partner signs in they are taken to a portal where they can view as well as upload information. Since both preview and upload require the API calls to be made via the client, instead of passing down a “Viewer Uploader” token, the application uses Token Exchange to downscope the token appropriately based on the action that the user is trying to perform. This ensures that if the token is compromised, data leakage is minimized thereby improving the overall security posture of the application. ### Scenario #2: A custom permissions model A large fin-tech company is building a secure client vault to manage investments for their clients. They are also using Box UI Elements to build out the content management front end of their application. They create app users as usual for each one of their clients and app advisors. When they wanted to share content across app users, they collaborate the app user(s) as "Editor" role (Box's role). This guarantees that every app user had full access to every other user’s content. To enable a user to access content via the UI Elements, the application does not provide the app user token to the client directly as the app user may be collaborated as an "Editor" into other user's content (highly privileged). Instead, it uses Token Exchange using the app user token to generate a downscoped token that limits: - the scope of what the token can be used for (view, upload, download, browse, share, etc.) and/or - the specific files that the user should have access to ### Scenario #3: Process Flows A not-for-profit union bank is developing a loan processing application using Box's secure content layer to facilitate the sharing of documents between loan applicants and internal users (loan processors and underwriters). The basic process is as follows: - When customers apply for a loan they must submit documents through a custom-built web portal as a part of the process (proof of income, identity etc.) - Box is used as the intermediary for sending/receiving docs - Internal employees need to upload files for customers - Internal employees can access documents through a custom web portal as well as Box Web app The application developers used Token Exchange along with UI Elements to build out a loan process management solution, where the application server downscopes the loan application's app user token based on which operations the client needs to perform, and passes it down to the clients (customers and loan officers). Using these downscoped tokens, the UI Elements are able to show the right controls/buttons to indicate to the user which actions they can perform (example: upload button is grayed out from the content explorer UI Elements if the downscoped token passed doesn't contain upload permissions). ### Scenario #4: Transactional Flows A Learning Management System provider is using Box Platform to power preview in their application. All users and associated permissions are managed by the application outside Box. From Box's perspective, all API calls made by the application are on its own behalf (any not any individual user), and all content stored and previewed belongs to the application and not to a single user. In this case, the application developer is using a sliver of Box's overall capabilities (for example Preview) transactionally and none of the other secure content sharing and collaboration capabilities. In fact, this is a key use case for many customers. Consider a straightforward use case of the application - the end user needs to upload a file and then preview it in the application itself. To do this the application is using the Content Uploader and Content Preview UI Elements, respectively. Since both preview + upload are bandwidth heavy operations, the application should not proxy the traffic and instead allow the client to perform these operations directly against Box. To make calls against Box, all UI Elements require a valid access token to be available on the client. But the application should never pass down the privileged "service account" token to the client which would give the client access to all content ever uploaded through the application. Instead, the application uses Token Exchange to down-scope it's service account token to an upload-only token to allow the client to upload files via the Upload UI Element, and a separate preview-only token to let the client preview via the Preview UI Element. ## Anti-patterns These anti-patterns have been included here to help you identify patterns that we do not recommend as they will either make your app development more challenging, your application less secure or performing or both. If you find yourself implementing any of these patterns on your app, please reach out to us via Box support so we can help you out. ### Passing privileged tokens to client Please NEVER DO THIS. This can potentially compromise the security of content in your Box enterprise. Always use token exchange to provide end users with the exact set of permissions. ### Proxying/filtering API responses If you are proxying/filtering API responses from Box only to limit data/content exposure to the client, you should try to see if using Token Exchange allows you to limit the exposure. This is especially true for high-bandwidth operations such as preview, download, and upload which are bandwidth intensive and so we recommend that the client performs those operations directly with Box. **Reference:** https://developer.box.com/guides/embed/ui-elements/access/ --- ## Untitled *Type: guide | Category: Embed Box * UI Elements Box UI Elements are pre-built UI components that allow developers to add elements of the main Box web application into their own… # UI Elements Box UI Elements are pre-built UI components that allow developers to add elements of the main Box web application into their own applications. They can be used to navigate through, upload, preview, and select content stored on Box and are available both as React components and framework-agnostic JavaScript libraries. ## Available Elements Box offers several UI Elements to create common user experiences with files and folders in an application. The available UI Elements are: - [Content Explorer](g://embed/ui-elements/explorer)- Allow users to search and browse through files and folders - [Content Open With](g://embed/ui-elements/open-with) - Allow users to open content stored in box with a partner application using an embedded dropdown We no longer support the `OpenWith` UI element for any new customers as of December 21, 2021. - [Content Picker](g://embed/ui-elements/picker) - Allow users to select files or folders from their Box account - [Content Preview](g://embed/ui-elements/preview) - Display interactive viewers for documents, images, audio, video, and more - [Content Sidebar](g://embed/ui-elements/sidebar) - Display a sidebar for file metadata and activity feed information - [Content Uploader](g://embed/ui-elements/uploader) - Allow users to upload files by selecting or using drag-and-drop UI Elements can be used in isolation or joined together to construct common user flows with content, such as uploading and then viewing a file. **Reference:** https://developer.box.com/guides/embed/ui-elements/ --- ## Untitled *Type: guide | Category: Embed Box * Content Explorer The Box Content Explorer UI Element allows developers to embed a folder view of content stored on Box in their desktop or… # Content Explorer The Box Content Explorer UI Element allows developers to embed a folder view of content stored on Box in their desktop or mobile web application. The library fetches information about a specified folder through the Box API and then renders the content in a folder view, similar to the main Box web application. Users can then navigate through the folder hierarchy and perform file operations like rename, delete, and share. Content Explorer comes with a metadata view that uses metadata query to find files and folders based on their metadata. The data is then displayed in the embedded view. ## Installation [Learn how to install](g://embed/ui-elements/installation) Box UI elements either through NPM or the Box CDN. ## Authentication The UI Elements are designed in an authentication agnostic way so whether you are using UI Elements for users who have Box accounts (Managed Users) or non-Box accounts (App Users), UI Elements should work out of the box. The reason for this is that UI Elements only expect a "token" to be passed in for authentication, and Box provides two different ways to generate tokens - OAuth and JWT. Learn about selecting an authentication method ## Sample HTML ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Box Content Explorer Demo</title> <!-- Latest version of the explorer css for your locale --> <link rel="stylesheet" href="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/explorer.css" /> </head> <body> <div class="container" style="height:600px"></div> <!-- Latest version of the explorer js for your locale --> <script src="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/explorer.js"></script> <script> var folderId = "123"; var accessToken = "abc"; var contentExplorer = new Box.ContentExplorer(); contentExplorer.show(folderId, accessToken, { container: ".container", }); </script> </body> </html> ``` ## Demo ## API ``` const { ContentExplorer } = Box; const contentExplorer = new ContentExplorer(); /** * Shows the content explorer. * * @param {string} folderId - The root folder id * @param {string} accessToken - Box API access token * @param {Object} [options] - Options * @return {void} */ contentExplorer.show(folderId, accessToken, options); /** * Hides the content explorer, removes all event listeners, and clears out the * HTML. * * @return {void} */ contentExplorer.hide(); /** * Clears out the internal in-memory * cache for the content explorer forcing * re-load of items via the API. * * @public * @return {void} */ contentExplorer.clearCache(); /** * Adds an event listener to the content explorer. Listeners should be added * before calling show() so no events are missed. * * @param {string} eventName - Name of the event * @param {Function} listener - Callback function * @return {void} */ contentExplorer.addListener(eventName, listener); /** * Removes an event listener from the content explorer. * * @param {string} eventName - Name of the event * @param {Function} listener - Callback function * @return {void} */ contentExplorer.removeListener(eventName, listener); /** * Removes all event listeners from the content explorer. * * @return {void} */ contentExplorer.removeAllListeners(); ``` ### Parameters | Parameter | Type | Description | | --- | --- | --- | | folderId | String | Box Folder ID. This will be the ID of the folder you want to navigate. If you want to use the Box All Files folder, then use 0 as the folderId. | | accessToken | String | Box API access token to use. This should have read/write access to the folder above. The value passed in for the token is assumed to never expire while the explorer is visible. | | options | Object | Optional options. See below for details. For example: contentExplorer.show(FOLDER_ID, TOKEN, {canDelete: false}) would be used to hide the delete option. | ### Options | Parameter | Type | Default | Description | | --- | --- | --- | --- | | container | String | document.body | CSS selector of the container in which the content explorer should be placed. Calling hide() will clear out this container. | | sortBy | String | name | The initial sort by option for the content list. Value can be either id, name, date or size. | | sortDirection | String | ASC | The initial sort direction option for the content list. Value should be either ASC or DESC. | | logoUrl | String | | URL of custom logo to show in header. If this value is the string box then the box logo will show. | | canPreview | Boolean | true | If this option is set to true AND can_preview permission on the file is true, files on the content explorer will be clickable. Clicking on a file will launch preview of that file. This option has no effect when the file permission can_preview is set to false. This is only applicable to files that can be previewed. | | canDownload | Boolean | true | Visually hides the download option if this is set to false. Hiding the option alone will not prevent downloading unless the file permissions also set can_download to false. This option has no effect when the file permission can_download is set to false. This is only applicable to files. | | canDelete | Boolean | true | Visually hides the delete option if this is set to false. Hiding the option alone will not prevent deleting unless the item permissions also set can_delete to false. This option has no effect when the item permission can_delete is set to false. | | canRename | Boolean | true | Visually hides the rename option if this is set to false. Hiding the option alone will not prevent renaming unless the item permissions also set can_rename to false. | | canUpload | Boolean | true | Visually hides the upload option if this is set to false. Hiding the option alone will not prevent uploading unless the current folder permissions also set can_upload to false. This option has no effect when the folder permission can_upload is set to false. | | canCreateNewFolder | Boolean | true | Visually hides the create new folder option. Hiding the option alone will not prevent creating a new folder unless the folder item permissions also set can_upload to false. This option has no effect when the folder item permission can_upload is set to false. | | canShare | Boolean | true | Visually hides the share button if set to false. Hiding the button alone will not prevent sharing unless the item permissions also set can_share to false. This option has no effect when the item permission can_share is set to false. | | canSetShareAccess | Boolean | true | Visually hides the sharing drop down select that allows changing share access, if set to false. Hiding the select drop down alone will not prevent changing the share access unless the item permissions also set can_set_share_access to false. This option has no effect when the item permission can_set_share_access is set to false. | | sharedLink | String | | Shared link URL, required if folder is shared and the access token doesn't belong to an owner or collaborator of the file. | | sharedLinkPassword | String | | Shared link password, required if shared link has a password. | | size | String | undefined | Indicates to the content explorer to fit within a small or large width container. Value can be absent or one of small or large. If absent the UI Element will adapt to its container and automatically switch between small width or large width mode. | | isTouch | Boolean | Defaults to the browser and device's default touch support | Indicates to the Content Explorer that it's is being rendered on a touch enabled device. | | autoFocus | Boolean | false | When set to true, the item grid will get focus on initial load. | | defaultView | String | files | Value can be either be files, recents or metadata. When set to recents, by default you will see recent items instead of the regular file/folder structure. metadata is required to display the metadata view in Content Explorer. If not provided, you'll get a regular folder view. | | requestInterceptor | Function | | Function to intercept requests. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | | responseInterceptor | Function | | Function to intercept responses. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | | ContentOpenWithProps | Object | { show: false } | Allows you to show the Open With Element when previewing via the explorer. | | token | String | | Developer token generated in the Developer Console. | | metadataQuery | Object | | Metadata query used to get the information for the metadata view. | | rootFolderID | String | | Folder ID with a metadata template applied. metadataQuery will apply to this folder. | | fieldsToShow | Object | | The metadata fields/columns to view - must be valid field names from the metadata template. | ### Events | Event Name | Event Data | Description | | --- | --- | --- | | select | Array<File | Web Link | Folder> | Will be fired when item rows are selected. | | rename | File | Web Link | Folder | Will be fired when an item is renamed. | | preview | File | Will be fired when a file is previewed. | | download | Array<File> | Will be fired when items are downloaded. | | delete | Array<File> | Will be fired when items are deleted. | | upload | Array<File> | Will be fired when items are uploaded. | | navigate | Folder | Will be fired when navigating into folders. | | create | Folder | Will be fired when a new folder is created | ## Keyboard Shortcuts When the item grid has focus, either manually by clicking on it or programmatically via javascript or via the above mentioned `autoFocus` prop, the following keyboard shortcuts will work if their corresponding operations are applicable and allowed. | Key | Action | | --- | --- | | Arrow Up | Previous item row | | Arrow Down | Next item row | | Ctrl/Cmd + Arrow Up | First item row | | Ctrl/Cmd + Arrow Down | Last item row | | / | Search | | Shift + X | Select an item row | | Delete | Delete the selected item | | Enter | Open the selected item | | Shift + R | Rename the selected item | | Shift + S | Share the selected item | | Shift + D | Download the selected item | | g then f | Navigates to the root folder | | g then u | Upload to the current folder | | g then b | Focuses the root folder breadcrumb | | g then r | Recent items | ## Scopes If your application requires the end user to only be able to access a subset of the Content Explorer functionality, you can use [Downscoping](guide://authentication/tokens/downscope) to appropriately downscope the Access Token to a resulting token that has the desired set of permissions, and can thus, be securely passed to the end user client initializing the Content Explorer. Below are a set of UI Element-specific scopes to go alongside Downscoping. These allow developers to enable/disable UI controls on the Content Explorer by configuring the appropriate scopes on the downscoped token. To learn more, see [Dedicated Scopes for Box UI Elements](guide://api-calls/permissions-and-errors/scopes). ### Base Scope | Scope Name | Permissions granted | | --- | --- | | base_explorer | Allows access to content in the folder tree based on user/file/token permissions. | ### Feature Scopes | Scope Name | Permissions granted | | --- | --- | | item_preview | Automatically enables preview of the file, upon user click (requires Preview UI Element to be referenced) | | item_download | Allows files/folders contents to be downloaded | | item_rename | Allows files/folders to be renamed | | item_share | Allows sharing of resource specified under "resource" of the downscope request. | | item_delete | Allows file/folders to be deleted | ### Sample Scenarios | Scenario | Scopes | | --- | --- | | User want to navigate folder structure (basic functionality) | base_explorer | | User want basic functionality + preview | base_explorer + item_preview | | User want basic functionality + preview + download | base_explorer + item_preview + item_download | | User want basic functionality + preview + download + rename file/folder names | base_explorer + item_preview + item_download + item_rename | | User wants all functionality (basic, preview, download, rename, share, upload and delete) | base_explorer + item_preview + item_download + item_rename + item_delete + item_share + item_upload | ## Custom actions You can expand the actions in the **More Options** menu for files and folders in Content Explorer and Content Picker. Your custom options show when user clicks the ellipsis button. To customize the **More Options** menu, pass an array of custom actions to `itemActions`. ``` contentExplorer.show(configData.FOLDER_ID, configData.ACCESS_TOKEN, { container: ".container", itemActions: customActions, }); ``` The array can include multiple actions. The action object should include the `label` and `onAction` callback functions. You can filter the custom actions to appear only on a specific item `type`, by passing the `file` or `folder` value. The `filter` value is used for advanced filtering, for example by a specific file extension: ``` const customActions = [ { label: "Preview in New Window", onAction: (item) => alert('action ' + item), type: 'file', }, { label: "Open in Box.com", onAction: (item) => window.open("https://app.box.com"), }, { label: "Export", onAction: (item) => console.log('action ' + item), filter: (item) => item.extension?.toLowerCase() === 'pdf', } ]; ``` See the implemented examples in CodePen: **Reference:** https://developer.box.com/guides/embed/ui-elements/explorer/ --- ## Untitled *Type: guide | Category: Embed Box * Customize Logo Each of the Box UI Elements allow for specifying a custom logo to place in the top-left corner of the embedded container. By… # Customize Logo Each of the Box UI Elements allow for specifying a custom logo to place in the top-left corner of the embedded container. By default, each of the UI Elements uses a generic placeholder as a logo. This is meant to be replaced by either a Box logo or a custom logo, such as a company's logo. To add a logo to a UI Element, supply a URL for a logo as an option in in the Javascript setup code. The following is an example of how to do this with the Content Preview UI Element. ``` var preview = new Box.Preview(); preview.show(fileId, accessToken, { container: '.preview-container', sharedLink: 'https://app.box.com/v/foo', sharedLinkPassword: 'bar', collection: [FILE_ID, '123', '234', ...], header: 'light', logoUrl: 'http://i.imgur.com/xh8j3E2.png', showAnnotations: true, showDownload: true }); ``` # Box Logo To present the Box logo in a UI Element, specify the string `box` as the `logoURL` option. ## Image size Images files will be fitted to a maximum height of 32 pixels and a maximum width of 80 pixels. Larger images will be shrunk to fit these dimensions. **Reference:** https://developer.box.com/guides/embed/ui-elements/logo/ --- ## Untitled *Type: guide | Category: Embed Box * Installation UI Elements can be used either by downloading the Javascript libraries directly from the Box CDN or by installing our NPM… # Installation UI Elements can be used either by downloading the Javascript libraries directly from the Box CDN or by installing our [NPM package](https://www.npmjs.com/package/box-ui-elements). All UI Elements require their corresponding CSS stylesheet to render properly. ## Prerequisites To use Box UI Elements, you need the following Node and React versions: - Node version: `>=18.18.2 <20.11.0` - React version `>=18.0.0` The available versions of UI elements are listed in the [manual installation](#manual-installation) section. ### Migration to React 18 For existing projects based on React 17 or below, check the [React 18 migration guide](https://react.dev/blog/2022/03/08/react-18-upgrade-guide). Once you upgrade React in your project, update the `box-ui-elements` package with `npm` or `yarn`: ``` npm install box-ui-elements --legacy-peer-deps yarn add box-ui-elements ``` This should result in updated version in the `package.json` file: ``` "box-ui-elements": "^23.0.0" ``` No additional changes related to Box UI elements are required in your code. For more information, check the blog post about React 18 upgrade for UI elements. ## NPM installation Use this when you are building a React based app and would like to import the components directly into your app at build time. **Note** The `--legacy-peer-deps` flag is necessary when installing UI elements with `npm` due to library dependencies. ``` npm install box-ui-elements --legacy-peer-deps yarn add box-ui-elements ``` Learn more on the NPM website ## Content Preview Use the Content Preview SDK if you need a specific version of the preview library. Otherwise, use Content Preview UI Element wrapper. ## Manual installation All the UI elements are also available directly from the Box CDN. | Element | Version | File | | --- | --- | --- | | Content Explorer | 23.0.0 | CSS https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/explorer.css | | | | JS with React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/explorer.js | | | | JS without React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/explorer.no.react.js | | Content Open With | 23.0.0 | CSS https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/openwith.css | | | | JS with React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/openwith.js | | | | JS without React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/openwith.no.react.js | | Content Picker | 23.0.0 | CSS https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/picker.css | | | | JS with React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/picker.js | | | | JS without React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/picker.no.react.js | | Content Sidebar | 23.0.0 | CSS https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/sidebar.css | | | | JS with React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/sidebar.js | | | | JS without React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/sidebar.no.react.js | | Content Uploader | 23.0.0 | CSS https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/uploader.css | | | | JS with React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/uploader.js | | | | JS without React https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/uploader.no.react.js | | Content Preview UI Element | 23.0.0 | CSS https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/preview.css | | | 23.0.0 | JS https://cdn01.boxcdn.net/platform/elements/23.0.0/en-US/preview.js | | Content Preview SDK | 2.106.0 | CSS https://cdn01.boxcdn.net/platform/preview/2.106.0/en-US/preview.css | | | | JS https://cdn01.boxcdn.net/platform/preview/2.106.0/en-US/preview.js | Use these links to either download the elements code to your application's code, or embed them straight into your page from the CDN. ``` <!DOCTYPE html> <html lang="en-US"> <head> <!-- Latest version of the explorer css for your locale --> <link rel="stylesheet" href="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/explorer.css" /> </head> <body> <!-- Latest version of the explorer js for your locale --> <script src="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/explorer.js"></script> ... </body> </html> ``` For Box Preview, the sample would look slightly different. ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Box Content Preview Demo</title> <!-- Latest version of Box Content Preview for en-US locale --> <script src="https://cdn01.boxcdn.net/platform/preview/{VERSION}/en-US/preview.js"></script> <link rel="stylesheet" href="https://cdn01.boxcdn.net/platform/preview/{VERSION}/en-US/preview.css" /> </head> <body> <div class="preview-container" style="height:400px; width:100%;"></div> <script> var preview = new Box.Preview(); preview.show("93392244621", "EqFyi1Yq1tD9mxY8F38sxDfp73pFd7FP", { container: ".preview-container", showDownload: true, }); </script> </body> </html> ``` ### Versions Most of the UI elements have 2 distinct versions. A standard `*.js` file (e.g. `explore.js`) that includes React and ReactDOM in the bundle. - Use this when you are not building a React based app or you don't want to include the components as part of your app's build process. - It includes React and ReactDOM libraries. - The file size of this asset will be larger than the one below. A smaller `*.no.react.js` file (e.g. `explore.no.react.js`) that does not get bundled with React and ReactDOM. - Use this when both React and ReactDOM libraries are already loaded on the application. - These libraries expect a React and ReactDOM `>= 16.6` and `< 18`. Only one of the two `js` files and the additional `css` file need to be added to a project. ### Supported Locales The above asset URLs use `en-US`. If you want to use another locale, then replace `en-US` in the URLs above with any of the following: `en-AU`, `en-CA`, `en-GB`, `da-DK`, `de-DE`, `es-ES`, `fi-FI`, `fr-CA`, `fr-FR`, `it-IT`, `ja-JP,`, `ko-KR`, `nb-NO`, `nl-NL`, `pl-PL`, `pt-BR`, `ru-RU`, `sv-SE`, `tr-TR`, `zh-CN`, `zh-TW` ## Self-hosting Content Preview To serve the Box Content Preview library from your own server, follow these steps. ### 1. Download release Either fork the repository and check out the version you want to serve or download the specific version as a zip. - Check out a specific version with `git checkout v2.106.0`. - Download a specific version as a zip from the [releases](https://github.com/box/box-content-preview/releases) page. ### 2. Install dependencies Install the dependencies and build the library with the following command. ``` yarn install && yarn build:i18n && yarn build:prod ``` ### 3. Serve files Self-serve everything except for the `dev` folder from the `/dist` folder. You must not alter the folder structure and `third-party` needs to be in the same folder as `2.106.0`. For example, if you self-host using a `box-assets` directory, these URLs must be accessible: - `https://cdn.YOUR_SITE.com/box-assets/2.106.0/en-US/preview.js` - `https://cdn.YOUR_SITE.com/box-assets/third-party/text/2.65.0/papaparse.min.js` - `https://cdn.YOUR_SITE.com/box-assets/third-party/model3d/1.12.0/three.min.js` ## Authentication In order to initialize any of the UI Elements, an application will need to provide a valid Access Token. Learn how to authenticate an application It is also recommended to [downscope](g://authentication/tokens/downscope) an Access Token before passing it into an insecure environment (the user's web browser). UI Elements only expect any Access Token to be passed in for authentication, and can therefore be used for any type of authentication available from Box Platform. For testing purposes, a [Developer Token](g://authentication/tokens/developer-tokens) can be used. ## CORS To use UI Elements, an application needs to allow the domain the widget is used on for Cross Origin Resource sharing. See the [CORS guide](g://security/cors) for more details. ## Source Code & Releases Source code for Box UI Elements is [hosted on GitHub](https://github.com/box/box-ui-elements). The repository contains detailed documentation for usage and development. Please file any bugs you encounter under the "Issues" tab with clear steps to reproduce. This repository also holds a list of [releases](https://github.com/box/box-ui-elements/releases). **Reference:** https://developer.box.com/guides/embed/ui-elements/installation/ --- ## Untitled *Type: guide | Category: Embed Box * Content Open With We no longer support the OpenWith UI element for any new customers as of December 21, 2021. The Box Content Open With UI… # Content Open With We no longer support the `OpenWith` UI element for any new customers as of December 21, 2021. The Box Content Open With UI Element allows developers to embed a dropdown to open content stored in box with a partner application, or locally on the desktop. The Element fetches information about enabled integrations using the Box API, and calls out to partner services. Users can then take action in these services, and the edited content will be automatically saved back to Box. The integrations included in the Open With Element are Google Suite, and Box Edit. Additional information on the Google Suite integration can be found on the [Box Community site](https://support.box.com/hc/en-us/articles/360043696994-Introducing-Box-for-G-Suite). Currently, the element only supports [App Users](page://platform/user-types) for authentication. ## Installation [Learn how to install](g://embed/ui-elements/installation) Box UI elements either through NPM or the Box CDN. ## Box Edit Box Edit requires additional setup in order to be integrated into a custom application. Box Edit uses the desktop application [Box Tools](https://support.box.com/hc/en-us/categories/360003188014-Box-Tools) in order to open content locally. - Requests must use a secure connection (from an `https` domain) - The application's domain must be allowed by Box Tools. Instructions can be found [here](g://embed/ui-elements/custom-domains). The ideal workflow is to bundle these steps within an installer that also installs Box Tools. - Safari requires a browser extension to connect to box tools. More details can be found [here](https://support.box.com/hc/en-us/articles/360043697334-Installing-Box-Tools). ## G Suite A valid G Suite account is required in order to use the Box for G Suite integration. To connect a user's G Suite and Box account, the `external_app_user_id` of the app user must be updated to be the email address associated with the user's G Suite account. The `external_app_user_id` of an app user can be updated via the [`PUT /users/:id`](e://put-users-id) endpoint. ## Setup The Open With UI Element is intended to be used after allowing your application and enabling integrations for app users using Box API endpoints. ### Activate application The 'Open With' UI Element is available to any developer building with the Box Platform. To activate it for your instance, add the "Enable integrations" scope to your application in the developer console. Once your application has been activated for API calls it will need to be reauthorized in your enterprise. The steps for performing these actions are available [here](g://authorization/custom-app-approval). ## List available integrations The first step to assigning an app integration to a user is to get the list of integrations that are available. This `GET` request can be made with the following `cURL` request. ``` curl -X GET https://api.box.com/2.0/app_integrations \ -H 'Authorization: Bearer [ACCESS_TOKEN]' ``` ``` { "next_marker": null, "entries": [ { "type": "app_integration", "id": "10897" }, { "type": "app_integration", "id": "1338" }, { "type": "app_integration", "id": "13418" }, { "type": "app_integration", "id": "3282" } ], "limit": 100 } ``` The app integration IDs are used to assign an integration to a given user. ## Get a specific integration To obtain additional information about a specific integration, based on ID, the following GET request may be made. ``` curl -X GET \ https://api.box.com/2.0/app_integrations/[APP_INTEGRATION_ID] \ -H 'Authorization: Bearer [ACCESS_TOKEN]' ``` ``` { "type": "app_integration", "id": "10897", "app": { "type": "app", "id": "336417" }, "name": "Edit with G Suite", "description": "Securely manage your Google Docs, Sheets and Slides in Box", "executable_item_types": [ "file" ], "restricted_extensions": [ "docx", "gdoc", "xlsx", "gsheet", "pptx", "gslides", "gslide" ], "scoped_to": "parent" } ``` ## Add integration to user To add an app integration to a valid app user, three pieces of information are required: - A valid [Service Account](page://platform/user-types/#service-account) Access Token. - The ID of the app user to be assigned the integration - The ID of the app integration to assign to the user While the two previous requests to get app integration information can be done with any valid token including a valid developer token, adding and removing app integrations requires a valid service account's access token. Using a developer token will produce a `404 Not Found` error. The following `POST` request can be made to assign an app integration to an app user: ``` curl -X POST https://api.box.com/2.0/app_integration_assignments \ -H 'Authorization: Bearer [SERVICE_ACCOUNT_TOKEN]' \ -d '{ "assignee": { "type": "user", "id": "[APP_USER_ID]" }, "app_integration": { "type": "app_integration", "id": "[APP_INTEGRATION_ID]" } }' ``` ``` { "type": "app_integration_assignment", "id": "72048301", "assignee": { "type": "user", "id": "6084519920" }, "app_integration": { "type": "app_integration", "id": "3282" } } ``` The ID in the JSON response can be used to manage app integrations after assignment, and should be stored by the application. ## Remove integration from user To remove an app integration from an app user, the following request may be made with a valid service access token and the app integration assignment ID from the previous step. ``` curl -X DELETE https://api.box.com/2.0/app_integration_assignments/[APP_INTEGRATION_ASSIGNMENT_ID] \ -H 'Authorization: Bearer [SERVICE_ACCOUNT_TOKEN]' ``` ``` 204 No Content ``` ## Sample HTML ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Box Content Open With Demo</title> <!-- Latest version of the open with css for your locale --> <link rel="stylesheet" href="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/openwith.css" /> </head> <body> <div class="container" style="height:600px"></div> <!-- Latest version of the open with js for your locale --> <script src="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/openwith.js"></script> <script> var fileId = "123"; var accessToken = "abc"; var contentOpenWith = new Box.ContentOpenWith(); contentOpenWith.show(fileId, accessToken, { container: ".container" }); </script> </body> </html> ``` ## Demo ### Open With Example ### Content Explorer + Open With Example # Access Token These demos may not fully function until you provide a valid access token under the JS tab of the demo. For the Open With element, you must provide a valid [Service Account](page://platform/user-types/#service-account) Access Token. ## Authentication The UI Elements are designed in an authentication agnostic way so whether you are using UI Elements for users who have Box accounts (Managed Users) or non-Box accounts (App Users), UI Elements should work out of the box. The reason for this is that UI Elements only expect a "token" to be passed in for authentication, and Box provides two different ways to generate tokens - OAuth and JWT. Learn about selecting an authentication method ## Scopes To run integrations with downscoped tokens, you must include the `item_execute_integration` scope as well as the scope required by the specific integration you would like to use. - **Google**: `item_readwrite` on the parent folder - **Adobe**: `root_readwrite` - **Box Edit**: `item_readwrite` on the parent folder. - **Box Edit Single File Collaboration**: `item_readwrite` on the file. More information on scopes can be found [here](guide://api-calls/permissions-and-errors/scopes). ## API ``` const { ContentOpenWith } = Box; const contentOpenWith = new ContentOpenWith(); /** * Shows the content open with element. * * @param {string} fileId - The root file id * @param {string} accessToken - Box API access token * @param {Object} [options] - Options * @return {void} */ contentOpenWith.show(fileId, accessToken, options); /** * Hides the content open with element, removes all event listeners, * and clears out the * HTML. * * @return {void} */ openWith.hide(); /** * Adds an event listener to the content open with element. Listeners should be added * before calling show() so no events are missed. * * @param {string} eventName - Name of the event * @param {Function} listener - Callback function * @return {void} */ contentOpenWith.addListener(eventName, listener); /** * Removes an event listener from the content open with element. * * @param {string} eventName - Name of the event * @param {Function} listener - Callback function * @return {void} */ contentOpenWith.removeListener(eventName, listener); /** * Removes all event listeners from the content open with element. * * @return {void} */ contentOpenWith.removeAllListeners(); ``` ### Parameters | Parameter | Type | Description | | --- | --- | --- | | fileId | String | Box File ID. This will be the ID of the file for which you would like to execute integrations. | | accessToken | String | Box API access token to use. This should have read/write access to the folder above. The value passed in for the token is assumed to never expire while the explorer is visible. | | options | Object | Optional options. See below for details. For example: contentExplorer.show(FOLDER_ID, TOKEN, {canDelete: false}) would be used to hide the delete option. | ### Options | Parameter | Type | Description | | --- | --- | --- | | dropdownAlignment | `left | right` | | boxToolsName | String | This string will replace the name of Box Tools in the "Install Box Tools to open this file on your desktop" message. | | boxToolsInstallUrl | String | This URL will be used instead of the default Box installation instructions which are linked in the "Install Box Tools to open this file on your desktop" message. | | onExecute | Function | A callback that executes when an integration invocation is attempted. | | onError | Function | A callback that executes when an error occurs. | | requestInterceptor | Function | Function to intercept requests. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | | responseInterceptor | Function | Function to intercept responses. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | Currently the `onError` and `onExecute` events are subject to a known bug. We recommend using `openWith.addListener('execute', callback)` and `openWith.addListener('error', callback)` as a temporary workaround. ### Events | Event Name | Event Data | Description | | --- | --- | --- | | execute | Integration ID | Will be fired when an integration invocation is executed. | | error | Error | Will be fired when an error occurs. | **Reference:** https://developer.box.com/guides/embed/ui-elements/open-with/ --- ## Untitled *Type: guide | Category: Embed Box * Theming & styling for Box UI Elements With theming & styling for Box UI Elements you can customize the look of the embedded Box component to… # Theming & styling for Box UI Elements With theming & styling for Box UI Elements you can customize the look of the embedded Box component to your enterprise's requirements. As of now, [theming & styling](https://medium.com/@stefaniuk.olga/b4a86518d5ca) is available for Content Explorer and Content Uploader. ## How to start Add the selected Box component to your application. The default Box theme is applied. ## Customization Box uses [design tokens](g://embed/ui-elements/ui-elements-design-tokens) for the customization purposes. Design tokens are named entities that store specific visual attributes, such as colors, spacing, typography, scale, and many more. They are used instead of hard-coded values to simplify sharing design properties across platforms, tools, and components. You can change the following elements in your embedded Box component. ### Colors Customize: - global color palette - select the primary, secondary, and accent colors - state colors - select color for states such as hover, focus, active, disabled - component-specific colors - for example, you can select different colors for your buttons depending on their type - gradients - choose and adjust a gradient as your background or other components - opacity - adjust the opacity of the overlay effects for Box Modals and side panels ### Typography Customize: - text decoration - underline, strikethrough, letter spacing - line heights and paragraph spacing ### Border, radius Choose: - border styling - width, styles, and colors - border radius ### Spacing Choose: - global spacing - component-specific spacing - component-specific alignment and distribution, for example justify-content ### Shadows and elevation Define: - shadow presets - custom shadows ### Interactive states Customize: - hover, active, focus, disabled, and error states - visual effect such as changed background color - transitions and animations ### Component-level overrides Customize text input, drop down, and checkboxes with individual color ### Icons Style interactive icons such as buttons or drop downs. To replace non-interactive icons such as file or folder icons with your custom ones, use inline SVGs in CSS. To change non-interactive icons color, height, and width, use CSS. See the implemented examples of custom icons in CodePen: ### Miscellaneous Style: - help text and labels - tool tips ## Demo **Reference:** https://developer.box.com/guides/embed/ui-elements/theming-styling/ --- ## Untitled *Type: guide | Category: Embed Box * Content Sidebar The Box Content Sidebar UI Element allows developers to add support for viewing file related metadata (incl. Box Skills) and… # Content Sidebar The Box Content Sidebar UI Element allows developers to add support for viewing file related metadata (incl. Box Skills) and Activity Feed (incl. versions, comments and tasks) in their desktop or mobile web application. ## Installation [Learn how to install](g://embed/ui-elements/installation) Box UI elements either through NPM or the Box CDN. ## Authentication The UI Elements are designed in an authentication agnostic way so whether you are using UI Elements for users who have Box accounts (Managed Users) or non-Box accounts (App Users), UI Elements should work out of the box. The reason for this is that UI Elements only expect a "token" to be passed in for authentication, and Box provides two different ways to generate tokens - OAuth and JWT. Learn about selecting an authentication method ## Sample HTML ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Box Content Sidebar</title> <!-- Latest version of the sidebar css for your locale --> <link rel="stylesheet" href="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/sidebar.css" /> </head> <body> <div class="container" style="height:600px"></div> <!-- Latest version of the sidebar js for your locale --> <script src="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/sidebar.js"></script> <script> var fileId = "123"; var accessToken = "abc"; // At least one of the sub-sidebars (details, activity feed, skills, metadata) need to be turned on for something to render. Details is iteself further divided into notices, properties, access stats and versions, one of which need to be enabled for the details sidebar to render. var sidebar = new Box.ContentSidebar(); sidebar.show(fileId, accessToken, { container: ".container", detailsSidebarProps: { hasNotices: true, hasProperties: true, hasAccessStats: true, hasVersions: true }, hasActivityFeed: true, hasSkills: true, hasMetadata: true }); </script> </body> </html> ``` ## Demo ### Stand-alone Sidebar ### Sidebar with Content Preview ### Sidebar with Content Explorer ## API ``` const { ContentSidebar } = Box; const sidebar = new ContentSidebar(); /** * Shows the file selection. * * @public * @param {String} fileId - The file id. * @param {String} token - The API access token. * @param {Object|void} [options] - Optional options. * @return {void} */ sidebar.show(fileId, token, options); /** * Hides the sidebar, removes all event listeners, and clears out the HTML. * * @public * @return {void} */ sidebar.hide(); /** * Clears out the internal in-memory cache for the sidebar. This forces * items to be reloaded from the API. * * @public * @return {void} */ sidebar.clearCache(); /** * Adds an event listener to the sidebar. Listeners should be added before * calling show() so no events are missed. * * @public * @param {String} eventName - Name of the event. * @param {Function} listener - Callback function. * @return {void} */ sidebar.addListener(eventName, listener); /** * Removes an event listener from the sidebar. * * @public * @param {String} eventName - Name of the event. * @param {Function} listener - Callback function. * @return {void} */ sidebar.removeListener(eventName, listener); /** * Removes all event listeners from the sidebar. * * @public * @return {void} */ sidebar.removeAllListeners(); ``` ### Parameters | Parameter | Type | Description | | --- | --- | --- | | fileId | String | Box File ID. This will be the ID of the file for which you want the sidebar. | | token | String | Box API access token to use. It can have read/write access to the file above. The value passed in for the token is assumed to never expire while the sidebar is visible. | | options | Object | Additional options. For example, sidebar.show(FILE_ID, TOKEN, {hasProperties: true}) would be used to show file properties in the sidebar. | ### Options | Parameter | Type | Default | Description | | --- | --- | --- | --- | | container | String | document.body | CSS selector of the container in which the content sidebar should be placed. Calling hide() will clear out this container. | | hasActivityFeed | Boolean | false | Set to true to show the activity feed that includes versions, comments and tasks. | | hasMetadata | Boolean | false | Set to true to show box metadata for the file. | | hasSkills | Boolean | false | Set to true to show the file skills data. | | detailsSidebarProps | Object | {} | See section below. | | requestInterceptor | Function | | Function to intercept requests. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | | responseInterceptor | Function | | Function to intercept responses. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | ### detailsSidebarProps | Parameter | Type | Default | Description | | --- | --- | --- | --- | | hasProperties | Boolean | false | Set to true to show file properties in the details sidebar. | | hasAccessStats | Boolean | false | Set to true to show file access stats in the details sidebar. | | hasVersions | Boolean | false | Set to true to show file versions in the details sidebar. | | hasNotices | Boolean | false | Set to true to show file related notices in the details sidebar. | ## Scopes If your application requires the end user to only be able to access a subset of the Content Sidebar's functionality, you can use [Downscoping](guide://authentication/tokens/downscope) to appropriately downscope the Access Token to a resulting token that has the desired set of permissions, and can thus, be securely passed to the end user client initializing the Content Sidebar. Below are a set of UI Element-specific scopes to go alongside Downscoping. These allow developers to enable/disable UI controls on the Content Sidebar by configuring the appropriate scopes on the downscoped token. To learn more, see [Dedicated Scopes for Box UI Elements](guide://api-calls/permissions-and-errors/scopes). ### Base Scope | Scope Name | Permissions granted | | --- | --- | | base_sidebar | Allows the user to get basic file info needed for the sidebar. | ### Feature Scopes | Scope Name | Permissions granted | | --- | --- | | item_comment | Allows adding and editing comments. | | item_rename | Allows editing of file description. | | item_upload | Allows editing of file metadata. | | item_task | Allows creating and resolving of tasks. | **Reference:** https://developer.box.com/guides/embed/ui-elements/sidebar/ --- ## Untitled *Type: guide | Category: Embed Box * Content Picker The Box Content Picker UI Element allows developers to add support for selecting files and folders from Box in their desktop… # Content Picker The Box Content Picker UI Element allows developers to add support for selecting files and folders from Box in their desktop or mobile web application. The library fetches information about a specified folder through the Box API and renders the content in a folder view. Users can select files or folders and this content information is then passed to another part of the application. ## Installation [Learn how to install](g://embed/ui-elements/installation) Box UI elements either through NPM or the Box CDN. ## Authentication The UI Elements are designed in an authentication agnostic way so whether you are using UI Elements for users who have Box accounts (Managed Users) or non-Box accounts (App Users), UI Elements should work out of the box. The reason for this is that UI Elements only expect a "token" to be passed in for authentication, and Box provides two different ways to generate tokens - OAuth and JWT. Learn about selecting an authentication method ## Sample HTML ``` <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Box File Selection</title> <!-- Latest version of the picker css for your locale --> <link rel="stylesheet" href="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/picker.css" /> </head> <body> <div class="container" style="height:600px"></div> <!-- Latest version of the picker js for your locale --> <script src="https://cdn01.boxcdn.net/platform/elements/{VERSION}/en-US/picker.js"></script> <script> var folderId = "123"; var accessToken = "abc"; var filePicker = new Box.FilePicker(); filePicker.show(folderId, accessToken, { container: ".container" }); </script> </body> </html> ``` ## Demo ### File Selection Demo ### Folder Selection Demo ### File Selection + Preview Demo ### File Selection as a popup # Access Token These demos may not fully function until you provide a valid access token. For testing purposes, you can use your temporary developer token. This will need to be updated under the JS tab in the demo. ## API ``` const { FilePicker } = Box; const filePicker = new FilePicker(); /** * Shows the file selection. * * @public * @param {String} folderId - The root folder id. * @param {String} accessToken - The API access token. * @param {Object|void} [options] - Optional options. * @return {void} */ filePicker.show(folderId, accessToken, options); /** * Hides the file picker, removes all event listeners, and clears out the HTML. * * @public * @return {void} */ filePicker.hide(); /** * Clears out the internal in-memory cache for the file picker. This forces * items to be reloaded from the API. * * @public * @return {void} */ filePicker.clearCache(); /** * Adds an event listener to the file picker. Listeners should be added before * calling show() so no events are missed. * * @public * @param {String} eventName - Name of the event. * @param {Function} listener - Callback function. * @return {void} */ filePicker.addListener(eventName, listener); /** * Removes an event listener from the file picker. * * @public * @param {String} eventName - Name of the event. * @param {Function} listener - Callback function. * @return {void} */ filePicker.removeListener(eventName, listener); /** * Removes all event listeners from the file picker. * * @public * @return {void} */ filePicker.removeAllListeners(); ``` ### Parameters | Parameter | Type | Description | | --- | --- | --- | | folderId | String | Box Folder ID. This will be the ID of the folder from which you want the content to be picked. If you want to use the Box All Files folder, then use 0 as the folderId. | | accessToken | String | Box API access token to use. This should have read/write access to the folder above. The value passed in for the token is assumed to never expire while the explorer is visible. | | options | Object | Optional options. See below for details. For example: contentExplorer.show(FOLDER_ID, TOKEN, {canDelete: false}) would be used to hide the delete option. | ### Options | Parameter | Type | Default | Description | | --- | --- | --- | --- | | container | String | document.body | CSS selector of the container in which the content picker should be placed. Calling hide() will clear out this container. | | sortBy | String | name | The initial sort by option for the content list. Value should be either name or date. | | sortDirection | String | ASC | The initial sort direction option for the content list. Value should be either ASC or DESC. | | logoUrl | String | | URL of custom logo to show in header. If this value is the string box then the box logo will show. | | extensions | Array<string> | [] | Array of file extensions to be allowed for selection. for example ['doc', 'ppt']. Applicable only to the File Picker and not the Folder Picker. If any extensions are provided, only those will have the ability to be selected. An empty array signifies all the file extensions are allowed for selection. | | maxSelectable | Number | Infinity | Number of files or folders that can be selected. Specify 1 if you want only 1 file or folder selected. | | canUpload | Boolean | true | Visually hides the upload option if this is set to false. Hiding the option alone will not prevent uploading unless the current folder permissions also set can_upload to false. This option has no effect when the folder permission can_upload is set to false. | | canSetShareAccess | Boolean | true | Visually hides the sharing drop down select if set to false. Hiding the select drop down alone will not prevent changing the share access unless the folder item permissions also set can_set_share_access to false. This option has no effect when the folder item permission can_set_share_access is set to false. | | canCreateNewFolder | Boolean | true | Visually hides the create new folder option. Hiding the option alone will not prevent creating a new folder unless the folder item permissions also set can_upload to false. This option has no effect when the folder item permission can_upload is set to false. | | sharedLink | String | | Shared link URL, required if folder is shared and the access token doesn't belong to an owner or collaborator of the file. | | sharedLinkPassword | String | | Shared link password, required if shared link has a password. | | modal | Object | | When the modal attribute is specified, then the content pickers will not be created in-place. Instead a button will be created in the container and clicking this button will launch the content picker in a modal popup. | | size | String | undefined | Indicates to the content picker to fit within a small or large width container. Value can be absent or one of small or large. If absent the UI Element will adapt to its container and automatically switch between small width or large width mode. | | isTouch | Boolean | Defaults to the browser and device's default touch support | Indicates to the content explorer that it's is being rendered on a touch enabled device. | | autoFocus | Boolean | false | When set to true, the item grid will get focus on initial load. | | defaultView | String | files | Value should either be files or recents. When set to recents, by default you will see recent items instead of the regular file/folder structure. | | chooseButtonLabel | String | | String to re-label the Choose button | | cancelButtonLabel | String | | String to re-label the Cancel button | | requestInterceptor | Function | | Function to intercept requests. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | | responseInterceptor | Function | | Function to intercept responses. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | ### Modal Options | Parameter | Type | Default | Description | | --- | --- | --- | --- | | buttonLabel | String | | Label for the button | | buttonClassName | String | Box Blue Button | CSS class to decorate the button | | modalClassName | String | | CSS class to decorate the modal popup content | | overlayClassName | String | | CSS class to decorate the modal popup overlay | ### Events | Event Name | Event Data | Description | | --- | --- | --- | | choose | Array<File | Web Link | Folder> | Will be fired when the Choose button is pressed. Event data will be an array of Folder Object or File Object or Web Link object depending upon whether it was a file selection or folder selection. | | cancel | | Will be fired when the Cancel button is pressed | ## Keyboard Shortcuts When the item grid has focus, either manually by clicking on it or programmatically via javascript or via the above mentioned `autoFocus` prop, the following keyboard shortcuts will work if their corresponding operations are applicable and allowed. | Key | Action | | --- | --- | | Arrow Up | Previous item row | | Arrow Down | Next item row | | Ctrl/Cmd + Arrow Up | First item row | | Ctrl/Cmd + Arrow Down | Last item row | | / | Search | | Shift + X | Select an item row | | Enter | Open the selected item | | g then f | Navigates to the root folder | | g then u | Upload to the current folder | | g then b | Focuses the root folder breadcrumb | | g then s | Shows the selected items | | g then x | Cancel | | g then c | Choose | | g then r | Recent items | ## Scopes If your application requires the end user to only be able to access a subset of the Content Picker functionality, you can use [Downscoping](guide://authentication/tokens/downscope) to appropriately downscope the Access Token to a resulting token that has the desired set of permissions, and can thus, be securely passed to the end user client initializing the Content Picker. Below are a set of UI Element-specific scopes to go alongside Downscoping. These allow developers to enable/disable UI controls on the Content Picker by configuring the appropriate scopes on the downscoped token. To learn more, see [Dedicated Scopes for Box UI Elements](guide://api-calls/permissions-and-errors/scopes). | Scope Name | Permissions granted | | --- | --- | | base_picker | Allows access to content in the folder tree based on user/file/token permissions | ### Feature Scopes | Scope Name | Permissions granted | | --- | --- | | item_share | Allows sharing of resource specified under "resource" of the Token Exchange request. | | item_upload | Allows upload in the content picker | ### Sample Scenarios | Scenario | Scopes | | --- | --- | | User wants to only navigate a folder structure and pick a file / folder | base_picker | | User wants to navigate a folder structure, pick a file / folder and also set access level | base_picker + item_share | | User wants to navigate a folder structure, pick a file / folder and also upload a file / folder | base_picker + item_upload | | User should be able to navigate a folder structure and pick a file / folder, upload a file / folder, and also set access level for a file/folder | base_picker + item_share + item_upload | ## Custom actions You can expand the actions in the **More Options** menu for files and folders in Content Explorer and Content Picker. Your custom options show when user clicks the ellipsis button. To customize the **More Options** menu, pass an array of custom actions to `itemActions`. ``` contentExplorer.show(configData.FOLDER_ID, configData.ACCESS_TOKEN, { container: ".container", itemActions: customActions, }); ``` The array can include multiple actions. The action object should include the `label`, and the `onAction` callback function. You can filter the custom actions to appear only on a specific item `type`, by passing the `file` or `folder` value. The `filter` value is used for advanced filtering, for example by a specific file extension: ``` const customActions = [ { label: "Preview in New Window", onAction: (item) => alert('action ' + item), type: 'file', }, { label: "Open in Box.com", onAction: (item) => window.open("https://app.box.com"), }, { label: "Export", onAction: (item) => console.log('action ' + item), filter: (item) => item.extension?.toLowerCase() === 'pdf', }, ]; ``` See the implemented examples in CodePen: **Reference:** https://developer.box.com/guides/embed/ui-elements/picker/ --- ## Untitled *Type: guide | Category: Embed Box * Dedicated Scopes When working with Box UI Elements many developers have shown interest in being able to implement their own permission model… # Dedicated Scopes When working with Box UI Elements many developers have shown interest in being able to implement their own permission model, different from Access Levels defined by Box. [Downscoping](g://authentication/tokens/downscope), also known as Token Exchange, is our mechanism by which developers can restrict the permissions on the Access Token to a more granular level, allowing them to build out their own permissions model on Box Platform. ## Scopes & UI Elements To facilitate this process we've created a new set of API scopes that allow developers to control which UI controls are available to end users in applications leveraging UI Element. The Box UI Element has been designed to respect the permission enforced via these scopes, so UI controls are turned on or off automatically depending on whether or not the token allows the corresponding functionality or not. Another advantage of these new scopes is that since the tokens are scoped to the precise set of operations that the application wants the end user to have access to, a savvy end user won't have any more access directly through the API using the token. This allows you to make your application more secure. ## Scope principles The new scopes have been designed keeping the following fundamentals in mind: - **All scopes should be modular and strictly additive:** So a developer can combine multiple scopes in a token exchange request to generate a token with the desired set of functionality. Also to avoid confusion, two scopes should never have the same permission. - **Scopes should directly map to a specific action in the UI Element:** So adding this scope to the token enables the specific action. Since some actions can only be performed by specific UI Elements, some scopes may only be meaningfully applicable to those UI Elements. - **Scope should contain the minimum set of permissions required to perform the corresponding action:** So even if some end-user of your application uses the token directly against the API, they can't gain access beyond what you intended them to provide through the UI Element. - **Every UI Element should have a "base scope" that encapsulates all required permissions for the UI Element to functionally work:** Any fewer permissions on the token and the basic set of operations on the UI Element won't work. This scope should always be included in the Token Exchange request. With that said, for every UI Element, we are adding two types of scopes: ### Base Scope Every UI Element has a "base scope", which provides the least set of permissions that are necessary for the UI Element to functionally work. For this reason, this "base scope" must always be present in the token exchange request. Since the base set of permissions for every UI Element to functionally work may not be the same (Content Uploader UI Element doesn't require preview permissions, for example), UI Elements may have their own respective base scopes. ### Feature Scopes In addition to the base scope, we also introduced feature-level scopes. Upon pairing with base scopes, feature scopes enable additional capabilities within your UI Element, and provide the user with permissions to perform the actions prescribed by the feature scope(s) added to their down-scoped token. As with base scopes, feature scopes too are mostly different for every UI Element. Since feature scopes are strictly additive, you can assume (unless noted otherwise in the documentation) that providing a user with access to a scope only gives them permission to perform the corresponding action and nothing else. Now that you understand what Base Scopes and Feature Scopes are, refer to the documentation for each of the UI Elements to learn more about their dedicated scopes. **Reference:** https://developer.box.com/guides/embed/ui-elements/scopes/ --- ## Untitled *Type: guide | Category: Embed Box * Content Preview The Box Content Preview UI Element allows developers to embed high quality and interactive previews of Box files in their… # Content Preview The Box Content Preview UI Element allows developers to embed high quality and interactive previews of Box files in their desktop or mobile web application. ## Content Preview Element vs Content Preview Library The Content Preview UI Element works differently from the other UI Elements, as the React component is a wrapper for the [Box Content Preview library](https://github.com/box/box-content-preview). It also requires passing a language (defaults to `en-US`) since the preview library bundles are localized. ``` var ContentPreview = require("./ContentPreview").default; <IntlProvider locale="en"> <ContentPreview contentSidebarProps={{ detailsSidebarProps: { hasAccessStats: true, hasClassification: true, hasNotices: true, hasProperties: true, hasRetentionPolicy: true, hasVersions: true, }, features: FEATURES, hasActivityFeed: true, hasMetadata: true, hasSkills: true, hasVersions: true, }} hasHeader={true} features={FEATURES} fileId={FILE_ID} token={TOKEN} {...PROPS} /> </IntlProvider>; ``` The Content Preview Library fetches information about the file and its converted representations through the Box API, chooses the appropriate viewer for the file type, dynamically loads the necessary static assets and file representations, and finally renders the file. This UI Element also allows loading previews of multiple files in the same container and exposes arrows to navigate between those files. It powers Preview in the main Box web application as well as the [expiring embed link object](r://file--full/#param-expiring_embed_link). ## Installation [Learn how to install](g://embed/ui-elements/installation) Box UI elements either through NPM or the Box CDN. ## Authentication UI Elements are designed in an authentication-agnostic way so whether they will work for Managed Box Users and non-Box users (App Users). The reason for this is that UI Elements only expect a [token](g://authentication/tokens/developer-tokens) for authentication, and Box provides two different ways to generate tokens - OAuth and JWT. Learn about selecting an authentication method ## Supported File Types Box Content Preview supports 120+ file types, including most document and image formats, HD video, 3D models, 360-degree images, and 360-degree videos. You can find the full list of supported file types [here](https://support.box.com/hc/en-us/articles/360043695794-Viewing-Different-File-Types-Supported-in-Box-Content-Preview). Note that where supported file types contain references to other objects, for example `DWG` files, those references are not supported in the Box preview. A notice will be displayed to all end users viewing a DWG file that contains unsupported references letting them know to take alternate steps to complete their workflow. ## Demo Use the navigation arrows to preview different file types. ## API ``` const { Preview } = Box; const preview = new Preview(); /** * Shows a preview. * * @public * @param {string} fileId - File ID to preview * @param {string} accessToken - Box API access token * @param {Object} [options] - Options * @return {void} */ preview.show(fileId, accessToken, options); /** * Hides the preview. * * @return {void} */ preview.hide(); /** * Prints the current file, if printable. * * @return {void} */ preview.print(); /** * Downloads the current file. * * @return {void} */ preview.download(); /** * Resizes the current preview, if applicable. This function only needs to * be called when preview's viewport has changed while the window has not. * If the window is resizing, then preview will automatically resize itself. * * @return {void} */ preview.resize(); /** * Adds an event listener to the preview. Listeners should be added * before calling show() so no events are missed. * * @param {string} eventName - Name of the event * @param {Function} listener - Callback function * @return {void} */ preview.addListener(); /** * Removes an event listener from the preview. * * @param {string} eventName - Name of the event * @param {Function} listener - Callback function * @return {void} */ preview.removeListener(eventName, listener); /** * Removes all event listeners from the preview. * * @return {void} */ preview.removeAllListeners(); ``` ### Parameters | Parameter | Type | Description | | --- | --- | --- | | fileId | String | Box File ID. | | accessToken | String | Box API access token to use. This should have read/write access to the folder above. The value passed in for the token is assumed to never expire while the explorer is visible. | | options | Object | Optional options. See below for details. For example: contentExplorer.show(FOLDER_ID, TOKEN, {canDelete: false}) would be used to hide the delete option. | ### Options | Parameter | Type | Default | Description | | --- | --- | --- | --- | | container | String | document.body | CSS selector of the container in which Preview should be placed | | sharedLink | String | | Shared link URL, required if file is shared and the access token doesn't belong to an owner or collaborator of the file | | sharedLinkPassword | String | | Shared link password, required if shared link has a password | | collection | Array | | List of file IDs to preview over. When used, this will show previews of multiple files within the same container and expose arrows to navigate between those files. Note that FILE_ID needs to be included in this list and that the SDK doesn't support collections with files that require a shared link or password. | | header | String | light | Values that control header visibility and background color. Use none for no header, light for a light header and background, and dark for a dark header and background | | logoUrl | String | | URL of custom logo to show in header. If this value is the string box then the box logo will show | | showAnnotations | Boolean | false | Whether annotation button in header and annotations on content are shown | | showDownload | Boolean | false | Whether download button is shown in header. Will also control print button visibility in viewers that support print. Note that this option will not override download permissions on the access token. | ## Token Generator Function The Preview library optionally takes a token generator function instead of a string token. Using a token generator function allows you to dynamically determine what tokens Preview should use. For example, you can pass in different access tokens for each file or make sure your token is refreshed and valid before showing a preview. The token generator function should return a promise that resolves in either a single string token that applies to all of the files being previewed or a map of typed file IDs to access token for those files. ``` // Example token generator function that resolves to a single access token var singleTokenGenerator = function () { return someApi.getToken().then(function (data) { return data.token; }); }; // Example token generator function that resolves to a map of tokens var mapTokenGenerator = function () { return Promise.resolve({ file_1234: "some_token_abcd", file_2345: "some_token_bcde", }); }; ``` ## Events The preview object exposes `addListener` and `removeListener` for binding to events. Event listeners should be bound before `show()` is called, otherwise events can be missed. ``` const listener = (value) => { // Do something with value }; // Attach listener before calling show otherwise events can be missed var preview = new Box.Preview(); preview.addListener(EVENTNAME, listener); // Show a preview preview.show(...); // Remove listener when needed preview.removeListener(EVENTNAME, listener); ``` `EVENTNAME` can be one of the following: `viewer` event will be triggered when we have the viewer instance first available. This will be the same object that is also a property included in the `load` event. Preview triggers this event before `load` so that clients can attach their listeners before the `load` event is triggered. `load` event will be triggered on every preview load when `show()` is called or if inter-preview navigation occurs. The event data will contain: ``` error: 'message', // Error message if any error occurred while loading viewer: {...}, // Instance of the current viewer object if no error occurred metrics: {...}, // Performance metrics file: {...} // Box file object with properties defined in file.js ``` `navigate` event will be triggered when navigation happens. The event includes the file ID of the file being navigated to, and this event will trigger before `load`. `notification` event will be triggered when either the preview wrapper or one of the viewers wants to notify something like a warning or non-fatal error. The event data will contain: ``` message: 'message', // Message to show type: 'warning' // 'warning', 'notice', or 'error' ``` `viewerevent` Each viewer will trigger its own sets of events. For example, the Image viewer will trigger `rotate` or `resize`, etc. while other viewers may trigger another set of events. The preview wrapper will also re-emit events at the preview level, with event data containing: ``` event: EVENTNAME, // Event name data: DATA, // Event data object viewerName: VIEWERNAME, // Name of the viewer. See VIEWERNAME above fileId: fileId // The file ID ``` ### Example event usage ``` var preview = new Box.Preview(); preview.addListener("viewer", (viewer) => { viewer.addListener("rotate", () => { // Do something when a viewer rotates a preview }); }); preview.addListener("load", (data) => { const viewer = data.viewer; viewer.addListener("rotate", () => { // Do something when a viewer rotates a preview }); }); preview.addListener("viewerevent", (data) => { if (data.viewerName === "Image") { if (data.event === "rotate") { // Do something when an image preview is rotated } } else if (data.viewerName === "Image360") { if (data.event === "rotate") { // Do something different when a 360-degree image is rotated } } else { } }); preview.addListener("rotate", (data) => { if (data.viewerName === "Image") { // Do something when an image preview is rotated } else if (data.viewerName === "Image360") { // Do something different when a 360-degree image is rotated } else { } }); ``` ## Annotations You can enable V4 [annotations](g://embed/ui-elements/annotations.md) in content preview. New annotations will sync in real time. To add V4 annotations to preview: 1. Run `npm i box-annotations@latest`to install [box annotations](https://github.com/box/box-annotations). Box annotations version should be at least major version 4 and up. 1. Run `npm i box-ui-elements@16.0.0` to install [BUIE](https://github.com/box/box-ui-elements/releases/tag/v16.0.0) version with annotation related change. Box UI elements should be the lowest working version that contains fully working V4 annotations. Import content preview and box annotations into your application: ``` import boxAnnotations from "https://cdn.skypack.dev/box-annotations@latest"; var file_id = "YOUR FILE ID"; var accessToken = "YOUR ACCESS TOKEN"; /* Enable annotations in sidebar */ var contentSidebarProps = { hasActivityFeed: true, features: { activityFeed: { annotations: { enabled: true, }, }, }, }; var options = { container: ".previewer", contentSidebarProps: contentSidebarProps, /* Enable annotations in preview */ enableAnnotationsDiscoverability: true, enableAnnotationsImageDiscoverability: true, showAnnotations: true, showAnnotationsControls: true, showAnnotationsDrawingCreate: true, }; /* BoxAnnotations */ var annotations = new BoxAnnotations(); /* Box Preview */ var contentPreviewer = new Box.ContentPreview(); /* Set annotation into previewer */ options["boxAnnotations"] = annotations; /* Show previewer */ contentPreviewer.show(file_id, accessToken, options); ``` The property `features: { activityFeed: { annotations: { enabled: true } } } } ` is subject to change in the future. ``` <link href="https://cdn01.boxcdn.net/platform/elements/16.0.0/en-US/preview.css" rel="stylesheet" type="text/css"></link> <script src="https://cdn01.boxcdn.net/platform/elements/16.0.0/en-US/preview.js"></script> <style> .previewer { border: 1px solid #eee; height: 500px; width: 100%; } </style> <div class="previewer"></div> <script type="module" src="./script.js"></script> ``` ## Box AI for UI Elements Box AI for UI Elements enhances the Content Preview UI Element with additional features, allowing the developers to add the Box Q&A AI functionality to their platform app. Enriched with Box AI features, the Preview UI element brings the following functionality: - Q&A and document summaries. - A **clear conversation** button that resets the conversation with Box AI. - Citations that appear below the answer if included in the answer. - Formatting support that allows requesting Markdown-formatted response, including bullet points or tables. - Question history that allows referencing previous context to achieve the best response possible. The question history is kept only during the current session. - Suggested questions that appear at the top of the chat by default to assist with the conversation. ### Enable Box AI for UI Elements To enable the Box AI modal in content preview header, follow these steps: Make sure your Node and React versions are `18.x` or higher. Download the [npm package that contains Box AI for UI Elements](https://www.npmjs.com/package/box-ui-elements/v/22.0.0) or directly from [Box CDN](g://embed/ui-elements/installation). Install the peer dependencies: - [`box-ai-content-answers`](https://www.npmjs.com/package/@box/box-ai-content-answers) - [`blueprint-web`](https://www.npmjs.com/package/@box/blueprint-web) - [`blueprint-web-assets`](https://www.npmjs.com/package/@box/blueprint-web-assets) To do so, run the following command: ``` npx install-peerdeps box-ui-elements@^22.0.0 ``` ### Using JavaScript To enable Box AI features, pass the following: - `hasHeader` prop set to `true`, - `contentAnswersProps` prop. The fields `show`, `isCitationsEnabled`, `isMarkdownEnabled`, `isResetChatEnabled` and `suggestedQuestions` are included by default. ``` const preview = new Box.Preview(); const suggestedQuestions = [ { label: 'What are the key takeaways?', prompt: 'What are the key takeaways?', id: '1234', }, { label: 'Summarize this document', prompt: 'Summarize this document', id: '5678', }, ]; preview.show(<FILE_ID>, <TOKEN>, { container: '.preview-container', contentAnswersProps={ show: true, isCitationsEnabled: true, isMarkdownEnabled: true, isResetChatEnabled: true, suggestedQuestions } hasHeader: true, }); ``` ### Using React component You can also add Box AI element to a header in a React component. To do so, add: - `hasHeader` prop set to `true`, - `contentAnswersProps` prop. The fields `show`, `isCitationsEnabled`, `isMarkdownEnabled`, `isResetChatEnabled` and `suggestedQuestions` are included by default. To localize the `suggestedQuestions` properly, make sure that the prompts are translated. The optional `label` property is for screen readers, while the `prompt` property is the text displayed to the user in the AI modal. ``` import ContentPreview from 'box-ui-elements/es/elements/content-preview'; import { IntlProvider } from "react-intl"; const suggestedQuestions = [ { label: 'Key takeaways', prompt: 'What are the key takeaways from this document?', id: '1234', }, { label: 'Summarize', prompt: 'Summarize this document', id: '5678', }, ]; export default () => { // Storing variables in the front end is not secure. // You will want to grab this value from a database for production const TOKEN = process.env.REACT_APP_BOX_DEVELOPER_TOKEN const FILE_ID = process.env.REACT_APP_BOX_PREVIEW_FILE_ID return ( <IntlProvider locale="en"> <ContentPreview contentAnswersProps={{ show: true, isCitationsEnabled: true, isMarkdownEnabled: true, isResetChatEnabled: true, suggestedQuestions }} fileId={FILE_ID} token={TOKEN} hasHeader=true /> </IntlProvider> ); }; ``` You can further customize your apps using the following event listeners for Content Preview available with this release: `onAsk`, `onClearConversations`, and `onRequestClose`. ## Scopes If your application requires the end user to only be able to access a subset of the Content Preview functionality, you can use [Downscoping](guide://authentication/tokens/downscope) to appropriately downscope the Access Token to a resulting token that has the desired set of permissions, and can thus, be securely passed to the end user client initializing the Content Preview. Below is a set of UI Element-specific scopes to go alongside Downscoping. These allow developers to enable/disable UI controls on the Content Preview by configuring the appropriate scopes on the downscoped token. To learn more, see [Dedicated Scopes for Box UI Elements](g://api-calls/permissions-and-errors/scopes). ### Base Scope | Scope Name | Permissions granted | | --- | --- | | base_preview | Allows the user to preview the file, nothing else | ### Feature Scopes | Scope Name | Permissions granted | | --- | --- | | item_download | Allows downloading/printing the content from the generated preview | | annotation_edit | Allows users to edit annotations (delete). Note: For highlight annotations to work, the text layer on the document needs to be enabled for the user. Text layer is disabled for all users that don't have download permissions on the file. To enable highlight annotations for a user, please ensure they have download permissions on the file. | | annotation_view_all | Allows users to view all users' annotations. | | annotation_view_self | Allows users to view their own annotations only. | # Enable highlight annotations with scopes The highlight scope is not included with `annotation_edit` and `annotation_view_all` scopes. The downscoped access token will need to include the `item_download` scope to enable highlighting. ### Sample Scenarios | Scenario | Scopes | | --- | --- | | User should only be able to preview (not download/print, annotate) | base_preview | | User should be able to preview, download and print | base_preview + item_download | | User should be able to preview and view all annotations (not download, print or create annotations) | base_preview + annotation_view_all | | User should be able to preview, and create annotations but only view their own. | base_preview + annotation_view_self + annotation_edit | | User should be able to preview, edit annotations and view all annotations | base_preview + annotation_view_all + annotation_edit | | User should be able to preview and only view their own annotations but not add/delete (ex: after review period has expired, all documents need to be stored in read only mode) | base_preview + annotation_view_self | **Reference:** https://developer.box.com/guides/embed/ui-elements/preview/ --- ## Untitled *Type: guide | Category: Embed Box * Content Uploader The Box Content Uploader UI Element allows developers to embed an upload widget in their desktop or mobile web application… # Content Uploader The Box Content Uploader UI Element allows developers to embed an upload widget in their desktop or mobile web application. Users can select files or use drag and drop to upload. Large files will be uploaded with the Chunked Upload API. ## Installation [Learn how to install](g://embed/ui-elements/installation) Box UI elements either through NPM or the Box CDN. ## Authentication The UI Elements are designed in an authentication agnostic way so whether you are using UI Elements for users who have Box accounts (Managed Users) or non-Box accounts (App Users), UI Elements should work out of the box. The reason for this is that UI Elements only expect a "token" to be passed in for authentication, and Box provides two different ways to generate tokens - OAuth and JWT. Learn about selecting an authentication method ## Demo ### Uploader ### Uploader as popup # Access Token These demos may not fully function until you provide a valid access token. For testing purposes, you can use your temporary developer token. This will need to be updated under the JS tab in the demo. ## API ``` const { ContentUploader } = Box; const uploader = new ContentUploader(); /** * Shows the content uploader. * * @public * @param {String} folderId - Folder ID to upload to. * @param {String} accessToken - Box API access token. * @param {Object|void} [options] - Optional options. * @return {void} */ uploader.show(folderId, accessToken, options); /** * Hides and clears HTML for the uploader. * * @public * @return {void} */ uploader.hide(); /** * Adds an event listener to the content uploader. * Listeners should be added before calling show() * so no events are missed. * * @public * @param {String} eventName Name of the event. * @param {Function} listener Callback function. * @return {void} */ uploader.addListener(eventName, listener); /** * Removes an event listener from the content uploader. * * @public * @param {String} eventName Name of the event. * @param {Function} listener Callback function. * @return {void} */ uploader.removeListener(eventName, listener); /** * Removes all event listeners from the content uploader. * * @public * @return {void} */ uploader.removeAllListeners(); ``` ### Parameters | Parameter | Type | Description | | --- | --- | --- | | folderId | String | Box Folder ID. This will be the ID of the folder from which you want files to be uploaded to. If you want to use the Box All Files folder, then use 0 as the folderId. | | accessToken | String | Box API access token to use. This should have upload access to the folder above. | | options | Object | Optional options. See below for details. | ### Options | Parameter | Type | Default | Description | | --- | --- | --- | --- | | container | String | document.body | CSS selector of the container in which the content uploader should be placed. Calling hide() will clear out this container. | | sharedLink | String | | Shared link URL, required if folder is shared and the access token doesn't belong to an owner or collaborator of the file. | | sharedLinkPassword | String | | Shared link password, required if shared link has a password. | | onClose | Function | | Callback function for 'Close' button, which will appear when there are no files to upload or when all uploads are complete. If this option is set to null the button will not appear. | | modal | Object | | When the modal attribute is specified, then the content uploader will not be created in-place. Instead a button will be created in the container and clicking this button will launch the content uploader in a modal popup. See below for the modal options. | | size | String | undefined | Indicates to the content uploader to fit within a small or large width container. Value can be absent or one of small or large. If absent the UI Element will adapt to its container and automatically switch between small width or large width mode. | | isTouch | Boolean | Defaults to the browser and device's default touch support | Indicates to the content explorer that it's is being rendered on a touch enabled device. | | fileLimit | Number | 100 | The maximum number of files that can be uploaded at once. If more than fileLimit files are selected for upload, any beyond the first fileLimit files will not be included for uploaded. A warning message will be shown in the footer when this happens. | | requestInterceptor | Function | | Function to intercept requests. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | | responseInterceptor | Function | | Function to intercept responses. For an example see this CodePen. Our underlying XHR library is axios.js and we follow a similar approach for interceptors. | ### Modal Options | Parameter | Type | Default | Description | | --- | --- | --- | --- | | buttonLabel | String | | Label for the button | | buttonClassName | String | Box Blue Button | CSS class to decorate the button | | modalClassName | String | | CSS class to decorate the modal popup content | | overlayClassName | String | | CSS class to decorate the modal popup overlay | ### Events | Event Name | Event Data | Description | | --- | --- | --- | | close | | Will be fired when 'Close' button is clicked. | | complete | Array<File> | Will be fired when all uploads in the current view are complete. Event data will be an array of File Object. | | upload | File | Fired when a single file is successfully uploaded. Event data will be a File Object. | | error | Object | Fired when a single file has an upload error. Event data will be an object with properties file from the File Web API and the error object error. | ## Scopes If your application requires the end user to only be able to access a subset of the Content Uploader functionality, you can use [Downscoping](guide://authentication/tokens/downscope) to appropriately downscope the Access Token to a resulting token that has the desired set of permissions, and can thus, be securely passed to the end user client initializing the Content Uploader. Below are a set of UI Element-specific scopes to go alongside Downscoping. These allow developers to enable/disable UI controls on the Content Uploader by configuring the appropriate scopes on the downscoped token. To learn more, see [Dedicated Scopes for Box UI Elements](guide://api-calls/permissions-and-errors/scopes). ### Base Scope | Scope Name | Permissions granted | | --- | --- | | base_upload | Allows upload into the folder specific under "resource" of the Token Exchange request. | ### Sample Scenarios | Scenario | Scopes | | --- | --- | | User wants to upload files to a Box folder | base_upload | **Reference:** https://developer.box.com/guides/embed/ui-elements/uploader/ --- ## Untitled *Type: guide | Category: Embed Box * UI Elements design tokens This table shows all the design tokens you can use for theming and styling purposes. Provided default values and… # UI Elements design tokens This table shows all the design tokens you can use for [theming and styling](g://embed/ui-elements/theming-styling) purposes. Provided default values and descriptions give clarity and guidance for implementation. ## Token structure There are two ways to provide tokens to the theme object in Content Explorer: flatten structure using full token names and nested structure using shortened names. The latter allows you to group tokens, which might improve the readability of your customization, but both produce the same results. ### Example Flatten structure: ``` const theme = { tokens: { "body-default-font-size": "14px", "body-default-font-weight": "400" "body-default-text-decoration": "none", "body-default-bold-line-height": "20px", } }; ``` Nested structure: ``` const theme = { tokens: { Body: { Default: { "font-size": "14px", "font-weight": "400", "text-decoration": "none", } "Default Bold": { "line-height": "20px", } } } }; ``` ## Border colors You can pass any CSS color value, like hexadecimal colors, RGB, cross-browser color names, and so on. | Token | Default value | Description | | --- | --- | --- | | border-checkbox-border | #6f6f6f | Default border color for checkboxes. | | border-checkbox-border-hover | #4e4e4e | Border color when hovering over checkboxes. | | border-checkbox-border-selected | #0061d5 | Border color for selected checkboxes. | | border-checkbox-border-selected-hover | #2079e3 | Border color when hovering over selected checkboxes. | | border-cta-border-outline | #000000 | Border for secondary buttons with transparent background. | | border-cta-border-outline-disabled | #646464 | Border for disabled outline buttons. | | border-cta-border-outline-hover | #000000 | Border for outline buttons on hover. | | border-cta-border-outline-pressed | #000000 | Border for outline buttons when pressed. | | border-cta-border-secondary | #bcbcbc | Border for secondary buttons. | | border-cta-border-secondary-disabled | #e8e8e8 | Border for disabled secondary buttons. | | border-cta-border-secondary-hover | #bcbcbc | Border for secondary buttons on hover. | | border-cta-border-secondary-pressed | #bcbcbc | Border for secondary buttons when pressed. | | border-divider-border | #e8e8e8 | Horizontal line separators. | | border-dropdown-border | #bcbcbc | Border for dropdown menus. | | border-gridthumbnail-border | #e8e8e8 | Border for item (file/folder) thumbnails in grid view. | | border-input-border | #909090 | Border for text inputs. | | border-input-border-error | #ed3757 | Border for text inputs with errors. | | border-input-border-focus | #2486fc | Border for focused text inputs. | | border-input-border-hover | #6f6f6f | Border for text inputs on hover. | | border-search-border | #f4f4f4 | Border for search inputs. | | border-search-border-hover | #6f6f6f | Border for search inputs on hover. | | border-switch-border | #bcbcbc | Border for toggle switches. | | border-switch-border-hover | #bcbcbc | Border for toggle switches on hover. | | border-tooltip-border-error | #f69bab | Border for error tool tips. | ## Icon colors You can only style interactive icons such as buttons or drop down. | Token | Default value | Description | | --- | --- | --- | | icon-cta-icon | #6f6f6f | Default color for icons in buttons. | | icon-cta-icon-hover | #222222 | Color for icons in buttons on hover. | | icon-cta-icon-pressed | #222222 | Color for icons in buttons when pressed. | ## Outline colors | Token | Default value | Description | | --- | --- | --- | | outline-focus-on-dark | #ffffff | Focus outline color on dark backgrounds. | | outline-focus-on-light | #2486fc | Focus outline color on light backgrounds. | ## Surface colors | Token | Default value | Description | | --- | --- | --- | | surface-checkbox-surface | #ffffff | Background color for checkboxes. | | surface-checkbox-surface-hover | #ffffff | Background color for checkboxes on hover. | | surface-checkbox-surface-selected | #0061d5 | Background color for selected checkboxes. | | surface-checkbox-surface-selected-hover | #2079e3 | Background color for selected checkboxes on hover. | | surface-cta-surface-icon | rgba(0, 0, 0, 0) | Background for icon buttons. | | surface-cta-surface-icon-disabled | rgba(0, 0, 0, 0) | Background for disabled icon buttons. | | surface-cta-surface-icon-hover | rgba(0, 0, 0, 0.04) | Background for icon buttons on hover. | | surface-cta-surface-icon-pressed | rgba(0, 0, 0, 0.08) | Background for icon buttons when pressed. | | surface-cta-surface-outline | rgba(0, 0, 0, 0) | Background for secondary buttons with transparent background. | | surface-cta-surface-outline-hover | rgba(0, 0, 0, 0.04) | Background for outline buttons on hover. | | surface-cta-surface-outline-pressed | rgba(0, 0, 0, 0.08) | Background for outline buttons when pressed. | | surface-cta-surface-secondary | #ffffff | Background for secondary buttons. | | surface-cta-surface-secondary-hover | #f4f4f4 | Background for secondary buttons on hover. | | surface-cta-surface-secondary-pressed | #e8e8e8 | Background for secondary buttons when pressed. | | surface-cta-surface-tertiary | #ffffff | Background for link styled buttons. | | surface-cta-surface-tertiary-hover | #f4f4f4 | Background for link styled buttons on hover. | | surface-cta-surface-tertiary-pressed | #e8e8e8 | Background for link styled buttons when pressed. | | surface-dropdown-surface | #ffffff | Background for dropdown menus. | | surface-dropdown-surface-error | #ffffff | Background for dropdown menus with errors. | | surface-dropdown-surface-focus | #ffffff | Background for focused dropdown menus. | | surface-dropdown-surface-hover | #ffffff | Background for dropdown menus on hover. | | surface-illustration-surface-box-neutral | #0061d5 | Color for illustrations (detailed icons). | | surface-input-surface | #ffffff | Background for text inputs. | | surface-input-surface-error | #ffffff | Background for text inputs with errors. | | surface-input-surface-focus | #ffffff | Background for focused text inputs. | | surface-input-surface-hover | #ffffff | Background for text inputs on hover. | | surface-menu-surface | #ffffff | Background for dropdown menu options. | | surface-menu-surface-focus | #f4f4f4 | Background for focused menu items. | | surface-menu-surface-hover | #f4f4f4 | Background for menu items on hover. | | surface-search-surface | #f4f4f4 | Background for search inputs. | | surface-search-surface-focused | #ffffff | Background for focused search inputs. | | surface-search-surface-hover | #fbfbfb | Background for search inputs on hover. | | surface-sliderthumb-surface | #0061d5 | Color for range slider thumbs. | | surface-sliderthumb-surface-hover | #2486fc | Color for range slider thumbs on hover. | | slidertrack-surface | #6f6f6f | Color for range slider tracks. | | surface-surface | #ffffff | General background color. | | surface-surface-brand | #0061d5 | Background for primary buttons. | | surface-surface-brand-disabled | #0061d5 | Background for disabled primary buttons. | | surface-surface-brand-hover | #006ae9 | Background for primary buttons on hover. | | surface-surface-brand-pressed | #004eac | Background for primary buttons when pressed. | | surface-switch-surface | #ffffff | Background for toggle switches. | | surface-switch-surface-off | #d3d3d3 | Background for toggle switches in off state. | | surface-switch-surface-on | #0061d5 | Background for toggle switches in on state. | | surface-tooltip-surface | #4e4e4e | Background for tool tips. | | surface-tooltip-surface-error | #fdebee | Background for error tool tips. | ## Text colors | Token | Default value | Description | | --- | --- | --- | | text-cta-link | #0061d5 | Color for hyperlinks. | | text-cta-link-disabled | #b2cff2 | Color for disabled hyperlinks. | | text-cta-link-hover | #1d6bca | Color for hyperlinks on hover. | | text-cta-link-pressed | #2486fc | Color for hyperlinks when pressed. | | text-text-error-on-light | #d5324e | Error text color on light backgrounds. | | text-text-on-dark | #ffffff | Text color on dark backgrounds. | | text-text-on-light | #222222 | Primary text color on light backgrounds. | | text-text-on-light-secondary | #6f6f6f | Secondary text color on light backgrounds. | | text-text-on-light-secondary-hover | #4e4e4e | Secondary text color on hover. | ## Typography tokens The comment in the table refers to pixels in calculation based on a root font-size of 16 px. | Token | Default value | Description | | --- | --- | --- | | body-default-font-family | Lato, "Helvetica Neue", sans-serif | Font family for body text. | | body-default-font-size | 0.875rem | Font size for body text. | | body-default-font-weight | 400 | Font weight for body text. | | body-default-letter-spacing | 0.01875rem | Letter spacing for body text. | | body-default-line-height | 1.25rem | Line height for body text. | | body-default-text-decoration | none | Text decoration for body text. | | body-default-bold-font-family | Lato, "Helvetica Neue", sans-serif | Font family for bold body text. | | body-default-bold-font-size | 0.875rem | Font size for bold body text. | | body-default-bold-font-weight | 700 | Font weight for bold body text. | | body-default-bold-letter-spacing | 0.01875rem | Letter spacing for bold body text. | | body-default-bold-line-height | 1.25rem | Line height for bold body text. | | body-default-bold-text-decoration | none | Text decoration for bold body text. | | body-default-semibold-font-family | Lato, "Helvetica Neue", sans-serif | Font family for semi-bold body text. | | body-default-semibold-font-size | 0.875rem | Font size for semi-bold body text. | | body-default-semibold-font-weight | 600 | Font weight for semi-bold body text. | | body-default-semibold-letter-spacing | 0.01875rem | Letter spacing for semi-bold body text. | | body-default-semibold-line-height | 1.25rem | Line height for semi-bold body text. | | body-default-semibold-text-decoration | none | Text decoration for semi-bold body text. | | body-large-font-family | Lato, "Helvetica Neue", sans-serif | Font family for large body text. | | body-large-font-size | 1rem | Font size for large body text. | | body-large-font-weight | 400 | Font weight for large body text. | | body-large-letter-spacing | 0.01875rem | Letter spacing for large body text. | | body-large-line-height | 1.5rem | Line height for large body text. | | body-large-text-decoration | none | Text decoration for large body text. | | body-large-bold-font-family | Lato, "Helvetica Neue", sans-serif | Font family for large bold body text. | | body-large-bold-font-size | 1rem | Font size for large bold body text. | | body-large-bold-font-weight | 700 | Font weight for large bold body text. | | body-large-bold-letter-spacing | 0.01875rem | Letter spacing for large bold body text. | | body-large-bold-line-height | 1.5rem | Line height for large bold body text. | | body-large-bold-text-decoration | none | Text decoration for large bold body text. | | caption-bold-font-family | Lato, "Helvetica Neue", sans-serif | Font family for bold captions. | | caption-bold-font-size | 0.75rem | Font size for bold captions. | | caption-bold-font-weight | 700 | Font weight for bold captions. | | caption-bold-letter-spacing | 0.01875rem | Letter spacing for bold captions. | | caption-bold-line-height | 0.875rem | Line height for bold captions. | | caption-bold-text-decoration | none | Text decoration for bold captions. | | caption-default-font-family | Lato, "Helvetica Neue", sans-serif | Font family for captions. | | caption-default-font-size | 0.75rem | Font size for captions. | | caption-default-font-weight | 400 | Font weight for captions. | | caption-default-letter-spacing | 0.01875rem | Letter spacing for captions. | | caption-default-line-height | 0.875rem | Line height for captions. | | caption-default-text-decoration | none | Text decoration for captions. | | label-bold-font-family | Lato, "Helvetica Neue", sans-serif | Font family for bold labels. | | label-bold-font-size | 0.625rem | Font size for bold labels. | | label-bold-font-weight | 700 | Font weight for bold labels. | | label-bold-letter-spacing | 0.0375rem | Letter spacing for bold labels. | | label-bold-line-height | 1rem | Line height for bold labels. | | label-bold-text-decoration | none | Text decoration for bold labels. | | label-default-font-family | Lato, "Helvetica Neue", sans-serif | Font family for labels. | | label-default-font-size | 0.625rem | Font size for labels. | | label-default-font-weight | 400 | Font weight for labels. | | label-default-letter-spacing | 0.0375rem | Letter spacing for labels. | | label-default-line-height | 1rem | Line height for labels. | | label-default-text-decoration | none | Text decoration for labels. | | link-default-font-family | Lato, "Helvetica Neue", sans-serif | Font family for hyperlinks. | | link-default-font-size | 0.875rem | Font size for hyperlinks. | | link-default-font-weight | 400 | Font weight for hyperlinks. | | link-default-letter-spacing | 0.01875rem | Letter spacing for hyperlinks. | | link-default-line-height | 1.25rem | Line height for hyperlinks. | | link-default-text-decoration | underline | Text decoration for hyperlinks. | | notification-default-font-family | Lato, "Helvetica Neue", sans-serif | Font family for notifications. | | notification-default-font-size | 0.5625rem | Font size for notifications. | | notification-default-font-weight | 700 | Font weight for notifications. | | notification-default-letter-spacing | 0.01875rem | Letter spacing for notifications. | | notification-default-line-height | 0.75rem | Line height for notifications. | | notification-default-text-decoration | none | Text decoration for notifications. | | title-large-font-family | Lato, "Helvetica Neue", sans-serif | Font family for large titles. | | title-large-font-size | 1.125rem | Font size for large titles. | | title-large-font-weight | 700 | Font weight for large titles. | | title-large-letter-spacing | 0.01875rem | Letter spacing for large titles. | | title-large-line-height | 1.5rem | Line height for large titles. | | title-large-text-decoration | none | Text decoration for large titles. | | title-medium-font-family | Lato, "Helvetica Neue", sans-serif | Font family for medium titles. | | title-medium-font-size | 1rem | Font size for medium titles. | | title-medium-font-weight | 700 | Font weight for medium titles. | | title-medium-letter-spacing | 0.01875rem | Letter spacing for medium titles. | | title-medium-line-height | 1.5rem | Line height for medium titles. | | title-medium-text-decoration | none | Text decoration for medium titles. | | title-small-font-family | Lato, "Helvetica Neue", sans-serif | Font family for small titles. | | title-small-font-size | 0.9375rem | Font size for small titles. | | title-small-font-weight | 700 | Font weight for small titles. | | title-small-letter-spacing | 0.01875rem | Letter spacing for small titles. | | title-small-line-height | 1.25rem | Line height for small titles. | | title-small-text-decoration | none | Text decoration for small titles. | | title-subtitle-font-family | Lato, "Helvetica Neue", sans-serif | Font family for subtitles. | | title-subtitle-font-size | 0.875rem | Font size for subtitles. | | title-subtitle-font-weight | 700 | Font weight for subtitles. | | title-subtitle-letter-spacing | 0.01875rem | Letter spacing for subtitles. | | title-subtitle-line-height | 1.25rem | Line height for subtitles. | | title-subtitle-text-decoration | none | Text decoration for subtitles. | | title-x-large-font-family | Lato, "Helvetica Neue", sans-serif | Font family for extra-large titles. | | title-x-large-font-size | 1.3125rem | Font size for extra-large titles. | | title-x-large-font-weight | 700 | Font weight for extra-large titles. | | title-x-large-letter-spacing | 0.01875rem | Letter spacing for extra-large titles. | | title-x-large-line-height | 2rem | Line height for extra-large titles. | | title-x-large-text-decoration | none | Text decoration for extra-large titles. | ## Spacing, sizing, and shape tokens The comment in the table refers to pixels in calculation based on a root font-size of 16 px. | Token | Default value | Description | | --- | --- | --- | | border-1 | 0.0625rem | Border width (1 px equivalent). | | border-2 | 0.125rem | Border width (2 px equivalent). | | border-3 | 0.1875rem | Border width (3 px equivalent). | | border-4 | 0.25rem | Border width (4 px equivalent). | | border-6 | 0.375rem | Border width (6 px equivalent). | | border-8 | 0.5rem | Border width (8 px equivalent). | | dropshadow-1 | 0 0 0.5rem 0 rgba(0, 0, 0, 0.05) | Subtle shadow effect. | | dropshadow-2 | 0 0.0625rem 0.25rem 0 rgba(0, 0, 0, 0.1) | Medium shadow effect. | | dropshadow-3 | 0 0.25rem 0.75rem 0 rgba(0, 0, 0, 0.1) | Pronounced shadow effect. | | radius-05 | 0.125rem | Border radius (2 px equivalent). | | radius-1 | 0.25rem | Border radius (4 px equivalent). | | radius-2 | 0.375rem | Border radius (6 px equivalent). | | radius-3 | 0.5rem | Border radius (8 px equivalent). | | radius-4 | 0.75rem | Border radius (12 px equivalent). | | radius-5 | 1rem | Border radius (16 px equivalent). | | radius-6 | 1.25rem | Border radius (20 px equivalent). | | radius-7 | 1.5rem | Border radius (24 px equivalent). | | radius-8 | 1.75rem | Border radius (28 px equivalent). | | radius-half | 2rem | Border radius (32 px equivalent). | | size-05 | 0.125rem | Size measurement (2 px equivalent). | | size-1 | 0.25rem | Size measurement (4 px equivalent). | | size-2 | 0.5rem | Size measurement (8 px equivalent). | | size-3 | 0.75rem | Size measurement (12 px equivalent). | | size-4 | 1rem | Size measurement (16 px equivalent). | | size-5 | 1.25rem | Size measurement (20 px equivalent). | | size-6 | 1.5rem | Size measurement (24 px equivalent). | | size-7 | 1.75rem | Size measurement (28 px equivalent). | | size-8 | 2rem | Size measurement (32 px equivalent). | | size-9 | 2.25rem | Size measurement (36 px equivalent). | | size-10 | 2.5rem | Size measurement (40 px equivalent). | | size-11 | 2.75rem | Size measurement (44 px equivalent). | | size-12 | 3rem | Size measurement (48 px equivalent). | | size-14 | 3.5rem | Size measurement (56 px equivalent). | | size-15 | 3.75rem | Size measurement (60 px equivalent). | | size-16 | 4rem | Size measurement (64 px equivalent). | | size-18 | 4.5rem | Size measurement (72 px equivalent). | | size-20 | 5rem | Size measurement (80 px equivalent). | | space-05 | 0.125rem | Spacing measurement (2 px equivalent). | | space-1 | 0.25rem | Spacing measurement (4 px equivalent). | | space-2 | 0.5rem | Spacing measurement (8 px equivalent). | | space-3 | 0.75rem | Spacing measurement (12 px equivalent). | | space-4 | 1rem | Spacing measurement (16 px equivalent). | | space-5 | 1.25rem | Spacing measurement (20 px equivalent). | | space-6 | 1.5rem | Spacing measurement (24 px equivalent). | | space-7 | 1.75rem | Spacing measurement (28 px equivalent). | | space-8 | 2rem | Spacing measurement (32 px equivalent). | | space-9 | 2.25rem | Spacing measurement (36 px equivalent). | | space-10 | 2.5rem | Spacing measurement (40 px equivalent). | | space-11 | 2.75rem | Spacing measurement (44 px equivalent). | | space-12 | 3rem | Spacing measurement (48 px equivalent). | | space-14 | 3.5rem | Spacing measurement (56 px equivalent). | | space-15 | 3.75rem | Spacing measurement (60 px equivalent). | | space-16 | 4rem | Spacing measurement (64 px equivalent). | | space-18 | 4.5rem | Spacing measurement (72 px equivalent). | | space-20 | 5rem | Spacing measurement (80 px equivalent). | **Reference:** https://developer.box.com/guides/embed/ui-elements/ui-elements-design-tokens/ --- ## Untitled *Type: guide | Category: Folders * Build Folder Tree The following examples provide an example on how to create a JSON representation of a folder tree. A folder tree is the… # Build Folder Tree The following examples provide an example on how to create a JSON representation of a folder tree. A folder tree is the name of a folder, and every subfolder within that folder. The sample below allows for specifying the starting **root** folder and the maximum depth the code should traverse. It also allows for configuring what user is authenticated by allowing the passing in of an initialized SDK client. ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Box.V2; using Box.V2.Auth; using Box.V2.Config; using Box.V2.Converter; using Box.V2.Exceptions; using Box.V2.JWTAuth; using Box.V2.Models; using Newtonsoft.Json; namespace BoxPlayground { public class Program4 { static void Main(string[] args) { ExecuteMainAsync().Wait(); } public class BoxFolderTreeBuilder { public BoxClient BoxClient { get; set; } public string RootFolderId { get; set; } public int MaxDepth { get; set; } public BoxFolderTreeBuilder(BoxClient boxClient, string rootFolderId = "0", int maxDepth = -1) { this.BoxClient = boxClient; this.RootFolderId = rootFolderId; this.MaxDepth = maxDepth; } public async Task<BoxFolderTree> BuildFolderTreeWithFlatLists() { var tree = new BoxFolderTree { RootId = this.RootFolderId, Files = new List<BoxFolderTreeItem>(), Folders = new List<BoxFolderTreeFolder>() }; var rootFolderItems = await this.BoxClient.FoldersManager.GetFolderItemsAsync(this.RootFolderId, limit: 1000, autoPaginate: true); var rootFolderChildren = new List<BoxFolderTreeFolder>(); foreach (var item in rootFolderItems.Entries) { var folderTreeItem = new BoxFolderTreeItem(item); folderTreeItem.Path = $"{this.RootFolderId}"; if (item.Type == "file") { tree.Files.Add(folderTreeItem); } else if (item.Type == "folder") { var childFolder = new BoxFolderTreeFolder(folderTreeItem); tree.Folders.Add(new BoxFolderTreeFolder(folderTreeItem)); rootFolderChildren.Add(childFolder); } } tree = await Dive(tree, rootFolderChildren, 1); return tree; } private async Task<BoxFolderTree> Dive(BoxFolderTree tree, List<BoxFolderTreeFolder> children, int currentDepth) { if (InTooDeep(currentDepth)) { return tree; } else { currentDepth++; var additionalChildren = new List<BoxFolderTreeFolder>(); foreach (var child in children) { var folderItems = await this.BoxClient.FoldersManager.GetFolderItemsAsync(child.Item.Id, limit: 1000, autoPaginate: true); var foundFolder = tree.Folders.FindIndex((f) => { return f.Item.Id == child.Item.Id; }); foreach (var item in folderItems.Entries) { if (foundFolder >= 0) { tree.Folders[foundFolder].Children.Add(item); } var folderTreeItem = new BoxFolderTreeItem(item); folderTreeItem.Path = $"{child.Path}/{child.Item.Id}"; if (item.Type == "file") { tree.Files.Add(folderTreeItem); } else if (item.Type == "folder") { var childFolder = new BoxFolderTreeFolder(folderTreeItem); tree.Folders.Add(new BoxFolderTreeFolder(folderTreeItem)); additionalChildren.Add(childFolder); } } } if (additionalChildren.Count == 0) { return tree; } else { return await Dive(tree, additionalChildren, currentDepth); } } } private bool InTooDeep(int depthCount) { if (this.MaxDepth < 0) { return false; } else { return (depthCount >= this.MaxDepth); } } public class BoxFolderTreeItem { [JsonProperty(PropertyName = "item")] public BoxItem Item { get; set; } [JsonProperty(PropertyName = "path")] public string Path { get; set; } public BoxFolderTreeItem(BoxItem item) { Item = item; } } public class BoxFolderTreeFolder : BoxFolderTreeItem { public BoxFolderTreeFolder(BoxFolderTreeItem item) : base(item.Item) { this.Path = item.Path; } [JsonProperty(PropertyName = "children")] public List<BoxItem> Children { get; set; } = new List<BoxItem>(); } public class BoxFolderTree { [JsonProperty(PropertyName = "rootId")] public string RootId { get; set; } [JsonProperty(PropertyName = "files")] public List<BoxFolderTreeItem> Files { get; set; } [JsonProperty(PropertyName = "folders")] public List<BoxFolderTreeFolder> Folders { get; set; } public string writeJSON() { var converter = new Box.V2.Converter.BoxJsonConverter(); return converter.Serialize<BoxFolderTreeBuilder.BoxFolderTree>(this); } } } private static async Task ExecuteMainAsync() { using (FileStream fs = new FileStream($"./config.json", FileMode.Open)) { var session = new BoxJWTAuth(BoxConfig.CreateFromJsonFile(fs)); var serviceAccountClient = session.AdminClient(session.AdminToken()); var folderTreeBuilder = new BoxFolderTreeBuilder(serviceAccountClient, rootFolderId: "37477903736"); var tree = await folderTreeBuilder.BuildFolderTreeWithFlatLists(); System.Console.WriteLine(tree.writeJSON()); } } } } ``` ``` package com.box; import java.io.BufferedReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import com.box.sdk.BoxConfig; import com.box.sdk.BoxDeveloperEditionAPIConnection; import com.box.sdk.BoxFile; import com.box.sdk.BoxFolder; import com.box.sdk.BoxItem; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; public class BoxFolderTreeBuilder { private BoxDeveloperEditionAPIConnection _boxClient; private String _rootFolderId; private int _maxDepth; private static final String DEFAULT_ROOT_FOLDER_ID = "0"; private static final int DEFAULT_MAX_DEPTH = -1; public BoxFolderTreeBuilder(BoxDeveloperEditionAPIConnection boxClient) { this(boxClient, DEFAULT_ROOT_FOLDER_ID, DEFAULT_MAX_DEPTH); } public BoxFolderTreeBuilder(BoxDeveloperEditionAPIConnection boxClient, String rootFolderId) { this(boxClient, rootFolderId, DEFAULT_MAX_DEPTH); } public BoxFolderTreeBuilder(BoxDeveloperEditionAPIConnection boxClient, int maxDepth) { this(boxClient, DEFAULT_ROOT_FOLDER_ID, maxDepth); } public BoxFolderTreeBuilder(BoxDeveloperEditionAPIConnection boxClient, String rootFolderId, int maxDepth) { this._boxClient = boxClient; this._rootFolderId = rootFolderId; this._maxDepth = maxDepth; } public BoxFolderTree buildFolderTreeWithFlatLists() { BoxFolderTree tree = new BoxFolderTree(); tree.setRootId(this._rootFolderId); ArrayList<BoxFolderTreeFolder> rootFolderChildren = new ArrayList<>(); BoxFolder folder = new BoxFolder(this._boxClient, this._rootFolderId); String path = this._rootFolderId; for (BoxItem.Info itemInfo : folder) { if (itemInfo instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; BoxFolderTreeFile treeFile = new BoxFolderTreeFile(fileInfo, path); tree.files.add(treeFile); } else if (itemInfo instanceof BoxFolder.Info) { BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; BoxFolderTreeFolder treeFolder = new BoxFolderTreeFolder(folderInfo, path); tree.folders.add(treeFolder); rootFolderChildren.add(treeFolder); } } tree = Dive(tree, rootFolderChildren, 1); return tree; } private BoxFolderTree Dive(BoxFolderTree tree, ArrayList<BoxFolderTreeFolder> children, int currentDepth) { if (inTooDeep(currentDepth)) { return tree; } else { currentDepth++; ArrayList<BoxFolderTreeFolder> additionalChildren = new ArrayList<>(); for (BoxFolderTreeFolder child : children) { BoxFolder folderItems = new BoxFolder(this._boxClient, child.getItem().getID()); int foundFolder = -1; for (int i = 0; i < tree.folders.size(); i++) { if (child.getItem().getID() == tree.folders.get(i).getItem().getID()) { foundFolder = i; } } String path = String.format("%s/%s", child.getPath(), child.getItem().getID()); for (BoxItem.Info item : folderItems.getChildren()) { if (foundFolder >= 0) { tree.folders.get(foundFolder).children.add(new BoxFolderTreeItem(item)); } if (item instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) item; tree.files.add(new BoxFolderTreeFile(fileInfo, path)); } else if (item instanceof BoxFolder.Info) { BoxFolder.Info folderInfo = (BoxFolder.Info) item; BoxFolderTreeFolder nestedFolder = new BoxFolderTreeFolder(folderInfo, path); tree.folders.add(nestedFolder); additionalChildren.add(nestedFolder); } } } if (additionalChildren.size() == 0) { return tree; } else { return Dive(tree, additionalChildren, currentDepth); } } } private Boolean inTooDeep(int depthCount) { if (this._maxDepth < 0) { return false; } else { return (depthCount >= this._maxDepth); } } public class BoxFolderTree { private String rootId; private ArrayList<BoxFolderTreeFile> files = new ArrayList<>(); private ArrayList<BoxFolderTreeFolder> folders = new ArrayList<>(); public String getRootId() { return this.rootId; } public void setRootId(String id) { this.rootId = id; } public String writeJSON() { JsonObject requestJSON = new JsonObject(); JsonArray filesJSON = new JsonArray(); for (BoxFolderTreeFile file : files) { filesJSON.add(file.convertToJSON()); } JsonArray foldersJSON = new JsonArray(); for (BoxFolderTreeFolder folder : folders) { foldersJSON.add(folder.convertToJSON()); } requestJSON.add("rootId", this.rootId); requestJSON.add("files", filesJSON); requestJSON.add("folders", foldersJSON); return requestJSON.toString(); } } public class BoxFolderTreeItem { private BoxItem.Info item; public BoxFolderTreeItem(BoxItem.Info item) { this.item = item; } public JsonObject convertToJSON() { JsonObject itemJSON = new JsonObject(); itemJSON.add("id", this.item.getID()); itemJSON.add("name", this.item.getName()); String type = (item instanceof BoxFile.Info == true) ? "file" : "folder"; itemJSON.add("type", type); return itemJSON; } } public class BoxFolderTreeFile { private BoxFile.Info item; private String path; public BoxFolderTreeFile(BoxFile.Info item, String path) { this.item = item; this.path = path; } public BoxFile.Info getItem() { return this.item; } public void setItem(BoxFile.Info info) { this.item = info; } public String getPath() { return this.path; } public void setPath(String path) { this.path = path; } public JsonObject convertToJSON() { JsonObject itemJSON = new JsonObject(); JsonObject fileJSON = new JsonObject(); fileJSON.add("id", this.item.getID()); fileJSON.add("type", "file"); fileJSON.add("name", this.item.getName()); itemJSON.add("path", this.path); itemJSON.add("item", fileJSON); return itemJSON; } } public class BoxFolderTreeFolder { private BoxFolder.Info item; private String path; private ArrayList<BoxFolderTreeItem> children; public BoxFolderTreeFolder(BoxFolder.Info item, String path) { this.item = item; this.path = path; this.children = new ArrayList<>(); } public BoxFolder.Info getItem() { return this.item; } public void setItem(BoxFolder.Info info) { this.item = info; } public String getPath() { return this.path; } public void setPath(String path) { this.path = path; } public JsonObject convertFolderToJSON() { JsonObject itemJSON = new JsonObject(); JsonObject folderJSON = new JsonObject(); folderJSON.add("id", this.item.getID()); folderJSON.add("type", "folder"); folderJSON.add("name", this.item.getName()); itemJSON.add("path", this.path); itemJSON.add("item", folderJSON); return itemJSON; } public JsonObject convertToJSON() { JsonObject folderJSON = this.convertFolderToJSON(); JsonArray children = new JsonArray(); for (BoxFolderTreeItem item : this.children) { children.add(item.convertToJSON()); } folderJSON.add("children", children); return folderJSON; } } public static void main(String[] args) throws Exception { Path configPath = Paths.get("config.json"); try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) { BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection serviceAccountClient = BoxDeveloperEditionAPIConnection .getAppEnterpriseConnection(boxConfig); BoxFolderTreeBuilder treeBuilder = new BoxFolderTreeBuilder(serviceAccountClient, "43491738095", 2); BoxFolderTree tree = treeBuilder.buildFolderTreeWithFlatLists(); System.out.println(tree.writeJSON()); } } } ``` ``` class BoxFolderTreeBuilder { constructor(boxClient, options) { options = options || {}; boxClient._useIterators = true; this.boxClient = boxClient; this.maxDepth = options.maxDepth || -1; this.rootFolderId = options.rootFolderId || "0"; } async buildFolderTreeWithFlatLists() { let tree = { rootId: this.rootFolderId, folders: [], files: [] } let folderItemsIterator = await this.boxClient.folders.getItems(this.rootFolderId); let collection = await BoxUtilities.autoPage(folderItemsIterator); let rootFolderChildren = []; const path = `${this.rootFolderId}`; collection.forEach((item) => { if (item.type === "file") { tree.files.push({ item, path }) } else if (item.type === "folder") { let folderTreeFolder = { item, path, children: [] } tree.folders.push(folderTreeFolder); rootFolderChildren.push(folderTreeFolder); } }); tree = await this.dive(tree, rootFolderChildren, 1); return tree; } async dive(tree, children, currentDepth) { if (this.inTooDeep(currentDepth)) { return tree; } else { currentDepth++; let additionalChildren = []; let childrenPromises = []; children.forEach((child) => { let foundFolder = -1; childrenPromises.push(this.boxClient.folders.getItems(child.item.id) .then((folderItemsIterator) => { return BoxUtilities.autoPage(folderItemsIterator) .then((collection) => { for (let i = 0; i < tree.folders.length; i++) { if (child.item.id === tree.folders[i].item.id) { foundFolder = i; } } const path = `${child.path}/${child.item.id}`; collection.forEach((item) => { if (foundFolder >= 0) { tree.folders[foundFolder].children.push(item); } if (item.type === "file") { tree.files.push({ item, path }) } else if (item.type === "folder") { let folderTreeFolder = { item, path, children: [] } tree.folders.push(folderTreeFolder); additionalChildren.push(folderTreeFolder); } }); return; }); })); }); await Promise.all(childrenPromises); if (additionalChildren.length === 0) { return tree; } else { return this.dive(tree, additionalChildren, currentDepth); } } } inTooDeep(depthCount) { if (this.maxDepth < 0) { return false; } else { return (depthCount >= this.maxDepth); } } } class BoxUtilities { static async autoPage(iterator, collection = []) { let moveToNextItem = async () => { let item = await iterator.next(); if (item.value) { collection.push(item.value); } if (item.done !== true) { return moveToNextItem(); } else { return collection; } } return moveToNextItem(); } } let folderTreeBuilder = new BoxFolderTreeBuilder(client); folderTreeBuilder.buildFolderTreeWithFlatLists() .then((tree) => { console.log(JSON.stringify(tree)); }) ``` **Reference:** https://developer.box.com/guides/folders/bulk/build-folder-tree/ --- ## Untitled *Type: guide | Category: Folders * Change Folder Owner To change the owner of a folder, first invite the user you wish to transfer the folder to as a collaborator on the… # Change Folder Owner To change the owner of a folder, first invite the user you wish to transfer the folder to as a collaborator on the folder. Then, update the created collaboration by changing the role of that invited user to `owner`. ``` curl -X PUT https://api.box.com/2.0/collaborations/1234 \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "role": "owner" }' ``` ``` BoxCollaborationRequest requestParams = new BoxCollaborationRequest() { Id = "12345", Role = "owner" }; BoxCollaboration collab = await client.CollaborationsManager.EditCollaborationAsync(requestParams); ``` ``` Collection<BoxCollaboration.Info> pendingCollaborations = BoxCollaboration.getPendingCollaborations(api); for (BoxCollaboration.Info collabInfo : pendingCollaborations) { collabInfo.setRole(BoxCollaboration.Role.OWNER); collabInfo.getResource().updateInfo(collabInfo); } ``` ``` from boxsdk.object.collaboration import CollaborationRole, CollaborationStatus collaboration = client.collaboration(collab_id='12345') updated_collaboration = collaboration.update_info(CollaborationRole.OWNER) ``` ``` client.collaborations.update('12345', {role: client.collaborationRoles.OWNER}) .then(collaboration => { // ... }); ``` Depending on the settings, a user with access to a folder might be able to invite other users, yet in all cases only the current owner of a folder can transfer the ownership. **Reference:** https://developer.box.com/guides/folders/single/change-owner/ --- ## Untitled *Type: guide | Category: Embed Box * Preview - Viewers & Events This page describes the preview experience for each file type. It also lists the events you can listen for by… # Preview - Viewers & Events This page describes the preview experience for each file type. It also lists the events you can listen for by viewer type. ## Text Viewer The text viewer renders previews of text files. For code files like `py` or `rb`, it uses [`highlight.js`](https://github.com/isagalaev/highlight.js) to add syntax highlighting. ### Behavior The text viewer displays the first 192 KB of text in the file. Additional text is truncated and a notification and download button are appended to the bottom of the preview. Re-sizing the viewer window will reflow the text to fit the available space and the zoom in and out buttons will increase and decrease font size respectively. This viewer supports printing and will attempt to print with appropriate syntax highlighting when either `print()` is invoked or the print button is pressed. Note that printing large files may cause some browsers to freeze for a few seconds. ### Controls - Zoom In - Zoom Out - Fullscreen: can be exited with the escape key ### Supported File Extensions `as`, `as3as`, `asmas`, `batas`, `cas`, `ccas`, `cmakeas`, `cppas`, `csas`, `cssas`, `cxxas`, `diffas`, `erbas`, `groovyas`, `has`, `hamlas`, `hhas`, `htmas`, `htmlas`, `javaas`, `jsas`, `lessas`, `mas`, `makeas`, `mdas`, `mlas`, `mmas`, `phpas`, `plas`, `plistas`, `propertiesas`, `pyas`, `rbas`, `rstas`, `sassas`, `scalaas`, `scriptas`, `scmas`, `smlas`, `sqlas`, `shas`, `vias`, `vimas`, `webdocas`, `xhtmlas`, `yaml`, ### Events The text viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | | zoom | The preview zooms in or out | 1. {number} zoom: new zoom value | | | | 2. {boolean} canZoomIn: true if the viewer can zoom in more | | | | 3. {boolean} canZoomOut: true if the viewer can zoom out more | | printsuccess | An attempt to print triggered successfully | | ## 360 Video Viewer The 360 video viewer renders a preview of a video stored as an equirectangular projection (often recorded with a 360 camera). ### Behavior This viewer gives you an interactive view of the 360 degree video. ### Controls - Change the view direction with the left mouse button (single touch on touch-enabled device). ### VR button When using a browser that supports WebVR and a suitable VR device is attached to your computer, a VR button will be available to allow toggling in and out of VR mode. ### Limitations Currently, this previewer requires that the file be named with a `.360` preceding the file extension. This is so that Preview SDK knows to run this viewer rather than the standard video preview. ### Supported File Extensions `360.3g2`, `360.3gp`, `360.avi`, `360.m2v`, `360.m2ts`, `360.m4v`, `360.mkv`, `360.mov`, `360.mp4`, `360.mpeg`, `360.mpg`, `360.mts`, `360.qt`, `360.wmv` ### Events The 360 video viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | ## SWF Viewer The SWF viewer uses [`SWFObject`](https://github.com/swfobject/swfobject) to embed SWF files. ### Behavior If the user has the Adobe Flash Player plugin, `SWFObject` will embed the SWF file and allow the plugin to render relevant content. Note that all network requests made by the flash content will be blocked due to security constraints, so any content that requires network connectivity will not be rendered. ### Supported File Extensions - `swf` ### Events The SWF viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | ## Presentation viewer The presentation viewer renders previews of PowerPoint files. ### Behavior The presentation viewer remembers which slide you were viewing upon closing the preview. The next time that file is opened, you will immediately be brought to that slide. Scrolling the mouse up and down, or swiping up and down on mobile will transition between slides. Zooming in or out will increase or decrease the size of the slide respectively. If the zoom level causes the content to overflow, scrolling the mouse will allow you to scroll around the slide. To return to normal scrolling behavior, the user must zoom out until the overflow is removed. ### Controls - Zoom In - Zoom Out - Set Page: either with the up and down arrows, or by clicking the page number and entering text - Fullscreen: can be exited with the escape key ### Supported File Extensions `ppt`, `pptx`, `odp` ### Options | Option | Type | Description | | --- | --- | --- | | annotations | boolean | Optional. Whether annotations on content are shown. Defaults to false | ### Events The presentation viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. string error (optional): error message | | | | 2. object file: current file | | | | 3. object metrics: information from the logger | | | | 4. object viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | object file | | reload | The preview reloads | | | resize | The preview resizes | 1. number height: window height | | | | 2. number width: window width | | zoom | The preview zooms in or out | 1. number zoom: new zoom value | | | | 2. boolean canZoomIn: true if the viewer can zoom in more | | | | 3. boolean canZoomOut: true if the viewer can zoom out more | | pagerender | A page renders | number page number of rendered page | | pagefocus | A page is visible | number page number of focused page | | scrollstart | The viewer starts to scroll | 1. number scrollTop: number of pixels scrolled from top of viewport | | | | 2. number scrollLeft: number of pixels scrolled from left of viewport | | scrollend | The viewer stops scrolling | 1. number scrollTop: number of pixels scrolled from top of viewport | | | | 2. number scrollLeft: number of pixels scrolled from left of viewport | ## MP4 Viewer The MP4 viewer renders previews for video files. ### Behavior The MP4 viewer uses a black background to create a better viewing experience. Volume can be muted or unmuted by clicking the volume icon, or changed by dragging the volume scrubber. The position of the video can be changed by clicking or dragging the playback scrubber. ### Controls - Play/Pause - Volume - Settings - Fullscreen (can be exited with the escape key) ### Settings Settings are available through the cog icon in the preview toolbar. - Video speed values: `0.25`, `0.5`, normal (`1`), `1.25`, `1.5`, `2.0` ### Supported File Extensions `3g2`, `3gp`, `avi`, `m2v`, `m2ts`, `m4v`, `mkv`, `mov`, `mp4`, `mpeg`, `mpg`, `ogg`, `mts`, `qt`, `wmv` ### Events The MP4 viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. string error (optional): error message | | | | 2. object file: current file | | | | 3. object metrics: information from the logger | | | | 4. object viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | object file | | reload | The preview reloads | | | resize | The preview resizes | 1. number height: window height | | | | 2. number width: window width | | speedchange | Media speed changes | string playback speed | | play | The video plays | | | pause | The video pauses | | | seek | The video skips to a time | number time | ## MP3 Viewer The MP3 viewer displays previews for audio files. ### Behavior Volume can be muted or unmuted by clicking the volume icon, or changed by dragging the volume scrubber. The position of the audio can be changed by clicking or dragging the playback scrubber. ### Controls - Play/Pause - Volume - Settings ### Settings Settings are available through the cog icon in the preview toolbar. - Audio Speed: `0.25`, `0.5`, normal (`1`), `1.25`, `1.5`, `2.0` ### Supported File Extensions `aac`, `aif`, `aifc`, `aiff`, `amr`, `au`, `flac`, `m4a`, `mp3`, `ra`, `wav`, `wma` ### Events The MP3 viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. string error (optional): error message | | | | 2. object file: current file | | | | 3. object metrics: information from the logger | | | | 4. object viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | object file | | reload | The preview reloads | | | resize | The preview resizes | 1. number height: window height | | | | 2. number width: window width | | speedchange | Media speed changes | string playback speed | | play | The video plays | | | pause | The video pauses | | | seek | The video skips to a time | number time | ## Office Viewer The Office viewer renders previews of Microsoft Office documents by embedding an `<iframe>` of Microsoft's Office Online viewer. ### Behavior The Office viewer currently supports previews of Excel files using Microsoft Office Online from within the Box Web Application. Support for platform use cases and other Office file formats is in progress. There are several limitations at the moment: - File must be downloadable - File size cannot be greater than 5MB - File cannot be shared via a Box shared link with a password (shared links without passwords are okay) ### Supported File Extensions `xlsx` ### Events The Office viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | ## Markdown Viewer The Markdown viewer uses [`Remarkable`](https://github.com/jonschlinkert/remarkable) to parse markdown files and [`highlight.js`](https://github.com/isagalaev/highlight.js) to add syntax highlighting to code blocks contained within. ### Behavior The Markdown viewer parses the first 192KB of raw markdown in the file and renders it using GitHub's Markdown style. Additional content is truncated and a notification along with a download button are appended to the bottom of the preview. The viewer supports GitHub Flavored Markdown including tables, syntax highlighting, and automatic URL linking. Re-sizing the viewer window will reflow the markdown to fit the available space. Also, this viewer supports printing and will attempt to print the parsed markdown and with syntax highlighting on code when either `print()` is invoked or the print button is pressed. Note that printing large files may cause some browsers to freeze for a few seconds. ### Controls - Fullscreen (can be exited with the escape key) ### Supported File Extensions `md` ### Events The Markdown viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | | printsuccess | An attempt to print triggered successfully | | ## Model3D viewer The `Model3D` viewer renders previews of 3D model files and allows you to enable different rendering modes to inspect various aspects of the model. for example wireframe, texture coordinates, and more. Animation data is also supported for files that contain it (for example `box3d`, `fbx`, `dae`). ### Behavior The `Model3D` viewer gives you an interactive view of the model. The left mouse button allows you to orbit about the model (single touch on touch-enabled device). Double-clicking somewhere on the model allows you to change orbit focus. ### Controls - Zoom (change distance to the model) with the mouse wheel (or two-finger scroll on a touch-enabled device). - Pan (lateral movement) with the right mouse button (or three-finger swipe on a touch-enabled device). - Animation Selection: If the model that is being viewed contains animations, two animation buttons will be visible in the toolbar. The first allows you to play and pause the animation and the second allows the selection of the current animation. - VR button: If using a browser that supports WebVR and a suitable VR device is attached to your computer, the VR button will allow toggling in and out of VR mode. ### Settings Settings are available through the cog icon in the preview toolbar. - Render Mode: Lit, Unlit, Normal, Shape, UV Overlay - Toggle Wireframe - Toggle Skeleton - Camera Projection: Perspective, Orthographic - Render Quality: Auto, Full - Rotate Model: X, Y, Z ## Box3D Packages Preview gives users the ability to view a single file within Box so, by default, you can't view textures on your model. However, the Box web application gives users the ability to create a Box3D package that combines all dependent files into a single file that can be shared and previewed. To do this, right-click the model file within Box and choose "Create 3D Package". All referenced files found within Box will be included in the resulting package. ### Supported File Extensions `box3d`, `fbx`, `dae`, `3ds`, `obj`, `stl`, `ply` ### Events The `Model3D` viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | ## 360 Image viewer The 360 image viewer renders a preview of an image stored as an equirectangular projection (often taken with a 360 camera). ### Behavior This viewer gives you an interactive view of a 360 degree image. First, a low resolution version of the image is loaded to give a quick view before the full resolution image is finished loading. Clicking and dragging with the left mouse button will change the view direction (single touch and drag on touch-enabled device). ### Controls - Fullscreen (can be exited with the escape key) - VR Button: When using a browser that supports WebVR and a suitable VR device is attached to your computer, a VR button will be available to allow toggling in and out of VR mode. ### Limitations Currently, this previewer requires that the file be named with a '.360' preceding the file extension. This is so that Preview SDK knows to run this viewer rather than the standard image viewer. ### Supported File Extensions `360.jpg`, `360.jpeg`, `360.png`, `360.ai`, `360.bmp`, `360.dcm`, `360.eps`, `360.gif`, `360.ps`, `360.psd`, `360.svg`, `360.svs`, `360.tga`, `360.tif`, `360.tiff` ### Events The 360 image viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | ## Image viewer The image viewer renders previews of image files. ### Behavior Rotating the viewer will rotate the image 90 degrees clockwise. At the default zoom level, clicking on the image will zoom in once. When zoomed in, clicking on the document will return to the default zoom level. When zoomed out, clicking on the document will zoom in until the original zoom level is reached. ### Controls - Zoom In - Zoom Out - Rotate - Fullscreen: can be exited with the escape key ### Supported File Extensions `ai`, `bmp`, `dcm`, `eps`, `idml`, `indt`, `indd`, `inx`, `gif`, `png`, `ps`, `psd`, `svs`, `tga` ### Options | Option | Type | Description | | --- | --- | --- | | annotations | boolean | Optional. Whether annotations on content are shown. Defaults to false | ### Events The image viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | | zoom | The preview zooms in or out | 1. {number} zoom: new zoom value | | | | 2. {boolean} canZoomIn: true if the viewer can zoom in more | | | | 3. {boolean} canZoomOut: true if the viewer can zoom out more | | pan | The preview is panning | | | panstart | Panning starts | | | panend | Panning ends | | | rotate | The image rotates | | | printsuccess | An attempt to print triggered successfully | | ## Multi-image viewer The multi-image viewer renders previews of multi-image files (`tiff`, `tif`). ### Behavior At the default zoom level, clicking on the image will zoom in once. When zoomed in, clicking on the document will return to the default zoom level. When zoomed out, clicking on the document will zoom in until the original zoom level is reached. ### Controls - Zoom In - Zoom Out - Fullscreen: can be exited with the escape key - Set Page: either with the up and down arrows, or by clicking the page number and entering text ### Supported File Extensions `tif`, `tiff` ### Options | Option | Type | Description | | --- | --- | --- | | annotations | boolean | Optional. Whether annotations on content are shown. Defaults to false | ### Events The image viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | | zoom | The preview zooms in or out | 1. {number} zoom: new zoom value | | | | 2. {boolean} canZoomIn: true if the viewer can zoom in more | | | | 3. {boolean} canZoomOut: true if the viewer can zoom out more | | pagefocus | A page is visible | {number} page number of focused page | | pan | The preview is panning | | | panstart | Panning starts | | | panend | Panning ends | | ### Methods The following methods are available for the multi-page image viewer. | Method Name | Explanation | Method Parameters | | --- | --- | --- | | zoom | Zooms the image | {string} 'in', 'out', or 'reset' | | previousPage | Navigates to the previous page | | | nextPage | Navigates to the next page | | | setPage | Navigates to a given page | {number} page number | | toggleFullscreen | Toggles full screen mode | | ## Document viewer The document viewer renders previews for a variety of document types. ### Behavior The document viewer remembers which page you were viewing upon closing the preview. The next time that file is opened, you will immediately be brought to that page. Resizing the viewer window will cause the document to resize. ### Controls - Zoom In - Zoom Out - Set Page: either with the up and down arrows, or by clicking the page number and entering text - Fullscreen (can be exited with the escape key) ### Supported File Extensions `as`, `as3`, `asm`, `bat`, `c`, `cc`, `cmake`, `cpp`, `cs`, `css`, `csv`, `cxx`, `diff`, `doc`, `docx`, `erb`, `gdoc`, `groovy`, `gsheet`, `h`, `haml`, `hh`, `htm`, `html`, `java`, `js`, `less`, `log`, `m`, `make`, `md`, `ml`, `mm`, `msg`, `odp`, `ods`, `odt`, `pdf`, `php`, `pl`, `plist`, `ppt`, `pptx`, `properties`, `py`, `rb`, `rst`, `rtf`, `sass`, `scala`, `scm`, `script`, `sh`, `sml`, `sql`, `tsv`, `txt`, `vi`, `vim`, `webdoc`, `wpd`, `xhtml`, `xls`, `xlsm`, `xlsx`, `xml`, `xsd`, `xsl`, `yaml` ### Options | Option | Type | Description | | --- | --- | --- | | annotations | boolean | Optional. Whether annotations on content are shown. Defaults to false | ### Events The document viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | | zoom | The preview zooms in or out | 1. {number} newScale: new zoom value | | | | 2. {boolean} canZoomIn: true if the viewer can zoom in more | | | | 3. {boolean} canZoomOut: true if the viewer can zoom out more | | pagerender | A page is rendered | {number} page number of rendered page | | pagefocus | A page is visible | {number} page number of focused page | | scrollstart | The viewer starts to scroll | 1. {number} scrollTop: number of pixels scrolled from top of viewport | | | | 2. {number} scrollLeft: number of pixels scrolled from left of viewport | | scrollend | The viewer stops scrolling | 1. {number} scrollTop: number of pixels scrolled from top of viewport | | | | 2. {number} scrollLeft: number of pixels scrolled from left of viewport | | printsuccess | An attempt to print triggered successfully | | | printsuccess | An attempt to print failed | | ### Annotations | Event Name | Explanation | Event Data | | --- | --- | --- | | annotationdraw | Text is highlighted | | | annotationcommentpending | User hovers back into a dialog that has a pending comment | | | annotationcreate | Annotation is created | | | annotationcancel | An annotation was started but then abandoned before it was created | | | annotationdelete | Annotation with provided AnnotationID is deleted. If no ID is provided, deletes the first (and only remaining) annotation in the thread. | | ## <iframe> viewer The `<iframe>` viewer embeds an frame to show content rendered from an external source. ### Behavior The `<iframe>` viewer is used for previews of Box Notes. Box Notes has full-featured viewers within the main Box Web Application, but these full viewers are not initialized when users navigate from previews of other files that may be in the same directory as the Notes files. In this situation, the `<iframe>` viewer embeds an view-only render of the Box Note file. ### Supported File Extensions `boxnote` ### Events The `<iframe>` viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | ## DASH viewer The DASH viewer renders previews for video files using [`Shaka Player`](https://github.com/google/shaka-player). ### Behavior The DASH viewer uses a black background to create a more native viewing experience. Video is streamed in chunks of bytes at an initial quality determined automatically. Volume can be muted or unmuted by clicking the volume icon, or changed by dragging the volume scrubber. The position of the video can be changed by clicking or dragging the playback scrubber. ### Controls - Play/Pause - Volume - Settings - Fullscreen (can be exited with the escape key) ### Settings Settings are available through the cog icon in the preview toolbar. - Video Speed: `0.25`, `0.5`, normal (`1`), `1.25`, `1.5`, `2.0` - Video Quality: `480p`, `1080p`, `auto` ### Supported File Extensions `3g2`, `3gp`, `avi`, `m2v`, `m2ts`, `m4v`, `mkv`, `mov`, `mp4`, `mpeg`, `mpg`, `ogg`, `mts`, `qt`, `wmv` ### Events The DASH viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | | speedchange | The media speed changes | {string} playback speed | | qualitychange | The video quality changes | {string} media quality | | bandwidthhistory | Gives bandwidth history when the preview is destroyed | {array} bandwidth information | | switchhistory | Gives quality switching history when the preview is destroyed | {array} quality switch objects | | adaptation | Quality adapts to a change in bandwidth | {number} bandwidth | | play | The video plays | | | pause | The video pauses | | | seek | The video skips to a time | {number} time | ## CSV viewer The CSV viewer uses [`PapaParse`](https://github.com/mholt/PapaParse) to parse CSV and TSV files and [`React Virtualized`](https://github.com/bvaughn/react-virtualized) to display the parsed data in a table. ### Behavior Resizing the viewer window will cause the table to resize, and the zoom in and out buttons will increase and decrease font size respectively. Currently, column and row sizes are fixed and overflowing text will be truncated. This viewer does not support printing. ### Controls - Zoom In - Zoom Out - Fullscreen (can be exited with the escape key) ### Supported File Extensions `csv`, `tsv` ### Events The CSV viewer triggers the following events. | Event Name | Explanation | Event Data | | --- | --- | --- | | destroy | The preview is intentionally destroyed | | | load | The preview loads | 1. {string} error (optional): error message | | | | 2. {object} file: current file | | | | 3. {object} metrics: information from the logger | | | | 4. {object} viewer: current viewer | | notification | A notification is displayed | | | navigate | The preview is shown for a given index | {object} file | | reload | The preview reloads | | | resize | The preview resizes | 1. {number} height: window height | | | | 2. {number} width: window width | | zoom | The preview zooms in or out | 1. {number} zoom: new zoom value | | | | 2. {boolean} canZoomIn: true if the viewer can zoom in more | | | | 3. {boolean} canZoomOut: true if the viewer can zoom out more | **Reference:** https://developer.box.com/guides/embed/ui-elements/viewers-and-events/ --- ## Untitled *Type: guide | Category: Folders * Create Folder To create a folder in Box you will need to provide our API with a name for the new folder, as well as the id of the parent… # Create Folder To create a folder in Box you will need to provide our API with a `name` for the new folder, as well as the `id` of the `parent` folder that you would like to create the new folder within. # Name restrictions There are some restrictions to the folder name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), as well as names with trailing spaces are prohibited. Additionally, the names `.` and `..` are reserved names and therefore also prohibited. **Reference:** https://developer.box.com/guides/folders/single/create/ --- ## Untitled *Type: guide | Category: Folders * Bulk Manipulation The following pages discuss how to do various bulk methods to folders. # Bulk Manipulation The following pages discuss how to do various bulk methods to folders. **Reference:** https://developer.box.com/guides/folders/bulk/ --- ## Untitled *Type: guide | Category: Folders * Create Folder Lock To create a lock on a folder in Box you will need to provide our API with the id of the folder for which the lock should… # Create Folder Lock To create a lock on a folder in Box you will need to provide our API with the `id` of the folder for which the lock should be applied. Optionally you may supply the specific `locked_operations` to be applied with the folder lock. # Folder Locks When using any folder lock API endpoints, you must be authenticated as the owner/co-owner of the folder you are trying to access. # Setting Locked Operations If the `locked_operations` object is included with a folder lock request, both `move` and `delete` need to be set to `true`. Supplying only one lock operation in the object, or setting the values of both to something other than `true` will produce an error. These options are in place to allow for additional operations in the future. ## Lock Operations There are two possible lock operations that may be applied to a folder, `move` and `delete`. The `move` lock will prevent the folder from being moved to a new location or owner while the lock is still applied. The `delete` lock will prevent the folder from being deleted while the lock is still applied. **Reference:** https://developer.box.com/guides/folders/single/create-lock/ --- ## Untitled *Type: guide | Category: Folders * Copy Folder Creates a copy of a folder within a destination folder. The original folder will not be changed. To copy a folder in Box you… # Copy Folder Creates a copy of a folder within a destination folder. The original folder will not be changed. To copy a folder in Box you will need to provide our API with the `id` of the `parent` folder that you would like to copy the folder into. Optionally, you can provide a different name for the new folder. # Name restrictions There are some restrictions to the folder name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), as well as names with trailing spaces are prohibited. Additionally, the names `.` and `..` are reserved names and therefore also prohibited. ## Asynchronous copying If the folder being copied contains up to 500 items the copy will happen synchronously with the API call. The call will not return until the copy operation has completed. If the folder contains more than 500 items the copy operation will be run asynchronously and the API call will return directly yet before the copy operation has completed. We currently have no API to check when a copy operation has finished. ## Folder locking During this operation, part of the file tree will be locked, mainly the source folder and all of its descendants, as well as the destination folder. For the duration of the operation, no other move, copy, delete, or restore operation can performed on any of the locked folders. Most importantly, this means that the same folder can not be copied to two different parts of the folder tree at the same time. ## Metadata If the destination folder has a metadata cascade policy attached to any of the parent folders a metadata cascade operation will be kicked off asynchronously. We currently have no API to check when this operation has finished. **Reference:** https://developer.box.com/guides/folders/single/copy/ --- ## Untitled *Type: guide | Category: Folders * Delete Folder Lock To remove a lock applied to a folder in Box, call the DELETE /folder_locks/:id API with the id of the folder lock. Folder… # Delete Folder Lock To remove a lock applied to a folder in Box, call the `DELETE /folder_locks/:id` API with the id of the folder lock. # Folder Locks When using any folder lock API endpoints, you must be authenticated as the owner/co-owner of the folder you are trying to access. # Locating the folder Lock ID To delete a folder lock you must supply the folder lock ID to the API. A folder lock ID is supplied in the response when [creating a folder lock](g://folders/single/create-lock), or when [listing locks](g://folders/single/get-locks) on a given folder. **Reference:** https://developer.box.com/guides/folders/single/delete-lock/ --- ## Untitled *Type: guide | Category: Folders * Delete Folder To remove a folder in Box you will need to provide our API with the ID of the folder. Deleting non-empty folders This API… # Delete Folder To remove a folder in Box you will need to provide our API with the ID of the folder. ## Deleting non-empty folders This API returns an error if the folder is not empty. When deleting a folder, you can pass in the `recursive` parameter to force a folder to be deleted even if it is not empty. This will delete all items within this folder, including any of their descendants. ## Folder locking The enterprise settings determine whether the folder will be permanently deleted from Box or moved to the trash. During this operation, part of the file tree will be locked, mainly the source folder and all of its descendants. For the duration of the operation, no other move, copy, delete, or restore operation can performed on any of the locked folders. ## Timeout Timeout for this operation is 60 seconds. The operation will include after a `HTTP 503` has been returned. **Reference:** https://developer.box.com/guides/folders/single/delete/ --- ## Untitled *Type: guide | Category: Folders * Get Folder Lock To get a list of the current locks on a folder in Box, call the GET /folder_locks/ API with the id of the folder supplied as… # Get Folder Lock To get a list of the current locks on a folder in Box, call the `GET /folder_locks/` API with the id of the folder supplied as a `folder_id` query string parameter. # Folder Locks When using any folder lock API endpoints, you must be authenticated as the owner/co-owner of the folder you are trying to access. ## Folder ID The `id` of any folder can be determined by visiting a folder in the web application and copying the `id` from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. **Reference:** https://developer.box.com/guides/folders/single/get-locks/ --- ## Untitled *Type: guide | Category: Folders * Single Folders The following pages discuss how to do various single folder methods. # Single Folders The following pages discuss how to do various single folder methods. **Reference:** https://developer.box.com/guides/folders/single/ --- ## Untitled *Type: guide | Category: Folders * Move Folder To move a folder, update the ID of its parent folder. Operation details This call will return synchronously. This holds true… # Move Folder To move a folder, update the ID of its parent folder. ## Operation details This call will return synchronously. This holds true even for folder moves when the folder contains a large number of items in all of its descendants. For very large folders, this means the call could take minutes or hours to complete and some parts of the tree are locked during moves. When moving a folder, part of the file tree will be locked, mainly the source folder and all of its descendants, as well as the destination folder. For the duration of the move you cannot perform other move, copy, delete, or restore operation on any of the locked folders. ## Moving a subfolder to a private folder When you attempt to move a collaborated subfolder to a private one, you will get the [`cannot_make_collaborated_subfolder_private`](../../api-calls/permissions-and-errors/common-errors.md#400-bad-request) error. In such a case, specify the ID of the user that folder belongs to setting the `owned_by.id` parameter in the request: **Reference:** https://developer.box.com/guides/folders/single/move/ --- ## Untitled *Type: guide | Category: Folders * Update Folder To update a folder in Box you will need to call the following API. Name restrictions There are some restrictions to the folder… # Update Folder To update a folder in Box you will need to call the following API. ## Name restrictions There are some restrictions to the folder name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), as well as names with trailing spaces are prohibited. Additionally, the names `.` and `..` are reserved names and therefore also prohibited. ## Timeout Timeout for this operation is 60 seconds. The operation will complete after a `HTTP 503` has been returned. **Reference:** https://developer.box.com/guides/folders/single/update/ --- ## Untitled *Type: guide | Category: Folders * Rename Folder To rename a folder in Box you will need to provide our API with a new name for the folder. Name restrictions There are some… # Rename Folder To rename a folder in Box you will need to provide our API with a new `name` for the folder. # Name restrictions There are some restrictions to the folder name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), as well as names with trailing spaces are prohibited. Additionally, the names `.` and `..` are reserved names and therefore also prohibited. **Reference:** https://developer.box.com/guides/folders/single/rename/ --- ## Untitled *Type: guide | Category: Integration Mappings * Delete Slack Integration Mapping The DELETE integration_mappings/slack/:integration_mapping_id call removes the mapping between the channel… # Delete Slack Integration Mapping The `DELETE integration_mappings/slack/:integration_mapping_id` call removes the mapping between the channel and the folder. A new mapping and a new folder in the default folder structure will be created when the next file is uploaded to the channel. Deleting the mapping does not delete the Box folder, or the Slack channel. **Reference:** https://developer.box.com/guides/integration-mappings/slack-mappings/delete-mapping/ --- ## Untitled *Type: guide | Category: Integration Mappings * Create Slack Integration Mapping Use the POST integration_mappings/slack/:integration_mapping_id call to create a mapping. To make it work… # Create Slack Integration Mapping Use the `POST integration_mappings/slack/:integration_mapping_id` call to create a mapping. To make it work, you need `box_item` and `partner_item` parameters, which refer to a Box folder and a Slack channel, respectively. Remember that before the mapping can be created, this service account must be set as a co-owner role on the folder that is being mapped. If you encounter any errors, see the [troubleshooting guide](g://integration-mappings/slack-mappings/troubleshooting). You can provide options that change the default settings for the created mapping. For example setting `is_access_management_disabled` to `true` will disable collaboration management. Slack channel members will not become collaborators on the channel folder and no shared links will be created for channels with 1000+ members. ## Create Slack Integration Mapping with Box SDK Use Box SDK to automatically create the Integration Mapping, including a co-owner collaboration of the service account on the Slack channel - Box folder mapping. To do so, use this script: ``` const BoxSDK = require('box-node-sdk'); const axios = require('axios'); const integrationMappingsApiUrl = 'https://api.box.com/2.0/integration_mappings/slack' const boxFolderId = 'PASTE YOUR FOLDER ID HERE'; const slackChannelId = 'PASTE YOUR CHANNEL ID HERE'; const slackOrgId = 'PASTE YOUR SLACK ORG ID HERE (CHANGE TO WORKSPACE ID IF NECESSARY)'; const developerToken = 'PASTE YOUR DEVELOPER TOKEN HERE'; let serviceAccountId = '<PLACEHOLDER>'; const client = BoxSDK.getBasicClient(developerToken); async function postIntegrationMappingSlack(){ return axios.post(integrationMappingsApiUrl, { partner_item: { id: slackChannelId, slack_org_id: slackOrgId, // change slack_org_id to slack_workspace_id if Box for Slack is installed on the workspace level type: "channel" }, box_item: { id: boxFolderId, type: "folder" } }, { headers: { 'Authorization': `Bearer ${developerToken}` } }); } function isPlaceholder(str){ return str === '<PLACEHOLDER>'; } async function addCoowner(serviceAccountId, folderId){ try { await client.collaborations.createWithUserID(serviceAccountId, folderId, 'co-owner') } catch (error){ if(error.response.body.code === 'user_already_collaborator'){ console.log('Service account already collaborated in the co-owner role.') } else { throw error; } } } async function logServiceAccountId() { try { await postIntegrationMappingSlack(); } catch (error) { console.log(`Replace the value of serviceAccountId with: ${error.response.data.context_info.service_account_id} and re-run the script.`) } } async function createSlackIntegrationMapping() { if(isPlaceholder(serviceAccountId)){ await logServiceAccountId(); } else { await addCoowner(serviceAccountId, boxFolderId); await postIntegrationMappingSlack(); } } module.exports = { createSlackIntegrationMapping } ``` Make sure to replace `PLACEHOLDER` with the logged value of `serviceAccountId`. **Reference:** https://developer.box.com/guides/integration-mappings/slack-mappings/create-mapping/ --- ## Untitled *Type: guide | Category: Integration Mappings * Slack Integration Mappings When Box as the Content Layer is enabled, Box folder is created for each channel, and all files uploaded to this… # Slack Integration Mappings When [Box as the Content Layer](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) is enabled, Box folder is created for each channel, and all files uploaded to this channel are stored in this folder. The [Integration Mappings API](r://integration-mapping) allows the Box Enterprise Admin (EA) to customize the upload folder of the Slack channel to any folder within the enterprise instead of relying on the default one. **Reference:** https://developer.box.com/guides/integration-mappings/slack-mappings/ --- ## Untitled *Type: guide | Category: Integration Mappings * List Slack Integration Mappings Use the GET /integration_mappings/slack call to fetch and filter the mappings, both the ones created… # List Slack Integration Mappings Use the `GET /integration_mappings/slack` call to fetch and filter the mappings, both the ones created manually by the admin those created automatically by the integration. **Reference:** https://developer.box.com/guides/integration-mappings/slack-mappings/list-mappings/ --- ## Untitled *Type: guide | Category: Integration Mappings * Slack Integration Mappings Setup Before starting work with Integration Mappings API, perform the following steps. Roles Make sure you have… # Slack Integration Mappings Setup Before starting work with Integration Mappings API, perform the following steps. ## Roles Make sure you have an Admin or a Co-admin role. ## Install and configure Box for Slack 1. Install [Box for Slack](https://support.box.com/hc/en-us/articles/360044195313-Installing-and-Using-the-Box-for-Slack-Integration) in the relevant Slack workspace or organizations. 2. Enable the [Box as Content Layer for Slack](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). 3. Make sure the service account you are using is a collaborator on the folder that will be mapped. To do so, use the `Invite People` folder option to invite the service account as a collaborator. If you encounter any errors, see the [troubleshooting guide](g://integration-mappings/slack-mappings/troubleshooting). ## Create Box application 1. Create a [platform app with OAuth authentication](g://authentication/oauth2/oauth2-setup) in the [Box developer console](https://app.box.com/developers/console) 2. Open the application and enable the **Manage enterprise properties** application scope under **Configuration** > **Required Access Scopes**. For Slack-side channel validation, the [Integration Mappings API](e://get-integration-mappings-slack) is calling the Slack API. ## Authorization To authorize your Integration Mappings requests: 1. Navigate to the [platform app](g://applications/app-types/platform-apps) that you have created as one of the prerequisites. 2. Generate a [developer token](g://authentication/tokens/developer-tokens) and add it to the HTTP header of each request: ``` Authorization: Bearer {developer_token} ``` The developer token is valid for 60 minutes. After that time you need to generate it again. **Reference:** https://developer.box.com/guides/integration-mappings/slack-mappings/setup/ --- ## Untitled *Type: guide | Category: Integration Mappings * Slack Integration Mappings Troubleshooting As the Integration Mappings API performs different types of validation, some errors might occur… # Slack Integration Mappings Troubleshooting As the Integration Mappings API performs different types of validation, some errors might occur. You can find descriptions and solutions to these common errors below. ## Service account is not a co-owner of the folder The [Box as Content Layer for Slack](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) service account must be added as an owner or co-owner of the folder to manage collaborations and uploads. ``` Box as File Storage for Slack (user id: 123, user email: user@example.com) must be a collaborator in role co-owner or owner of the folder example123, before it can be mapped to the channel example123. Please create a collaboration or ensure the ownership for Box as File Storage for Slack and retry.` ``` To resolve this error use the data in the response to make sure the service account has the necessary role to perform the mapping. ``` "context_info": { "service_account_id": "12345678", "service_account_email": "AutomationUser_12345678_gdueygwe@boxdevedition.com", } ``` Perform the following steps: 1. Copy the `service_account_email` from `context_info`. 2. In the folder settings, use the `Invite People` option to invite the service account as a co-owner. ## Channel is already mapped to a folder in Box API returns the following error when you attempt to create a mapping for a channel that already has a Box folder mapped: ``` Channel: example123 is already mapped to a folder in Box. ``` If you wanted to start using a new folder, use `GET` to retrieve the `id` of the mapping and then the `UPDATE` method to update the target Box folder. ## Channel was not found API returns this error if the Slack bot associated with the integration can not retrieve information about the channel. ``` Channel: example123 was not found. If it is a private channel, ensure that Box has been added to the channel. ``` Ensure that the `partner_item` is correct - make sure you provide `slack_org_id` for org installations and `slack_workspace_id` for workspace ones. If the channel is private, ensure that the Slack bot has been added to the channel. ## Channel not suitable for Custom File Storage (CFS) ``` Channel: example123 is not suitable for CFS. Slack Connect channels with a pending Connect status can not be mapped to Box folders. ``` Slack Connect channels (cross enterprise channels) are currently not supported as a part of Box as a Content Layer for Slack. ## Box folder externally owned Box folder selected for mapping must be owned by the enterprise that the Admin is part of. ``` Box folder: example123 cannot be mapped, because it is externally owned. Mapped folder must belong to the enterprise: example_enterprise. ``` ## Custom File Storage (CFS) turned off API returns this error when you're trying to create the mapping for an enterprise that has Box for Slack installed, but did not enable [Box as a Content Layer for Slack](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). ## Box enterprise mismatch API returns this error when there is a mismatch between the Admin’s enterprise and Box for Slack configuration. See [Installing and using Box for Slack](https://support.box.com/hc/en-us/articles/360044195313-Installing-and-Using-the-Box-for-Slack-Integration) for information on how to enable Box for Slack. **Reference:** https://developer.box.com/guides/integration-mappings/slack-mappings/troubleshooting/ --- ## Untitled *Type: guide | Category: Integration Mappings * Delete Teams integration mappings The DELETE integration_mappings_teams_id call removes the mapping between the channel and the folder. A… # Delete Teams integration mappings The `DELETE integration_mappings_teams_id` call removes the mapping between the channel and the folder. A new mapping and a new folder in the default folder structure will be created when the next file is uploaded to the channel. Deleting the mapping does not delete the Box folder or the Teams channel. **Reference:** https://developer.box.com/guides/integration-mappings/teams-mappings/delete-mappings/ --- ## Untitled *Type: guide | Category: Integration Mappings * Create Teams integration mappings Use the POST integration_mappings_teams call to create a mapping. To make it work, you need the box_item… # Create Teams integration mappings Use the `POST integration_mappings_teams` call to create a mapping. To make it work, you need the `box_item` and the `partner_item` parameters, which refer to a Box folder and a Teams channel, respectively. **Reference:** https://developer.box.com/guides/integration-mappings/teams-mappings/create-mappings/ --- ## Untitled *Type: guide | Category: Integration Mappings * Update Slack Integration Mapping Use the PUT integration_mappings/slack/:integration_mapping_id call to update the existing mapping or the… # Update Slack Integration Mapping Use the `PUT integration_mappings/slack/:integration_mapping_id` call to update the existing mapping or the target Box folder. **Reference:** https://developer.box.com/guides/integration-mappings/slack-mappings/update-mapping/ --- ## Untitled *Type: guide | Category: Integration Mappings * List Teams integration mappings Use the GET /integration_mappings/teams call to fetch and filter the mappings, both the ones created… # List Teams integration mappings Use the `GET /integration_mappings/teams` call to fetch and filter the mappings, both the ones created manually by the admin and those created automatically by the integration. **Reference:** https://developer.box.com/guides/integration-mappings/teams-mappings/list-mappings/ --- ## Untitled *Type: guide | Category: Integration Mappings * Teams integration mappings Before you can start working with Teams integration mapping API, perform the steps below. Prerequisites Admin or… # Teams integration mappings Before you can start working with [Teams](https://support.box.com/hc/en-us/articles/360044667034-Introducing-Box-for-Microsoft-Teams) integration mapping API, perform the steps below. ## Prerequisites - Admin or Co-Admin role - [Box for Microsoft Teams](https://support.box.com/hc/en-us/articles/360050737154-Assigning-a-Default-Box-Folder-to-a-Teams-Channel-or-Chat) integration installed ## Create a Box application 1. Create a [platform app with OAuth authentication](g://authentication/oauth2/oauth2-setup) in the [Box developer console](https://app.box.com/developers/console). 2. Open the application and enable the **Manage enterprise properties** application scope under **Configuration** > **Required Access Scopes**. ## Authorize integration mappings requests 1. Navigate to the [platform app](g://applications/app-types/platform-apps) that you have created as one of the prerequisites. 2. Generate a [developer token](g://authentication/tokens/developer-tokens) and add it to the HTTP header of each request: ``` Authorization: Bearer {developer_token} ``` The developer token is valid for 60 minutes. After that time, you need to generate it again. **Reference:** https://developer.box.com/guides/integration-mappings/teams-mappings/ --- ## Untitled *Type: guide | Category: Integration Mappings * Update Teams integration mappings Use the PUT integration_mappings_teams_id call to update the existing mapping of the target Box folder. # Update Teams integration mappings Use the `PUT integration_mappings_teams_id` call to update the existing mapping of the target Box folder. **Reference:** https://developer.box.com/guides/integration-mappings/teams-mappings/update-mappings/ --- ## Untitled *Type: guide | Category: Metadata * Create a metadata cascade policy When a metadata template has been applied to a folder, a metadata cascade policy can be created by calling… # Create a metadata cascade policy When a metadata template has been applied to a folder, a metadata cascade policy can be created by calling the [`POST /metadata_cascade_policies`](e://post_metadata_cascade_policies) API endpoint with the `folder_id` of the folder to apply the policy to, and the `scope` and `templateKey` of metadata template to. To get the `scope` and `templateKey` for a template, either [list all metadata templates](g://metadata/templates/list), or [list all instances on an file](g://metadata/instances/list). A cascade policy can only be created if a metadata instance has already been applied to the folder with the given `scope` and `templateKey`. **Reference:** https://developer.box.com/guides/metadata/cascades/create/ --- ## Untitled *Type: guide | Category: Metadata * Delete a metadata cascade policy A metadata cascade policy can be deleted by calling the DELETE /metadata_cascade_policies/:id API endpoint… # Delete a metadata cascade policy A metadata cascade policy can be deleted by calling the [`DELETE /metadata_cascade_policies/:id`](e://delete_metadata_cascade_policies_id) API endpoint with the `id` of the policy to remove. To get the `id` of the policy, [list all policies](g://metadata/cascades/list) for the folder. **Reference:** https://developer.box.com/guides/metadata/cascades/delete/ --- ## Untitled *Type: guide | Category: Metadata * Get a metadata cascade policy Information for a metadata cascade policy can be retrieved by calling the GET /metadata_cascade_policies/:id… # Get a metadata cascade policy Information for a metadata cascade policy can be retrieved by calling the [`GET /metadata_cascade_policies/:id`](e://get_metadata_cascade_policies_id) API endpoint with the `id` of the policy. To get the `id` of the policy, [list all policies](g://metadata/cascades/list) for the folder. **Reference:** https://developer.box.com/guides/metadata/cascades/get/ --- ## Untitled *Type: guide | Category: Metadata * Force-apply metadata to all items in a folder When a metadata cascade policy already exists on a folder, the metadata instance can be force… # Force-apply metadata to all items in a folder When a metadata cascade policy already exists on a folder, the metadata instance can be force-applied to all items in a folder by calling the [`POST /metadata_cascade_policies/:id/apply`](e://post_metadata_cascade_policies_id_apply) API endpoint with the `id` of the metadata cascade policy. To get the `id` of the policy, [list all policies](g://metadata/cascades/list) for the folder. The metadata cascade operation will be started off asynchronously. The API call will return directly with the `202 Accepted` HTTP status code before the cascade operation is complete. There is currently no way to check for when this operation is finished. ## Conflict resolution An additional `conflict_resolution` parameter can be passed to this API to define how to deal with any existing instances of the template on any of the items in the folder. By default, without setting any value for `conflict_resolution` this API will preserve the existing value on any items. When the value is set to `overwrite`, it will force-apply the value of the template attached to the cascade policy over any existing value. **Reference:** https://developer.box.com/guides/metadata/cascades/force-apply/ --- ## Untitled *Type: guide | Category: Metadata * Metadata cascade policies A metadata cascade policy describes how metadata instances applied to a folder should be applied to any item… # Metadata cascade policies A metadata cascade policy describes how metadata instances applied to a folder should be applied to any item within that folder. For example, a user might assign the same `invoiceData` metadata template to a project folder allowing it to automatically apply to all the files and folders within that project folder. Every policy specifies exactly one metadata template instance and one folder. ## Activation and permissions To use metadata cascade policies, an enterprise admin needs to enable them for the entire enterprise. In the **Admin Console**, select **Enterprise Settings**, **Content & Sharing**, **Cascading Folder Level Metadata**. Click the Edit configuration button and pick who can apply cascade policies to folders. Any user with edit permissions on a folder and the ability to create cascade policies can create metadata cascade policies for that given folder. ## Limitations There is some delay from file upload to the metadata being applied. This very much depends on the number of items in a folder. Metadata cascade operations are performed asynchronously and there is currently no way to check when all metadata has been cascaded to all files. **Reference:** https://developer.box.com/guides/metadata/cascades/ --- ## Untitled *Type: guide | Category: Metadata * Date metadata field A metadata field of type date is displayed to a user as a date picker. Although dates are presented to users in the Box… # Date metadata field A metadata field of type `date` is displayed to a user as a date picker. Although dates are presented to users in the Box Web app as date-pickers, the actual dates are actually stored as in `RFC3339` format, with up to millisecond precision. The time part of the date is always set to `T00:00:00.000Z`. ## Create a date field A `date` field can be added to a metadata template either when creating a metadata template, or when updating a template with the `addField` operation. The required attributes for a `date` field are a `type`, a `displayName`, and a `key`. ``` { "scope": "enterprise", "displayName": "Contract", "fields": [ { "type": "date", "key": "effective_date", "displayName": "Effective Date", "description": "The effective date when the contract goes in effect", "hidden": false } ] } ``` Optionally, a `description` can be provided that is shown to a user in the UI, and the field can be set to `hidden` to hide it from users in the web and mobile apps. ## Update a date field A `date` template field can be updated by updating the template it belongs to. Updates to templates happen through **operations** to ensure that any template that is already assigned to a file or folder is updated as well. When updating a `date` metadata field, the only relevant operation is the `editField` operation, which can be used to change the field's `key`, `displayName`, `description`, and `hidden` values. ``` [ { "op": "editField", "fieldKey": "effective_date", "data": { "displayName": "Effective Contract Date", "description": "The contract's effective date", "key": "effective_contract_date", "hidden": true } } ] ``` This will affect existing instances of this template. **Reference:** https://developer.box.com/guides/metadata/fields/date/ --- ## Untitled *Type: guide | Category: Metadata * List metadata cascade policies Metadata cascade policies can be listed for a folder by calling the GET /metadata_cascade_policies API… # List metadata cascade policies Metadata cascade policies can be listed for a folder by calling the [`GET /metadata_cascade_policies`](e://get_metadata_cascade_policies) API endpoint with a `folder_id`. ## Pagination This API uses [marker-based pagination](g://api-calls/pagination/marker-based) and can return a `next_marker` value in the response body to indicate that more templates might be available. **Reference:** https://developer.box.com/guides/metadata/cascades/list/ --- ## Untitled *Type: guide | Category: Metadata * Enum metadata field A metadata field of type enum is displayed to a user as a dropdown list. The user can select one item from the list. An… # Enum metadata field A metadata field of type `enum` is displayed to a user as a dropdown list. The user can select one item from the list. An `enum` allows a user to select zero or a single value. To allow a user to select multiple values, use the [`multiSelect`](g://metadata/fields/multi-select) template field. ## Create an enum field An `enum` field can be added to a metadata template either when creating a metadata template, or when updating a template with the `addField` operation. The required attributes for an `enum` field are a `type`, a `displayName`, a `key`, and a list of options. ``` { "scope": "enterprise", "displayName": "Contract", "fields": [ { "type": "enum", "key": "customer_state", "displayName": "Customer State", "description": "The US state where the customer is located", "hidden": false, "options": [ {"key": "N/A"}, {"key": "AL"}, {"key": "AK"} ] } ] } ``` Optionally, a `description` can be provided that is shown to a user in the UI, and the field can be set to `hidden` to hide it from users in the web and mobile apps. ## Update an enum field An `enum` template field can be updated by updating the template it belongs to. Updates to templates happen through **operations** to ensure that any template that is already assigned to a file or folder is updated as well. ### Change basic field values When updating an `enum` metadata field, one of the possible operations is the `editField` operation, which can be used to change the field's `key`, `displayName`, `description`, and `hidden` values. ``` [ { "op": "editField", "fieldKey": "customer_state", "data": { "displayName": "Customer State (USA)", "key": "customer_state_usa" } } ] ``` The `fieldKey` here represents the original key of the field to change. The `data.key` field is the new key of the field. This will affect existing instances of this template. ### Add an option Adding an option to an `enum` field can be achieved through the `addEnumOption` operation. The operation expects the `fieldKey` to be set to the key of the `enum` field to change, and a `data` object with the `key` of the new option to add. ``` [ { "op": "addEnumOption", "fieldKey": "customer_state", "data": { "key": "AR" } } ] ``` The list of options should now be as follows. ``` ... "options": [ {"key": "N/A"}, {"key": "AL"}, {"key": "AK"}, {"key": "AR"} ] ... ``` This will affect existing instances of this template. ### Reorder options Reordering the options in an `enum` field can be achieved through the `reorderEnumOptions` operation. The operation expects the `fieldKey` to be set to the key of the `enum` field to change, and an `enumOptionKeys` array with the keys of the options in order. ``` [ { "op": "reorderEnumOptions", "fieldKey": "customer_state", "enumOptionKeys": [ "AL", "AK", "AR", "N/A" ] } ] ``` The list of options should now be as follows. ``` ... "options": [ {"key": "AL"}, {"key": "AK"}, {"key": "AR"}, {"key": "N/A"} ] ... ``` New options can not be added with this operation. This will affect existing instances of this template. ### Edit an option Editing an option of an `enum` field can be achieved through the `editEnumOption` operation. The operation expects the `fieldKey` to be set to the key of the `enum` field to change, and an `enumOptionKey` to be set to the key of the field option. Finally, it expects a `data` object with the new `key` of the field option. ``` [ { "op": "editEnumOption", "fieldKey": "customer_state", "enumOptionKey": "N/A", "data": { "key": "Outside USA" } } ] ``` The list of options should now be as follows. ``` ... "options": [ {"key": "AL"}, {"key": "AK"}, {"key": "AR"}, {"key": "Outside USA"} ] ... ``` This will affect existing instances of this template. ### Remove an option Removing an option from an `enum` field can be achieved through the `removeEnumOption` operation. The operation expects the `fieldKey` to be set to the key of the `enum` field to change, and an `enumOptionKey` to be set to the key of the field option to remove. ``` [ { "op": "removeEnumOption", "fieldKey": "customer_state", "enumOptionKey": "AL" } ] ``` The list of options should now be as follows. ``` ... "options": [ {"key": "AK"}, {"key": "AR"}, {"key": "Outside USA"} ] ... ``` This will affect existing instances of this template. Any fields that were set to this value will have the value reset to `null`. **Reference:** https://developer.box.com/guides/metadata/fields/enum/ --- ## Untitled *Type: guide | Category: Metadata * Float metadata field A metadata field of type float is displayed to a user as a standard text-field that only accepts numeric input. Create… # Float metadata field A metadata field of type `float` is displayed to a user as a standard text-field that only accepts numeric input. ## Create a float field A `float` field can be added to a metadata template either when creating a metadata template, or when updating a template with the `addField` operation. The required attributes for a `float` field are a `type`, a `displayName`, and a `key`. ``` { "scope": "enterprise", "displayName": "Contract", "fields": [ { "type": "float", "key": "contract_value", "displayName": "Contract Value", "description": "The contract's total value", "hidden": false } ] } ``` Optionally, a `description` can be provided that is shown to a user in the UI, and the field can be set to `hidden` to hide it from users in the web and mobile apps. ## Update a float field A `float` template field can be updated by updating the template it belongs to. Updates to templates happen through **operations** to ensure that any template that is already assigned to a file or folder is updated as well. When updating a `float` metadata field, the only relevant operation is the `editField` operation, which can be used to change the field's `key`, `displayName`, `description`, and `hidden` values. ``` [ { "op": "editField", "fieldKey": "contract_value", "data": { "displayName": "Total Annual Contract Value", "description": "The contract's total anual value", "key": "contract_tav", "hidden": true } } ] ``` This will affect existing instances of this template. **Reference:** https://developer.box.com/guides/metadata/fields/float/ --- ## Untitled *Type: guide | Category: Metadata * Metadata fields A metadata template field describes a specific piece of data within a metadata template. For example, the ID of an invoice… # Metadata fields A [metadata template field](r://metadata-template/#param-fields) describes a specific piece of data within a metadata template. For example, the ID of an invoice might be represented as an `id` field on an `invoiceData` template. Every metadata template contains a list of `field` objects, and each field is of one of the following types: | | | | --- | --- | | string | A text field | | float | A numeric input field | | date | A date picker field | | enum | A dropdown list for selecting a single value | | multiSelect | A dropdown list for selecting multiple values | ## Basic field types The basic field types are a `string` for a text field, `float` for a numeric field, and `date` for a date-time picker field. ## Lists field types Additionally, metadata templates support two field types to represent dropdown lists. An `enum` field represents a list of predefined items that a user can select, while a `multiSelect` field represents a list of items where the user can select more than one value. **Reference:** https://developer.box.com/guides/metadata/fields/ --- ## Untitled *Type: guide | Category: Metadata * String metadata field A metadata field of type string is displayed to a user as a standard text-field. Create a string field A string field… # String metadata field A metadata field of type `string` is displayed to a user as a standard text-field. ## Create a string field A `string` field can be added to a metadata template either when creating a metadata template, or when updating a template with the `addField` operation. The required attributes for a `string` field are a `type`, a `displayName`, and a `key`. ``` { "scope": "enterprise", "displayName": "Customer", "fields": [ { "type": "string", "key": "name", "displayName": "Name", "description": "The customer's legal name", "hidden": false } ] } ``` Optionally, a `description` can be provided that is shown to a user in the UI, and the field can be set to `hidden` to hide it from users in the web and mobile apps. ## Update a string field A `string` template field can be updated by updating the template it belongs to. Updates to templates happen through **operations** to ensure that any template that is already assigned to a file or folder is updated as well. When updating a `string` metadata field, the only relevant operation is the `editField` operation, which can be used to change the field's `key`, `displayName`, `description`, and `hidden` values. ``` [ { "op": "editField", "fieldKey": "name", "data": { "displayName": "Customer Name", "description": "The contact name at the customer", "key": "customer_name", "hidden": true } } ] ``` This will affect existing instances of this template. **Reference:** https://developer.box.com/guides/metadata/fields/string/ --- ## Untitled *Type: guide | Category: Metadata * Multi Select metadata field A metadata field of type multiSelect is displayed to a user as a dropdown list. The user can select multiple… # Multi Select metadata field A metadata field of type `multiSelect` is displayed to a user as a dropdown list. The user can select multiple items from the list. A `multiSelect` field allows a user to select zero, one, or more values. To force a user to select only one value at most, use the [`enum`](g://metadata/fields/enum) template field. ## Create a multiSelect field A `multiSelect` field can be added to a metadata template either when creating a metadata template, or when updating a template with the `addField` operation. The required attributes for a `multiSelect` field are a `type`, a `displayName`, a `key`, and a list of options. ``` { "scope": "enterprise", "displayName": "Contract", "fields": [ { "type": "multiSelect", "key": "box_entity", "displayName": "Box Entity", "description": "The Box entity that this contract belongs to", "hidden": false, "options": [ {"key": "Box, Inc"}, {"key": "Box.com (UK) Ltd."}, {"key": "KK Box Japan"} ] } ] } ``` Optionally, a `description` can be provided that is shown to a user in the UI, and the field can be set to `hidden` to hide it from users in the web and mobile apps. ## Update a multiSelect field A `multiSelect` template field can be updated by updating the template it belongs to. Updates to templates happen through **operations** to ensure that any template that is already assigned to a file or folder is updated as well. ### Change basic field values When updating a `multiSelect` metadata field, one of the possible operations is the `editField` operation, which can be used to change the field's `key`, `displayName`, `description`, and `hidden` values. ``` [ { "op": "editField", "fieldKey": "box_entity", "data": { "displayName": "Box Entities", "key": "box_entities" } } ] ``` The `fieldKey` here represents the original key of the field to change. The `data.key` field is the new key of the field. This will affect existing instances of this template. ### Add an option Adding an option to a `multiSelect` field can be achieved through the `addMultiSelectOption` operation. The operation expects the `fieldKey` to be set to the key of the `multiSelect` field to change, and a `data` object with the `key` of the new option to add. ``` [ { "op": "addMultiSelectOption", "fieldKey": "box_entity", "data": { "key": "Box (NL) BV" } } ] ``` The list of options should now be as follows. ``` ... "options": [ {"key": "Box, Inc"}, {"key": "Box.com (UK) Ltd."}, {"key": "KK Box Japan"}, {"key": "Box (NL) BV"} ] ... ``` This will affect existing instances of this template. ### Reorder options Reordering the options in a `multiSelect` field can be achieved through the `reorderMultiSelectOptions` operation. The operation expects the `fieldKey` to be set to the key of the `multiSelect` field to change, and a `multiSelectOptionKeys` array with the keys of the options in order. ``` [ { "op": "reorderMultiSelectOptions", "fieldKey": "box_entity", "multiSelectOptionKeys": [ "Box, Inc", "Box.com (UK) Ltd.", "Box (NL) BV", "KK Box Japan" ] } ] ``` The list of options should now be as follows. ``` ... "options": [ {"key": "Box, Inc"}, {"key": "Box.com (UK) Ltd."}, {"key": "Box (NL) BV"}, {"key": "KK Box Japan"} ] ... ``` New options can not be added with this operation. This will affect existing instances of this template. ### Edit an option Editing an option of a `multiSelect` field can be achieved through the `editMultiSelectOption` operation. The operation expects the `fieldKey` to be set to the key of the `multiSelect` field to change, and a `multiSelectOptionKey` to be set to the key of the field option. Finally, it expects a `data` object with the new `key` of the field option. ``` [ { "op": "editMultiSelectOption", "fieldKey": "box_entity", "multiSelectOptionKey": "Box (NL) BV", "data": { "key": "Box.nl BV" } } ] ``` The list of options should now be as follows. ``` ... "options": [ {"key": "Box, Inc"}, {"key": "Box.com (UK) Ltd."}, {"key": "Box.nl BV"}, {"key": "KK Box Japan"} ] ... ``` This will affect existing instances of this template. ### Remove an option Removing an option from a `multiSelect` field can be achieved through the `removeMultiSelectOption` operation. The operation expects the `fieldKey` to be set to the key of the `multiSelect` field to change, and a `multiSelectOptionKey` to be set to the key of the field option to remove. ``` [ { "op": "removeMultiSelectOption", "fieldKey": "customer_state", "multiSelectOptionKey": "KK Box Japan" } ] ``` The list of options should now be as follows. ``` ... "options": [ {"key": "Box, Inc"}, {"key": "Box.com (UK) Ltd."}, {"key": "Box.nl BV"} ] ... ``` This will affect existing instances of this template. Any fields that were set to this value will have the value removed from its list of selected values. **Reference:** https://developer.box.com/guides/metadata/fields/multi-select/ --- ## Untitled *Type: guide | Category: Metadata * Remove metadata from an item Removing an instance of a metadata template assigned to a file or folder can be done using the item's id, and… # Remove metadata from an item Removing an instance of a metadata template assigned to a file or folder can be done using the item's `id`, and the template's `templateKey` and `scope`. Metadata [scopes](g://metadata/scopes) can be either `global` for templates available to all enterprises, `enterprise` for templates available to the current enterprise, or the `enterprise_:id` for templates belonging to an enterprise whose ID is the `:id` value in the scope name. ## Remove metadata from an file Deleting an instance of a metadata template from a file be achieved by calling the [`DELETE /files/:file_id/metadata/:templateKey/schema`](e://delete_files_id_metadata_id_id) API. This API returns a `204 No Content` API response with no response body when the instance has been successfully removed from the file. ## Remove metadata from an folder Deleting an instance of a metadata template from a folder be achieved by calling the [`DELETE /folders/:folder_id/metadata/:templateKey/schema`](e://delete_folders_id_metadata_id_id) API. This API returns a `204 No Content` API response with no response body when the instance has been successfully removed from the folder. **Reference:** https://developer.box.com/guides/metadata/instances/delete/ --- ## Untitled *Type: guide | Category: Metadata * Apply metadata to an item A metadata template can be applied to a file or folder using the item's id, the template's templateKey and scope… # Apply metadata to an item A metadata template can be applied to a file or folder using the item's `id`, the template's `templateKey` and `scope`, and a set of values for each field in the template. Metadata [scopes](g://metadata/scopes) can be either `global` for templates available to all enterprises, `enterprise` for templates available to the current enterprise, or the `enterprise_:id` for templates belonging to an enterprise whose ID is the `:id` value in the scope name. You can assign up to 100 templates to specific file or folder. ## Apply metadata to a file To apply an instance of a metadata template to a file, call the [`POST /files/:file_id/metadata/:scope/:templateKey`](e://post_files_id_metadata_id_id) API endpoint with the file's `file_id`, the template's `scope` and `templateKey`, and an optional set of values for each [field](g://metadata/fields) in the template. To get the `scope` and `templateKey` for a template, either [list all metadata templates](g://metadata/templates/list), or [list all instances on an file](g://metadata/instances/list). ## Tuple already exists error When there is already metadata applied to this file for the given metadata template, a error is returned with the error code `tuple_already_exists`. In this case, it this case the instance needs to be updated instead. ## Apply metadata to a folder To apply an instance of a metadata template to a folder, call the [`POST /folders/:folder_id/metadata/:scope/:templateKey`](e://post_folders_id_metadata_id_id) API endpoint with the folder's `folder_id`, the template's `scope` and `templateKey`, and an optional set of values for each [field](g://metadata/fields) in the template. To get the `scope` and `templateKey` for a template, either [list all metadata templates](g://metadata/templates/list), or [list all instances on an folder](g://metadata/instances/list). ## Tuple already exists error When there is already metadata applied to this folder for the given metadata template, a error is returned with the error code `tuple_already_exists`. In this case, it this case the instance needs to be updated instead. ## Request body The body of the request can contain a value for each [field](g://metadata/fields) in the template. To inspect what fields are present on a template, inspect a metadata metadata template. For example, let's assume the following template. ``` { "id": "8120731a-41e4-11ea-b77f-2e728ce88125", "type": "metadata_template", "templateKey": "productInfo", "scope": "enterprise_1234567", "displayName": "Product Info", "hidden": false, "copyInstanceOnItemCopy": true, "fields": [ { "id": "feed71de-41e5-11ea-b77f-2e728ce88125", "type": "string", "key": "name", "displayName": "Name", "hidden": false }, { "id": "02b36bb6-41e6-11ea-b77f-2e728ce88125", "type": "enum", "key": "category", "displayName": "Category", "hidden": false, "options": [ { "id": "06a7bcc2-41e6-11ea-b77f-2e728ce88125", "key": "SUVs" }, { "id": "0a50df02-41e6-11ea-b77f-2e728ce88125", "key": "Saloons" }, { "id": "0e466be0-41e6-11ea-b77f-2e728ce88125", "key": "Cabriolets" } ] } ] } ``` This template has 2 [template fields](g://metadata/fields), `name` and `category`. The `name` field is a regular text field, and the `category` is an enum. The request body to assign this template to a file or folder can include a value for any of the fields on the template. It is possible for the body to have no values for no fields. In this case, a valid example would be the following request body. ``` { "name": "Model 3", "category": "SUVs" } ``` One exception is a `global` scoped template with the key `properties` that can be used to assign any data to a template. Using this template, any set of key/value pairs can be assigned to a template. The `category` field in this example is an `enum` field and needs to be one of the available options on the field. **Reference:** https://developer.box.com/guides/metadata/instances/create/ --- ## Untitled *Type: guide | Category: Metadata * Metadata instances A metadata instance describes the relation between a metadata template and a file or folder. It includes the values that… # Metadata instances A [metadata instance](g://metadata/instances) describes the relation between a [metadata template](g://metadata/templates) and a file or folder. It includes the values that are assigned for every field of the template. For example, a user might have assigned an `invoiceData` metadata template to a file and provided 2 values, one for the invoice ID and one for the customer ID. You can assign up to 100 templates to specific file or folder. **Reference:** https://developer.box.com/guides/metadata/instances/ --- ## Untitled *Type: guide | Category: Metadata * Comparison to regular search At the surface the Metadata Query API seems very similar to the Search for content API, but there are several… # Comparison to regular search At the surface the [Metadata Query API](e://post_metadata_queries_execute_read) seems very similar to the [Search for content API](e://get_search), but there are several important differences in how they operate. At a high level the Metadata Query API is optimized for exactness and throughput, while regular search is optimized for relevance to a human user. ## Deep comparison | | Metadata Query API | Search API | | --- | --- | --- | | What is indexed? | This API only returns files/folders based on the values in the metadata templates that are searched. | This API returns files, folders and web links based on values in the item names, descriptions, contents (up to the first 10,000 bytes) as well as the associated metadata template instances. | | Indexing time | This API returns accurate results as soon as metadata has been added, removed, updated or deleted for a file or folder. | This API is subject to a search indexing delay, which is typically 10 minutes, yet may be longer in some cases. This means that items may not be returned for more than 10 minutes after metadata has been updated. | | Matching | This API uses exact matching based on SQL conventions. Results are returned based on a specified sort order. | This API uses fuzzy matching and may return results that vary based on string tokenization, removal of special characters, and other search concepts. Result order is based on either relevance or the updated date of the item. | | Conditional logic | This API supports multi-part boolean expressions with comparison operators. | This API has limited support for querying by metadata. It only supports querying 1 metadata template at a time and only allows simple query operations. | | Response type | This API returns both the matched file/folder and the associated metadata matched by the query. | This API only returns the matched item. A subsequent API call is needed to return each item's metadata. | | Throughput | This API is currently subject to per-user rate limits and to a 10 requests per second per enterprise limit. | This API supports 6 searches per second per user, up to 60 searches per minute and 12 searches per second per enterprise. | | Scale | This API has no limit on the number of items with the specified metadata template that can be returned. It is recommended to only send queries which match no more than 2,000 results. | This API has no limit on number of items with the specified metadata template that can be returned, yet the response time increases significantly as the number of items matching the search grows. This API does have a limit of up to 10 million results for a query. It is recommended to only send queries which match no more than 50,000 results. | | Scope | This API is always limited to the content to which the user has access | This API may be either limited to the content to which the user has access (​user_content​) or to all content in the enterprise (​enterprise_content​). | Search API calls that match more than 10,000 results may result in slight changes in relevance. This may result in duplicate results and results that are not returned. Search should not be considered an ​exact matching​ solution on large data sets. ## Scenarios The following are some example scenarios that may help you decide what API to use. ### Searching an entire enterprise for a term You want to find all content in an enterprise with content or metadata that matches the keyword `Guarantee`. In this case the [Search API](e://get_search) is recommended. This API matches terms in both content and metadata, and can be scoped to find all content in the entire enterprise. ### Searching for multiple metadata values You want to find all documents with the metadata template `​Contract​` having a value greater than $100,000, a renewal date in 2019, and which are ​not​ associated with account number `​1234`. In this case the [Metadata Query API](e://post_metadata_queries_execute_read) is recommended. With a metadata query you can write boolean expressions that evaluate multiple fields in a metadata template, such as a number, a date, and a string. ### Mixing metadata and content search You want to find all documents with the metadata template `​Contract​` having a value greater than $100,000, renewal date in 2019, which are ​not​ associated with account number `​1234`, ​and which contain the term “Sale” in the title or document body. This scenarios is currently **not supported**. At the moment neither of the APIs supports mixing both fuzzy search (searching for "Sale") and the boolean expression matching metadata fields. **Reference:** https://developer.box.com/guides/metadata/queries/comparison/ --- ## Untitled *Type: guide | Category: Metadata * Get metadata on item Information about an instance of a metadata template assigned to a file or folder can be retrieved using the item's id… # Get metadata on item Information about an instance of a metadata template assigned to a file or folder can be retrieved using the item's `id`, and the template's `templateKey` and `scope`. Metadata [scopes](g://metadata/scopes) can be either `global` for templates available to all enterprises, `enterprise` for templates available to the current enterprise, or the `enterprise_:id` for templates belonging to an enterprise whose ID is the `:id` value in the scope name. ## Get metadata instance on file To get an instance of a metadata template on a file, call the [`GET /files/:file_id/metadata/:scope/:templateKey`](e://get_files_id_metadata_id_id) API endpoint with the file's `file_id` and the template's `scope` and `templateKey`. To get the `scope` and `templateKey` for a template, either [list all metadata templates](g://metadata/templates/list), or [list all instances on an file](g://metadata/instances/list). ## Get metadata instance on folder To get an instance of a metadata template on a folder, call the [`GET /folders/:folder_id/metadata/:scope/:templateKey`](e://get_files_id_metadata_id_id) API endpoint with the folder's `folder_id` and the template's `scope` and `templateKey`. To get the `scope` and `templateKey` for a template, either [list all metadata templates](g://metadata/templates/list), or [list all instances on an folder](g://metadata/instances/list). **Reference:** https://developer.box.com/guides/metadata/instances/get/ --- ## Untitled *Type: guide | Category: Metadata * Create a query A metadata query is a POST request to the ​/metadata_queries/execute_read- endpoint, in which the body contains all the parts… # Create a query A metadata query is a `POST` request to the ​`/metadata_queries/execute_read`- endpoint, in which the body contains all the parts of the metadata query. Most important here are the `from` attribute that specifies the template to search for, the `ancestor_folder_id` to specify the folder to search in, and the `query` to determine any template fields to search by. ``` curl -X POST https://api.box.com/2.0/metadata_queries/execute_read \ -H 'Authorization: Bearer <ACCESS_TOKEN>' \ -H 'Content-Type: application/json' \ -d '{ "from": "enterprise_123456.contractTemplate", "query": "amount >= :value", "query_params": { "value": 100 }, "fields": [ "name", "metadata.enterprise_123456.contractTemplate.customerName", "metadata.enterprise_123456.contractTemplate.amount" ], "ancestor_folder_id": "5555", "order_by": [ { "field_key": "amount", "direction": "asc" } ], "limit": 100 }' ``` For more details about all the available parameters, check out any of our other [metadata query guides](g://metadata/queries), or the associated endpoint reference. Learn more about the query syntax ## Response Any files or folders that match the query are returned in the API response. The body of the response is a JSON object with a list of `entries` for each file or folder, and a `next_marker` value that you can use to find the next page of results. Each of the entries will represent the file or folder that matched the query, and only any fields explicitly requested in the `field` parameter are returned. ``` { "entries": [ { "type": "file", "id": "1617554169109", "name": "My Contract.docx", "metadata": { "enterprise_123456": { "contractTemplate": { "$parent": "file_161753469109", "$scope": "enterprise_123456", "$template": "contractTemplate", "$version": 0, "customerName": "Phoenix Corp", "amount": 100 } } } } ], "limit": 20, "next_marker": "AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff" } ``` By default this API returns `20` items per page, but more items can be requested using marker-based pagination. Learn more about paginating query results **Reference:** https://developer.box.com/guides/metadata/queries/create/ --- ## Untitled *Type: guide | Category: Metadata * Update metadata on an item Updating the metadata applied to a file or folder can be done by using the item's id, the template's templateKey… # Update metadata on an item Updating the metadata applied to a file or folder can be done by using the item's `id`, the template's `templateKey` and `scope`, and a set of JSON operations to manipulate the data on the template instance. ## Update metadata on a file To update the metadata to a file, call the [`PUT /files/:file_id/metadata/:scope/:templateKey`](e://put_files_id_metadata_id_id) API endpoint with the file's `file_id`, the template's `scope` and `templateKey`, set of JSON operations to manipulate the data on the template instance. The authenticated user needs to have write access on the file to be able to write changes to the metadata on a file. ## Update metadata on a folder To update the metadata to a folder, call the [`PUT /folders/:folder_id/metadata/:scope/:templateKey`](e://put_folders_id_metadata_id_id) API endpoint with the folder's `folder_id`, the template's `scope` and `templateKey`, set of JSON operations to manipulate the data on the template instance. The authenticated user needs to have write access on the file to be able to write changes to the metadata on a file. ## JSON Operations Updating an piece of metadata follow the [JSON-Patch specification](https://tools.ietf.org/html/rfc6902), which is represented as a list of operation objects. For metadata instances, these operations can be either `add`, `replace`, `remove` , `test`, `move`, or `copy`. Every operation exists out of an `op` name, the [JSON Pointer](https://tools.ietf.org/html/rfc6901) `path` that points to the field to changes, and an optional `value` or `from` value depending on the operation being made. ``` [ { "op": "test", "path": "/competitiveDocument", "value": "no" }, { "op": "remove", "path": "/competitiveDocument" }, { "op": "test", "path": "/status", "value": "active" }, { "op": "replace", "path": "/status", "value": "inactive" }, { "op": "test", "path": "/author", "value": "Jones" }, { "op": "copy", "from": "/author", "path": "/editor" }, { "op": "move", "from": "/currentState", "path": "/previousState" }, { "op": "add", "path": "/currentState", "value": "reviewed" } ] ``` When editing metadata, only values that adhere to the metadata template schema will be accepted. The update is applied completely or not at all. If any errors occur during the application of the update operations, the metadata instance is not changed. The template instance can only be updated if the template has already been assigned to the file or folder. ### Add a new value To add a new value on a template, use the `add` operation. ``` [ { "op": "add", "path": "/name", "value": "Model 3" } ] ``` This will add the `name` field with a value of `Model 3` . Before this operation, the template did not have a value for the `name` field. ``` { // "name": null, // old value "name": "Model 3", // new value "category": "SUVs", "$type": "productInfo-8120731a-41e4-11ea-b77f-2e728ce88125", "$parent": "folder_3456", "$id": "22ba8c96-41e6-11ea-b77f-2e728ce88125", "$version": 3, "$typeVersion": 0, "$template": "productInfo", "$scope": "enterprise_1234567", "$canEdit": true } ``` For `enum` and `multiSelect` fields this new value needs to be one of the valid options for the field. ### Replace a value To replace a value on a template, use the `replace` operation. ``` [ { "op": "replace", "path": "/name", "value": "Model 4" } ] ``` This will replace the `name` field value `Model 3` with a new value of `Model 4`. ``` { // "name": "Model 3", # Old value "name": "Model 3", // new value "category": "SUVs", "$type": "productInfo-8120731a-41e4-11ea-b77f-2e728ce88125", "$parent": "folder_3456", "$id": "22ba8c96-41e6-11ea-b77f-2e728ce88125", "$version": 3, "$typeVersion": 0, "$template": "productInfo", "$scope": "enterprise_1234567", "$canEdit": true } ``` For `enum` and `multiSelect` fields this new value needs to be one of the valid options for the field. ### Copy a value To copy a value from one field to another, use the `copy` operation. ``` [ { "op": "copy", "from": "/name", "path": "/displayName" } ] ``` This will add the `displayName` field with a value that matches the value of the `name` field. Before this operation, the template did not have a value for the `displayName` field. ``` { "name": "Model 3", "displayName": "Model 3", // new value, copied from the name "category": "SUVs", "$type": "productInfo-8120731a-41e4-11ea-b77f-2e728ce88125", "$parent": "folder_3456", "$id": "22ba8c96-41e6-11ea-b77f-2e728ce88125", "$version": 3, "$typeVersion": 0, "$template": "productInfo", "$scope": "enterprise_1234567", "$canEdit": true } ``` For `enum` and `multiSelect` fields this new value needs to be one of the valid options for the field. ### Move a value To move a value from one field to another, use the `move` operation. ``` [ { "op": "copy", "from": "/name", "path": "/displayName" } ] ``` This will add the `displayName` field with a value that matches the value of the `name` field. Before this operation, the template did not have a value for the `displayName` field. After this operation, the `name` field no longer exists. ``` { // "name": "Model 3", // old value, no longer present now "displayName": "Model 3", // new value, copied from the name "category": "SUVs", "$type": "productInfo-8120731a-41e4-11ea-b77f-2e728ce88125", "$parent": "folder_3456", "$id": "22ba8c96-41e6-11ea-b77f-2e728ce88125", "$version": 3, "$typeVersion": 0, "$template": "productInfo", "$scope": "enterprise_1234567", "$canEdit": true } ``` For `enum` and `multiSelect` fields this new value needs to be one of the valid options for the field. ### Remove a value To remove a value from the metadata instance, use the `remove` operation. ``` [ { "op": "remove", "path": "/name" } ] ``` This will remove the `name` field completely from the metadata instance. ``` { // "name": "Model 3", // old value, no longer present now "category": "SUVs", "$type": "productInfo-8120731a-41e4-11ea-b77f-2e728ce88125", "$parent": "folder_3456", "$id": "22ba8c96-41e6-11ea-b77f-2e728ce88125", "$version": 3, "$typeVersion": 0, "$template": "productInfo", "$scope": "enterprise_1234567", "$canEdit": true } ``` For `enum` and `multiSelect` fields this new value needs to be one of the valid options for the field. ### Test a value To test that a field has the value you expect, use the `test` operation. ``` [ { "op": "test", "path": "/name", "value": "Model 4" } ] ``` When a test fails the API will not perform any of the operations and return a `409 Conflict` HTTP status with the following error. ``` { "message": "value differs from expectations", "code": "failed_json_patch_application", "request_id": "bzxgr1gbcq5h67pj" } ``` The main purpose of this operation is to validate that the values on the metadata instance are as expected before any operations are performed. The Box API either performs all changes or none, and therefore a failing test is very useful to ensure all values are expected before any transformation is applied. **Reference:** https://developer.box.com/guides/metadata/instances/update/ --- ## Untitled *Type: guide | Category: Metadata * List all metadata on an item Metadata instances can be listed for either a file or a folder. List metadata on a file To list all metadata… # List all metadata on an item Metadata instances can be listed for either a file or a folder. ## List metadata on a file To list all metadata instances on a file, call the [`GET /files/:file_id/metadata`](e://get_files_id_metadata) API endpoint. This API does not support paging and it will always return all of the metadata instances for this file. ## List metadata on a folder To list all metadata instances on any folder (except for the root folder), call the [`GET /folders/:file_id/metadata`](e://get_files_id_metadata) API endpoint. This API does not support paging and it will always return all of the metadata instances for this file. This API can not be used on the root folder with ID `0`. **Reference:** https://developer.box.com/guides/metadata/instances/list/ --- ## Untitled *Type: guide | Category: Metadata * Limitations A few limits apply to the the metadata query APIs. Files and folders ​A metadata query will only return items (files or folders… # Limitations A few limits apply to the the metadata query APIs. ## Files and folders ​A metadata query will only return items (files or folders) to which the requesting user has at least `previewer` access. ## Enterprise vs Global templates A metadata query only works with metadata templates that have been created by that enterprise. A query will not return results based on the content of free form key-value pairs stored in the `​global.properties` template. ## Classification metadata templates Box uses metadata templates to power its content classification. These metadata templates can not be used in metadata queries, as they will most likely run into issues regarding large results sets. More on this next. There are no immediate plans to start supporting these queries in the future. ## Recommended result set size Where possible it is recommended to only send requests for which the result set is less than 2,000 items.​ The ​result set​ is the entire collection of files and folder that match the metadata query exclusively based on evaluating the `​from​`, `​query​`, and `​query_params​` parameters - before the requesting user’s permissions and the `​ancestor_folder​` scope are considered. When sending a metadata query request for which the result set exceeds 2,000 items, the API can only guarantee that it returns all all matching results if both the following conditions are met. 1. The requesting user has at least **​Previewer** ​permission to all items in the result set 2. The ancestor folder contains all of the files in the result set When sending a metadata query request for which the result set exceeds 2,000 items and for which these conditions are not true, the API might return error with a 4XX response code indicating that the query will need to be restricted to return fewer results. For example, consider the following simplified representation of a metadata template called `catalogImages​` which has one string field called `​photographer`. ``` { "templateKey": "catalogImages", "fields": [ { "type": "string", "key": "photographer" } ] } ``` In this example, assume that there are 10 photographers, each of which have captured the same number of images that have the ​`catalogImages​` template applied. Now consider assume that there are 4,000 files in your Box enterprise which have the `catalogImages` template ​applied and which are split evenly between the two folders,​ `Parts​` and `Products`, ​which are children of the parent folder `​Catalog​` as shown below. ``` Catalog/ | |- Parts/ | |- file_0000.jpeg |- ... |- file_1999.jpeg |- Products/ | |- file_2000.jpeg |- ... |- file_3999.jpeg ``` The following table indicates the outcome of several possible queries. The query is described in plain language for readability. Remember that the ​result set ​is defined as a collection of items (files and folders) which match the metadata query exclusively based on evaluating the `​from​`, `​query​`, and `​query_params` parameters before the requesting user’s permissions and the `​ancestor_folder​` scope are considered. | Query | Result Set | Outcome | Notes | | --- | --- | --- | --- | | Select items with the catalogImages ​template where the ​photographer​ is Mike | 200 items | Success | By only selecting items for Mike the result set is constrained to only 400 files | | Select items with the catalogImages ​template | 4,000 items | May fail | The result set exceeds 2,000 items. If the user does not have access to all of the files in the result set the query may fail | | Select items with the catalogImages ​template in the Products​ folder | 4,000 items | May fail | The result set exceeds 2,000 items and not all results are contained within the ancestor folder. | | Select items with the catalogImages ​template in the Products folder where the photographer​ is Mike | 200 items | Success | By only selecting items for Mike the result set is constrained to only 400 files | **Reference:** https://developer.box.com/guides/metadata/queries/limitations/ --- ## Untitled *Type: guide | Category: Metadata * Common errors Metadata query API errors mostly are similar to errors returned by other APIs, however at this time some incorrect client… # Common errors Metadata query API errors mostly are similar to errors returned by other APIs, however at this time some incorrect client requests may result in a server-side error with a HTTP status code in the `5XX` range rather than an appropriate `400 Bad Request` error. This is a known issue which will be addressed soon. ## Incorrect template key and scope A common error is to use an incorrect value for the the `from` value in the request, which can result in various errors in the `HTTP 4XX` range. Without a correct `from` value the API does not know what template to search for. The value in `from` must be formed as `scope.templateKey`. In this case `scope` is your enterprise's template scope, which looks something like `enterprise_123456`. The numeric value here is your enterprise's ID. Any scope that does not match this format, including the `global` scope and the `enterprise` shorthand scope, will return an error. The `templateKey` is the unique key for the metadata template within your enterprise. The API returns an error when a template with the given key does not exist, or when the key is used within the wrong enterprise were the key does not exist. The [List all metadata templates for enterprise endpoint](e://get-metadata-templates-enterprise) can be used to list all templates available in your enterprise, including their `scope` and `templateKey`. ## Missing value in query_param A common error is to forget to include a query argument in the `query_params` object, which results in a `HTTP 400` error with a code of `unexpected_json_type`. Without all arguments present in the `query_params` the API can not compile your request into a full query. For example, assume your search `query` is as follows `amount >= :value AND status = :status`. All of the arguments that start with a colon `:` will need to be present in the `query_params`. In this case your query parameters would have to look something like this. Missing out on any of these values will result in an error. ``` "query_params": { "value": 100, "status": "active" } ``` The name of each argument can configured to your liking and does not need to match the field key. The only requirement is that it starts with a `:`. ## Missing ancestor_folder_id A common error is to forget the `ancestor_folder_id` in the request, which results in a `HTTP 400` error with a code of `bad_request`. Without the `ancestor_folder_id` value the API does not know what folder to search for results in. When in doubt a value of `0` can be used for the user's root folder. **Reference:** https://developer.box.com/guides/metadata/queries/errors/ --- ## Untitled *Type: guide | Category: Metadata * Metadata queries A metadata query provides a way to find files and folders by searching for the metadata attached to them. For example, to… # Metadata queries A metadata query provides a way to find files and folders by searching for the metadata attached to them. For example, to find the all files for an invoice with a certain ID, the query would look for all files and folders with the `invoiceData` template attached to it and a value of `id = :id`, where `:id` would be the value of the invoice. ## Authentication The metadata query API can be used by applications that have been authenticated using traditional [OAuth 2.0](g://authentication/oauth2) or [JWT](g://authentication/jwt). **Reference:** https://developer.box.com/guides/metadata/queries/ --- ## Untitled *Type: guide | Category: Metadata * Paginate and sort By default only 20 query results are returned per page and the order of these results is not guaranteed and may change… # Paginate and sort By default only 20 query results are returned per page and the order of these results is not guaranteed and may change. Pagination and sorting allow for getting more results and defining the order of the results. ## Pagination By default the API only returns the first page of 20 results. To request more results per page the `limit` query parameter can be send with the request. ``` curl -X POST https://api.box.com/2.0/metadata_queries/execute_read \ -H 'Authorization: Bearer <ACCESS_TOKEN>' \ -H 'Content-Type: application/json' \ -d '{ "from": "enterprise_123456.contractTemplate", "fields": ["name"], "ancestor_folder_id": "5555", "limit": 100 }' ``` The maximum value for `limit` is 100. To return more pages of results each page returns a `next_marker` value. ``` { "entries": [...], "next_marker": "AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff" } ``` This `next_marker` can be used to form a new request for the next page of results. ``` curl -X POST https://api.box.com/2.0/metadata_queries/execute_read \ -H 'Authorization: Bearer <ACCESS_TOKEN>' \ -H 'Content-Type: application/json' \ -d '{ "from": "enterprise_123456.contractTemplate", "fields": ["name"], "ancestor_folder_id": "5555", "limit": 100, "marker": "AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff" }' ``` When a response does not include a next marker it indicates that no more matching results exist. To use the `next_marker` it is important to use the exact same query for the next page of results. The API will return an error if any of the parameters like the `query`, `query_params`, or others are changed. ## Sort Results can be ordered by any of the supported metadata field types. These only supported types currently are `float`, `date`, and `string` [fields](g://metadata/fields). Ordering by `enum` or `multiSelect` value is currently not supported. To order result, provide one or more field keys to sort by, as well as a direction. ``` "order_by": [ { "field_key": "amount”, "direction": "desc" }, { "field_key": "created_at" "direction": "desc" } ] ``` The ordering direction must be the same for all ​​specified keys. In other words, for each `field_key` the `direction` must be the same. **Reference:** https://developer.box.com/guides/metadata/queries/pagination/ --- ## Untitled *Type: quick-start | Category: Metadata * Apply metadata to a file With your new customerData template in hand you can now apply this template to a file or folder. To apply this… # Apply metadata to a file With your new `customerData` template in hand you can now apply this template to a file or folder. To apply this template you will need the `scope` and `templateKey` of the template, as well as the ID of the item to apply the template to. ``` curl -X POST https://api.box.com/2.0/files/12345/metadata/enterprise/customerInfo \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "Box, Inc", "industry": "Technology", "tav": 1000000 }' ``` ``` var metadataValues = new Dictionary<string, object>() { { "name", "Box, Inc" }, { "industry", "Technology" }, { "tav", 100000 } }; Dictionary<string, object> metadata = await client.MetadataManager .CreateFileMetadataAsync(fileId: "12345", metadataValues, "enterprise", "customerInfo"); ``` ``` BoxFile file = new BoxFile(api, "12345"); file.createMetadata( "customerInfo", "enterprise", new Metadata() .add("name", "Box, Inc") .add("industry", "Technology") .add("tav", 100000) ); ``` ``` metadata = { 'name': 'Box, Inc', 'industry': 'Technology', 'tav': 1000000 } client.file(file_id='11111').metadata(scope='enterprise', template='customerInfo').set(metadata) ``` ``` client.files.addMetadata( '12345', client.metadata.scopes.ENTERPRISE, "customerInfo", { name: "Box, Inc", industry: "Technology", tav: 1000000 } ).then(metadata => { // ... }); ``` The `industry` field in this example is an `enum` field and therefore the value needs to be one of the available options on the field. Any other value will result in an error. The API will return the newly created metadata instance. ``` { "name": "Box, Inc", "industry": "Technology", "tav": 1000000, "$id": "01234500-12f1-1234-aa12-b1d234cb567e", "$parent": "folder_12345,", "$scope": "enterprise_34567", "$template": "customerInfo", "$type": "customerInfo-6bcba49f-ca6d-4d2a-a758-57fe6edf44d0", "$typeVersion": 2, "$version": 1, "$canEdit": true } ``` I've applied metadata to a file **Reference:** https://developer.box.com/guides/metadata/quick-start/create-instance/ --- ## Untitled *Type: quick-start | Category: Metadata * Create a metadata query As a final step, let's look at how you can create a query to find specific files and folders based on the metadata… # Create a metadata query As a final step, let's look at how you can create a query to find specific files and folders based on the metadata attached to those files/folders. A [metadata query](g://metadata/queries) provides a way to find files and folders by searching for the metadata attached to them. The search syntax is similar to SQL and it supports boolean operations and comparative operators to perform powerful searches. In our case, let's create a query to find any files or folders that have an instance of the `customerInfo` metadata template attached to them. We will filter this list down to any files that belong to a customer who's total account value is more than $200,000. ``` curl -X POST https://api.box.com/2.0/metadata_queries/execute_read \ -H 'Authorization: Bearer <ACCESS_TOKEN>" ' \ -H 'Content-Type: application/json' \ -d '{ "from": "enterprise_123456.customerInfo", "fields": [ "name", "enterprise_123456.customerInfo.name" "enterprise_123456.customerInfo.tav" ], "query": "tav >= :value", "query_params": { "value": 200000 }, "ancestor_folder_id": "0" }' ``` This API will return a list of matched files and folders, as well as the metadata that matched the query for that file. ``` { "entries": [ { "type": "file", "id": "11111", "etag": "0", "metadata": { "enterprise_123456": { "customerInfo": { "name": "Box", "tav": 1000000, "$parent": "folder_12345,", "$scope": "enterprise_123456", "$template": "customerInfo", "$version": 1 } } } } ], "limit": 20, "next_marker": "AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff" } ``` By default this API returns `20` items per page, but more items can be requested using marker-based pagination. Learn more about metadata queries I've queried a file using metadata **Reference:** https://developer.box.com/guides/metadata/quick-start/create-query/ --- ## Untitled *Type: guide | Category: Metadata * Query syntax The query syntax for the metadata query API is similar to that of a SQL database. To query for all files and folders that match… # Query syntax The query syntax for the metadata query API is similar to that of a SQL database. To query for all files and folders that match a contract metadata template with a contract value of over $100 the following metadata query could be created. ``` { "from": "enterprise_123456.contractTemplate", "query": "amount >= :value", "query_params": { "value": 100 }, "fields": [ "name", "metadata.enterprise_123456.contractTemplate.amount" ], "ancestor_folder_id": "5555" } ``` In this case the `from` value represents the `scope` and `templateKey` of the metadata template, and the `ancestor_folder_id` represents the folder ID to search within, including its subfolders. ## The fields parameter By default, this API will only return the base-representation of a file or folder, which includes their `id`, `type`, and `etag` values. To request any additional data the `fields` parameter can be used to query any additional fields, as well as any metadata associated to the item. For example: - `created_by` will add the details of the user who created the item to the response. - `metadata.<scope>.<templateKey>` will return the base-representation of the metadata instance identified by the `scope` and `templateKey`. - `metadata.<scope>.<templateKey>.<field>` will return all fields in the base-representation of the metadata instance identified by the `scope` and `templateKey` plus the field specified by the `field` name. Multiple fields for the same `scope` and `templateKey` can be defined. ## The query parameter The `query` parameter represents the SQL-like query to perform on the selected metadata instance. This parameter is optional, and without this parameter the API would return all files and folders for this template. Every left hand field name, like `amount`, needs to match the `key` of a field on the associated metadata template. In other words, you can only search for fields that are actually present on the associated metadata instance. Any other field name will result in the error returning an error. ### The query_params parameter To make it less complicated to embed dynamic values into the query string, an argument can be defined using a colon syntax, like `:value`. Each argument that is specified like this needs a subsequent value with that key in the `query_params` object, for example: ``` { ..., "query": "amount >= :amount AND country = :country", "query_params": { "amount": 100, "country": "United States" }, ... } ``` ### Logical operators A query supports the following logical operators. | Operator | | | --- | --- | | AND | Matches when all the conditions separated by AND are TRUE. | | OR | Matches when any of the conditions separated by OR is TRUE. | | NOT | Matches when the preceding condition(s) is not TRUE. | | LIKE | Matches when the template field value matches a pattern. Only supported for string values. See pattern matching for more details. See additional limitations below. | | NOT LIKE | Matches when the template field value does not match a pattern. Only supported for string values. See pattern matching for more details. See additional limitations below. | | ILIKE | Identical to LIKE but case insensitive. See additional limitations below. | | NOT ILIKE | Identical to NOT LIKE but case insensitive. See additional limitations below. | | IN | Matches when a template field value equals any value in a specified list. Use explicitly defined query_params arguments for each list item, such as amount IN (:arg1, :arg2, :arg3). By design, the IN operator isn't supported for multiselect fields in metadata queries and returns a 400 error. | | NOT IN | Similar to IN but when the template field value matches none of the arguments provided in the list. | | IS NULL | Matches when the template field value is null. | | IS NOT NULL | Matches when the template field value is not null . | Any match on a `string` or `enum` field is case sensitive except when using the `ILIKE` operator. ### Comparison operators A query supports the following comparison operators. | Operator | | | --- | --- | | = | Ensures a template field value is equal to the specified value | | > | Ensures a template field value is greater than the specified value | | < | Ensures a template field value is less than the specified value | | >= | Ensures a template field value is greater than or equal to the specified value | | <= | Ensures a template field value is less than or equal to the a specified value | | <> | Ensures a template field value is not equal to the a specified value | Bit-wise and arithmetic operators are not supported by the Metadata Query API. ### Pattern matching The `LIKE`, `NOT LIKE`, `ILIKE`, and `NOT ILIKE` operators match a string to a pattern. The pattern supports the following reserved characters. - `%` The percent sign represents zero, one, or multiple characters, for example `%Contract` matches `Contract`, `Sales Contract`, but not `Contract (Sales)`, - `_` The underscore represents a single character, for example `Bo_` matches `Box`, `Bot`, but not `Bots`, Both of these reserved characters can be used before, after, or in between other characters. A pattern can include multiple reserved characters, for example `Box% (____)` would match `Box Contract (2020)`. An example query would looks something like this. Note that the `%`-wrapped string is not in the `query` attribute but in the list of `query_params`. ``` { ..., "query": "country ILIKE :country", "query_params": { "country": "%United%" }, ... } ``` The backslash character `\` can be used to escape the `%` or `_` characters if those need to be matched literally, for example `20\%` would match the literal value of `20%`. **Reference:** https://developer.box.com/guides/metadata/queries/syntax/ --- ## Untitled *Type: quick-start | Category: Metadata * Create a custom metadata template To create a custom metadata template for your enterprise you can use our API directly or one of our SDKs… # Create a custom metadata template To create a custom metadata template for your enterprise you can use [our API directly](e://post-metadata-templates-schema) or one of our SDKs to create a new template. For this `customerInfo` template, we're going to create a template with 3 fields. The first field is a text field to hold the customer's `name`, the second is a dropdown list of the possible values for the `industry` the customer operates in, and the final field represents the total annual contract value (`tav`). Learn about the different field types To create this template we need to pass in the configuration for the fields, as well as a display name for the field. ``` curl -X POST https://api.box.com/2.0/metadata_templates/schema \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "scope": "enterprise", "displayName": "Customer Info", "fields": [ { "type": "string", "displayName": "Name" }, { "type": "enum", "displayName": "Industry", "options": [ {"key": "Technology"}, {"key": "Healthcare"}, {"key": "Legal"} ] }, { "type": "float", "displayName": "Total account value", "key": "tav" } ] }' ``` ``` var templateParams = new BoxMetadataTemplate() { DisplayName = "Customer Info", Scope = "enterprise", Fields = new List<BoxMetadataTemplateField>() { new BoxMetadataTemplateField() { Type = "string", DisplayName = "Name" }, new BoxMetadataTemplateField() { Type = "enum", DisplayName = "Industry", Options = new List<BoxMetadataTemplateFieldOption>() { new BoxMetadataTemplateFieldOption() { Key = "Technology" }, new BoxMetadataTemplateFieldOption() { Key = "Healthcare" }, new BoxMetadataTemplateFieldOption() { Key = "Legal" } } }, new BoxMetadataTemplateField() { Type = "float", DisplayName = "Total account value", Key="tav" }, } }; BoxMetadataTemplate template = await client.MetadataManager.CreateMetadataTemplate(templateParams); ``` ``` MetadataTemplate.Field name = new MetadataTemplate.Field(); name.setType("string"); name.setDisplayName("Name"); MetadataTemplate.Field industry = new MetadataTemplate.Field(); industry.setType("enum"); industry.setDisplayName("Industry"); MetadataTemplate.Option technology = new MetadataTemplate.Option(); technology.setKey("Technology"); MetadataTemplate.Option healthcare = new MetadataTemplate.Option(); healthcare.setKey("Healthcare"); MetadataTemplate.Option legal = new MetadataTemplate.Option(); legal.setKey("Legal"); List<MetadataTemplate.Option> options = new ArrayList<MetadataTemplate.Option>(); options.add(technology); options.add(healthcare); options.add(legal); MetadataTemplate.Field tav = new MetadataTemplate.Field(); tav.setType("float"); tav.setDisplayName("Total account value"); tav.setKey("tav"); List<MetadataTemplate.Field> fields = new ArrayList<MetadataTemplate.Field>(); fields.add(name); fields.add(industry); fields.add(tav); MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, "enterprise", "customerInfo", "Customer Info", false, fields); ``` ``` from boxsdk.object.metadata_template import MetadataField, MetadataFieldType fields = [ MetadataField(MetadataFieldType.STRING, 'Name') MetadataField(MetadataFieldType.ENUM, 'Industry', options=['Technology', 'Healthcare', 'Legal']) ] template = client.create_metadata_template('Customer Info', fields) ``` ``` client.metadata.createTemplate( 'Customer Info', [ { type: 'string', displayName: 'Name' }, { type: 'enum', displayName: 'Industry', options: [ {key: 'Technology'}, {key: 'Healthcare'}, {key: 'Legal'} ] }, { type: 'float', displayName: 'Total account value', key: 'tav' } ] ).then(template => { // ... }); ``` # Admin permissions required Creating metadata templates is restricted to users with admin permission. This means that only admins, or co-admins who have been granted rights to Create and edit metadata templates for your company by the admin can use the web app or the API to manage templates. The API will return the newly created metadata template. ``` { "id": "100ac693-a468-4b37-9535-05984b804dc2", "type": "metadata_template", "templateKey": "customerInfo", "scope": "enterprise_34567", "displayName": "Customer Info", "hidden": false, "copyInstanceOnItemCopy": false, "fields": [ { "id": "5c6a5906-003b-4654-9deb-472583fc2930", "type": "string", "key": "name", "displayName": "Name", "hidden": false }, { "id": "cf3eb5b8-52ef-456c-b175-44354a27e289", "type": "enum", "key": "industry", "displayName": "Industry", "options": [ {"key": "Technology"}, {"key": "Healthcare"}, {"key": "Legal"} ], "hidden": false }, { "id": "5c6a5906-4654-9deb-003b-472583fc2930", "type": "float", "key": "tav", "displayName": "Total account value", "hidden": false } ] } ``` # Template key Although you did not explicitly set the template key the key is automatically derived from the `displayName` value. In this case, the `templateKey` would be `customerInfo`. I've created a custom template **Reference:** https://developer.box.com/guides/metadata/quick-start/create-template/ --- ## Untitled *Type: quick-start | Category: Metadata * Working with Metadata The Metadata APIs are a great tool to allow applications to automatically add additional information to files and… # Working with Metadata The Metadata APIs are a great tool to allow applications to automatically add additional information to files and folders. ## Overview This guide will take you through the following steps. 1. [List all templates](g://metadata/quick-start/list-all) available to you. 2. [Create a custom metadata template](g://metadata/quick-start/create-template) to hold data specific to your enterprise. 3. [Apply a custom metadata template](g://metadata/quick-start/create-instance) to a file, allowing you to assign custom data to a file. 4. [Update metadata instance](g://metadata/quick-start/update-instance) on a file, allowing you to change the data assigned to a file. 5. [Update a metadata template](g://metadata/quick-start/update-template) and change the data applied to all instances of this template. 6. [Create a query to find files by metadata](g://metadata/quick-start/create-query) and change the data applied to all instances of this template. I am ready to get started **Reference:** https://developer.box.com/guides/metadata/quick-start/ --- ## Untitled *Type: quick-start | Category: Metadata * List all metadata templates It's likely your enterprise already has a list of metadata templates that you can use right off-the-shelve… # List all metadata templates It's likely your enterprise already has a list of metadata templates that you can use right off-the-shelve without having to create your own. In general, metadata templates are either available to only your enterprise or to every enterprise using Box. The `scope` of a template defines if a template is available to everyone (`global`) or only to your enterprise (`enterprise`). Learn more about metadata scopes ## Listing templates A few [global templates](e://get_metadata_templates_global) are available to all customers. Many of these templates are for Box's internal use, yet your application can use and apply these. More useful are templates created by applications and admins within your enterprise to hold data specific to your enterprise's needs. ## A metadata template A [metadata template](g://metadata/templates) describes a set of key/value pairs that can be assigned to a file or folder. For example, a `customerInfo` template might hold data about a customer, having a field for the customer name as well as the customer's industry. ``` { "id": "100ac693-a468-4b37-9535-05984b804dc2", "type": "metadata_template", "templateKey": "customerInfo", "scope": "enterprise_12345", "displayName": "Customer Info", "hidden": false, "copyInstanceOnItemCopy": false, "fields": [ { "id": "5c6a5906-003b-4654-9deb-472583fc2930", "type": "string", "key": "name", "displayName": "Name", "hidden": false }, { "id": "cf3eb5b8-52ef-456c-b175-44354a27e289", "type": "enum", "key": "industry", "displayName": "Industry", "options": [ {"key": "Technology"}, {"key": "Healthcare"}, {"key": "Legal"} ], "hidden": false } ] } ``` I've listed the templates available to me **Reference:** https://developer.box.com/guides/metadata/quick-start/list-all/ --- ## Untitled *Type: quick-start | Category: Metadata * Next steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. Listed all templates… # Next steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. 1. [Listed all templates](g://metadata/quick-start/list-all) available to you. 2. [Created a custom metadata template](g://metadata/quick-start/create-template) to hold data specific to your enterprise. 3. [Applied a custom metadata template](g://metadata/quick-start/create-instance) to a file, allowing you to assign custom data to a file. 4. [Updated a metadata instance](g://metadata/quick-start/update-instance) on a file, allowing you to change the data assigned to a file. 5. [Updated a metadata template](g://metadata/quick-start/update-template) and changed the data applied to all instances of this template. 6. [Queried for files and folders](g://metadata/quick-start/create-query) by matching the values in the metadata instances attached to them. ## Next Steps We recommend the following resources to learn more about using metadata with the Box API. - [Learn more about metadata scopes](g://metadata/scopes) - [Learn more about the different field types](g://metadata/fields) that can be used on a template. **Reference:** https://developer.box.com/guides/metadata/quick-start/next-steps/ --- ## Untitled *Type: quick-start | Category: Metadata * Update a metadata template Let's look at how we can update an existing metadata template. Updates to metadata templates are performed… # Update a metadata template Let's look at how we can update an existing metadata template. Updates to metadata templates are performed through **operations** rather than directly changing the template itself. This method allows you to update any existing metadata instances that are already applied to files and folders. Learn more about updating templates In this case, let's assume that we realized that having a `Name` field is a bit ambiguous, and therefore, we want to change the `Name` field of the `customerInfo` template to `Company Name` instead. By using the `editField` operation we can change the `displayName` and the `key` of the field on the template and on every instance of the template that might be applied to a file or folder. ``` curl -X PUT https://api.box.com/2.0/metadata_templates/enterprise/blueprintTemplate/schema \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '[ { "op": "editField", "fieldKey": "name", "data": { "key": "company_name", "displayName": "Company Name" } } ]' ``` ``` var updates = new List<BoxMetadataTemplateUpdate>() { new BoxMetadataTemplateUpdate() { Op = MetadataTemplateUpdateOp.editField, FieldKey = "name", Data = new { key = "company_name", displayName = "Company Name" } } }; BoxMetadataTemplate updatedTemplate = await client.MetadataManager .UpdateMetadataTemplate(updates, "enterprise", "customerData"); ``` ``` List<MetadataTemplate.FieldOperation> updates = new ArrayList<MetadataTemplate.FieldOperation>(); String editField = "{\"op\":\"editField\",\"fieldKey\":\"name\",\"data\":{\"key\":\"company_name\",\"displayName\":\"Company Name\"}}"; updates.add(new MetadataTemplate.FieldOperation(editField)); MetadataTemplate.updateMetadataTemplate(api, "enterprise", "customerData", updates); ``` ``` template = client.metadata_template('enterprise', 'customerData') updates = template.start_update() updates.edit_field('name', key='company_name', display_name="Company Name") template.update_info(updates) ``` ``` var operations = [ { op: 'editField', fieldKey: 'name', data: { key: 'company_name', displayName: "Company Name" } } ]; client.metadata.updateTemplate( 'enterprise', 'customerData', operations ).then(template => { //.. }); ``` The API will return the updated metadata template. ``` { "id": "100ac693-a468-4b37-9535-05984b804dc2", "type": "metadata_template", "templateKey": "customerInfo", "scope": "enterprise_34567", "displayName": "Customer Info", "hidden": false, "copyInstanceOnItemCopy": false, "fields": [ { "id": "5c6a5906-003b-4654-9deb-472583fc2930", "type": "string", "key": "company_name", "displayName": "Company Name", "hidden": false }, { "id": "cf3eb5b8-52ef-456c-b175-44354a27e289", "type": "enum", "key": "industry", "displayName": "Industry", "options": [ {"key": "Technology"}, {"key": "Healthcare"}, {"key": "Legal"} ], "hidden": false }, { "id": "5c6a5906-4654-9deb-003b-472583fc2930", "type": "float", "key": "tav", "displayName": "Total account value", "hidden": false } ] } ``` Updating the template through operations has the benefit that any instance of the template is automatically updated as well. In this case, the instance we created in previous steps would now look something like this. ``` { "company_name": "Box", "industry": "Technology", "tav": 1000000, "$id": "01234500-12f1-1234-aa12-b1d234cb567e", "$parent": "folder_12345,", "$scope": "enterprise_34567", "$template": "customerInfo", "$type": "customerInfo-6bcba49f-ca6d-4d2a-a758-57fe6edf44d0", "$typeVersion": 2, "$version": 1, "$canEdit": true } ``` I've updated metadata template **Reference:** https://developer.box.com/guides/metadata/quick-start/update-template/ --- ## Untitled *Type: guide | Category: Metadata * Create a metadata template To create a metadata template, pass a scope, displayName and an optional set of fields to the POST /metadata… # Create a metadata template To create a metadata template, pass a `scope`, `displayName` and an optional set of `fields` to the [`POST /metadata_templates/schema`](e://post_metadata_templates_schema) API. Metadata templates can only be created for the `enterprise` scope. Templates can not be created for the `global` scope. # Admin permissions required Creating metadata templates is restricted to users with admin permission. This means that only admins, or co-admins who have been granted rights to Create and edit metadata templates for your company by the admin can use the web app or the API to manage templates. ## Template Fields The `fields` attribute represents the set of individual fields that a user can fill in on a template. For example, a `customer` template might have a `name` field of type `string`. Template fields can be of `string`, `enum`, `float`, `date`, `enum` or `multiSelect` type. Each field requires at least a `type`, `displayName` and `key`. ``` { "scope": "enterprise", "displayName": "Customer", "fields": [ { "type": "string", "key": "name", "displayName": "Name" } ] } ``` The `enum` and `multiSelect` field types represent a dropdown list where a user can select respectively one or many options from a list of items. ``` { "scope": "enterprise", "displayName": "Customer", "fields": [ { "type": "enum", "key": "industry", "displayName": "Industry", "options": [ {"key": "Technology"}, {"key": "Healthcare"}, {"key": "Legal"} ] } ] } ``` Learn more about Metadata Template Fields ## Template Keys When a metadata template is created, a `templateKey` is automatically generated from the `displayName` of the template unless a `templateKey` is explicitly provided. When creating the template key, any spaces and irregular characters in the name are removed, and the string is transformed to camel case. For example, a metadata template that is named `Test Name (with-special_) Characters` will have a `templateKey` of `testNameWithspecialCharacters`. This template key is then used when making any API requests to get the template's information or assign it to an item. **Reference:** https://developer.box.com/guides/metadata/templates/create/ --- ## Untitled *Type: quick-start | Category: Metadata * Update metadata on a file Once metadata has been applied to a file or folder there is often a need to update the metadata at a later date… # Update metadata on a file Once metadata has been applied to a file or folder there is often a need to update the metadata at a later date. Updating a metadata instance is done by applying a set of operations to the original data. These operations are performed atomically, ensuring that the changes are either all applied or not applied at all. Learn more about updating instances In this case, let's assume we want to change the `name` of the customer from `Box, Inc` to `Box`. We can apply two operations, firstly, we ensure the value of the name is still `Box, Inc` before we change it, and secondly we make the change. ``` curl -X PUT https://api.box.com/2.0/files/12345/metadata/enterprise/customerInfo \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[ { "op": "test", "path": "/name", "value": "Box, Inc" }, { "op": "replace", "path": "/name", "value": "Box" } ]' ``` ``` var updates = new List<BoxMetadataUpdate>() { new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/name", Value = "Box, Inc" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.replace, Path = "/name", Value = "Box" } }; Dictionary<string, object> updatedMetadata = await client.MetadataManager .UpdateFileMetadataAsync("12345", updates, "enterprise", "customerInfo"); ``` ``` BoxFile file = new BoxFile(api, "12345"); file.updateMetadata( file.createMetadata( "customerInfo", "enterprise", new Metadata().test("/name", "Box, Inc").replace("/name", "Box") ); ``` ``` file = client.file(file_id='12345') metadata = file.metadata(scope='enterprise', template='customerInfo') updates = metadata.start_update() updates.test('/name', 'Box, Inc') updates.replace('/name', 'Box') file.update(updates) ``` ``` var updates = [ { op: 'test', path: '/name', value: 'Box, Inc' }, { op: 'replace', path: '/name', value: 'Box' } ]; client.files.updateMetadata( '12345', client.metadata.scopes.ENTERPRISE, "customerInfo", updates ).then(metadata => { //... }); ``` Learn more about all operations The API will return the updated metadata instance. ``` { "name": "Box", "industry": "Technology", "tav": 1000000, "$id": "01234500-12f1-1234-aa12-b1d234cb567e", "$parent": "folder_12345,", "$scope": "enterprise_34567", "$template": "customerInfo", "$type": "customerInfo-6bcba49f-ca6d-4d2a-a758-57fe6edf44d0", "$typeVersion": 2, "$version": 1, "$canEdit": true } ``` I've updated metadata on a file **Reference:** https://developer.box.com/guides/metadata/quick-start/update-instance/ --- ## Untitled *Type: guide | Category: Metadata * List all metadata templates Metadata templates can be listed for either the enterprise or the global scope. List global templates To list… # List all metadata templates Metadata templates can be listed for either the enterprise or the global scope. ## List global templates To list all global metadata templates, call the [`GET /metadata_templates/global`](e://get_metadata_templates_global) API endpoint. This API returns a list of all the metadata templates created by Box and made available to all enterprises. ## List current enterprise's templates To list all metadata templates created for usage within the current enterprise, call the [`GET /metadata_templates/enterprise`](e://get_metadata_templates_enterprise) API endpoint. This API returns a list of all the metadata templates created by this enterprise, and these templates are only available to apply to files in this enterprise. ## Pagination This API uses [marker-based pagination](g://api-calls/pagination/marker-based) and can return a `next_marker` value in the response body to indicate that more templates might be available. **Reference:** https://developer.box.com/guides/metadata/templates/list/ --- ## Untitled *Type: guide | Category: Metadata * Update a metadata template Updating a metadata template can be achieved by passing an array of operations to the PUT /metadata_templates… # Update a metadata template Updating a metadata template can be achieved by passing an array of operations to the [`PUT /metadata_templates/:scope/:templateKey/schema`](e://put_metadata_templates_id_id_schema) API. # Admin permissions required Updating metadata templates is restricted to users with admin permission. This means that only admins, or co-admins who have been granted rights to Create and edit metadata templates for your company by the admin can use the web app or the API to manage templates. ## Operations Updates to metadata templates are performed through **operations** rather than directly changing the template itself. This method allows us to update any existing metadata instances that are already applied to files and folders. ## Template operations Template operations update a template's details or fields. These operations are generally safe as they are applied to any template instance without much impact. ### Edit a template The operation `editTemplate` allows for editing any of the base properties of the template, like the `displayName`, `copyInstanceOnItemCopy` and more. | Parameter | | | --- | --- | | data | An object representing the properties to change | ``` [ { "op": "editTemplate", "data": { "displayName": "Client", "copyInstanceOnItemCopy": true } } ] ``` This will update the template to have a new display name of Client. This will affect existing instances of this template. ### Add a field to a template The operation `addField` adds a field to a template. | Parameter | | | --- | --- | | data | An object representing field to add | ``` [ { "op": "addField", "data": { "displayName": "Category", "key": "category", "hidden": false, "type": "string" } } ] ``` This will add a new non-hidden string field with a `displayName` and `key` of **category**. This will affect existing instances of this template. ### Reorder fields The operation `reorderFields` reorders the list of fields in a template to match the requested field list. | Parameter | | | --- | --- | | fieldKeys | The new list of field keys in the requested order | ``` { "op": "reorderFields", "fieldKeys": ["field2", "field1", "field3"] } ``` This will reorder the fields for the template to have `field2` first, followed by `field1`, then `field3`. This will affect existing instances of this template. It will reorder the fields, yet keep the values of the fields intact. ## Field operations Field operations transform the schema of a template. The following is a list of operations that can be used in this API and can potentially change the data of any previously assigned templates. These changes will be logged as template changes but not as file changes. ### Edit a field The operation `editField` edits any number of the base properties of a field like the `displayName`, `description`, `key`, and `hidden` state. | Parameter | | | --- | --- | | data | An object representing the new properties to set for the field | | fieldKey | The key of the field to be edited | ``` { "op": "editField", "fieldKey": "category", "data": { "displayName": "Customer Group" } } ``` This will update the field `category` to have a new display name of **Customer Group**. If the key is changed, existing values of the specified field are migrated to the new key. The search index will be updated, yet it may take time depending on how many files are affected by the change. This may affect existing instances of this template. ### Remove a field The operation `removeField` removes a field from a template. | Parameter | | | --- | --- | | fieldKey | The key of the field to remove from the template | ``` { "op": "removeField", "fieldKey": "brand" } ``` This will remove the field `brand` from the template as well as all instances of the template. The search index will be updated, yet it may take time depending on how many files are affected by the change. This will affect existing instances of this template. ## Field Option Operations Both the [`enum`](g://metadata/fields/enum) and [`multiSelect`](g://metadata/fields/multi-select) metadata field types support some additional operations to change the options of the fields. | Operation | | | --- | --- | | addEnumOption | Adds an option to an enum field | | editEnumOption | Edits an enum field option | | reorderEnumOptions | Re-orders the options on an enum field | | removeEnumOption | Removes an enum field option | | addMultiSelectOption | Adds an option to a multiSelect field | | editMultiSelectOption | Edits a multiSelect field option | | reorderMultiSelectOptions | Re-orders the options on a multiSelect field | | removeMultiSelectOption | Removes a multiSelect field option | **Reference:** https://developer.box.com/guides/metadata/templates/update/ --- ## Untitled *Type: guide | Category: Mobile * Android The Box Android SDK provides native access to the Box API from within your Android project. As of May 31, 2023 Android SDK is no… # Android The [Box Android SDK](https://github.com/box/box-android-sdk) provides native access to the Box API from within your Android project. As of May 31, 2023 Android SDK is no longer supported. You can still use your existing Android SDK applications with no impact, but you won't receive new features, updates, or bug fixes. If you would like to continue getting the latest and greatest Android features, we recommend using Java SDK to build apps on Android. Refer to [this](https://github.com/box/box-java-sdk/blob/main/doc/android.md) documentation for more details. **Reference:** https://developer.box.com/guides/mobile/android/ --- ## Untitled *Type: guide | Category: Mobile * Android SDK Installation As of May 31, 2023 Android SDK is no longer supported. You can still use your existing Android SDK applications… # Android SDK Installation As of May 31, 2023 Android SDK is no longer supported. You can still use your existing Android SDK applications with no impact, but you won't receive new features, updates, or bug fixes. If you would like to continue getting the latest and greatest Android features, we recommend using Java SDK to build apps on Android. Refer to [this](https://github.com/box/box-java-sdk/blob/main/doc/android.md) documentation for more details. The Android SDK may be obtained through several methods: - Adding as a Maven or Gradle dependency - Cloning the source into your project - Downloading one of the precompiled JARs ## Add as a Maven dependency Add the following to your Maven dependencies. ``` <dependency> <groupId>com.box</groupId> <artifactId>box-android-sdk</artifactId> </dependency> ``` ## Add as a Gradle dependency Add the following to your `build.gradle` file. ``` dependencies { implementation 'com.box:box-android-sdk:4.2.3' } ``` ## Clone the source The Box Android SDK source code may be obtained by cloning or downloading the [project from Github](https://github.com/box/box-android-sdk/tree/master/box-content-sdk). ## Download precompiled JARs Precompiled JARs for the Android SDK may be obtained from the Github project [releases page](https://github.com/box/box-android-sdk/releases) If one of the precompiled JARs is being used, the Android SDK will also require the following dependency: `minimal-json v0.9.1` (for Maven: `com.eclipsesource.minimal-json:minimal-json:0.9.1`) **Reference:** https://developer.box.com/guides/mobile/android/install/ --- ## Untitled *Type: guide | Category: Mobile * iOS The Box iOS SDK provides native access to the Box API from within your iOS project. # iOS The [Box iOS SDK](https://github.com/box/box-ios-sdk) provides native access to the Box API from within your iOS project. **Reference:** https://developer.box.com/guides/mobile/ios/ --- ## Untitled *Type: quick-start | Category: Search * Add Metadata Template to a File Your metadata template needs to be applied to at least one file to ensure a result in step 4. There are two… # Add Metadata Template to a File Your metadata template needs to be applied to at least one file to ensure a result in step 4. There are two ways to do add a metadata template to a file: via the UI or via the API. ## UI To apply metadata to a file using the UI, navigate to a file and open the preview. Use the **Metadata** tab and click **Add**. Find the metadata template created in step 1 and select a value. Ensure you click **Save**. ## API To add a metadata template to a file you will need to use the [create metadata instance on a file endpoint](e://post-files-id-metadata-id-id/). You will also need the `scope` and `templateKey` template values from the previous step. Below is an example of what the API call looks like to apply the same metadata shown in the UI above. Due to scale considerations a 403 error will returns when the metadata template is applied to more than 10,000 files or folders. I applied my template to at least one file **Reference:** https://developer.box.com/guides/search/quick-start/apply-template-to-file/ --- ## Untitled *Type: quick-start | Category: Search * Create a Metadata Template There are two ways to create a new metadata template: via the Admin Console or via the API using an Admin Access… # Create a Metadata Template There are two ways to create a new metadata template: via the Admin Console or via the API using an Admin Access Token. If you already have a metadata template created that you would like to use you can skip to the next step. ## Admin Console To create a template via the Admin Console, navigate to: **Admin Console** > **Content** Tab > **Metadata** > **Create New** The metadata feature is reserved for Business Plus accounts and above. To upgrade your account, please contact your Box account team. Once you select **Create New**, you are brought to a form used to create a new template, which is shown below. Select a **Dropdown-Single Select** format. Selecting a Dropdown-Multi Select format will change the structure of you query later on in this quick-start. ## API Creating a metadata template via the API requires an [Access Token](g://authentication/tokens) associated with a Box Admin or Co-Admin with permission to **create and edit metadata templates for your company**. If you are not sure who your token is associated with, make an API call to the [get current user endpoint](e://get-users-me). The easiest way to obtain a token meeting these requirements is to log in as an Admin or Co-Admin, pull up the application in the [Developer Console](https://account.box.com/developers/console), and click **Generate Developer Token** under the **Configuration** tab. [Developer tokens](g://authentication/tokens/developer-tokens) are always be associated with the user logged into the Developer Console when the button is clicked. Using [Postman](https://postman.com/) and the [Box Postman Collection](g://tooling/postman), below is an example of what an API call looks like to create the same metadata template created above using the Admin Console. If you would like to use a different template format than a Dropdown-Single Select, you will need to consult our reference documentation, as the body of the API call will differ from the example above. The response to this API call provides crucial information you will need later. If you created your template via the UI, you will learn how to obtain this information in the next step. I created a metadata template **Reference:** https://developer.box.com/guides/search/quick-start/create-metadata-template/ --- ## Untitled *Type: quick-start | Category: Search * Search content using metadata The Box Metadata Query API enables programmatic search of Box content based strictly on applied custom… # Search content using metadata The Box Metadata Query API enables programmatic search of Box content based strictly on applied custom metadata values. The structure of a metadata query is similar to that of a SQL query and allows for Boolean operators, such as AND, OR, and NOT, as well as comparison or range operators, such as equal to, greater-than, and less-than. Some benefits of the Metadata Query API include: - no indexing delay; query immediately after metadata creations, updates, and deletions - ability to specify a sort order by one or more fields - no limitation on the number of characters that are queryable - queries return item properties and metadata instances ## Overview This guide will take you through the following steps. 1. [Create a metadata template](g://search/quick-start/create-metadata-template) 2. [Locate information about the metadata template](g://search/quick-start/locate-template-info) via API 3. [Apply the metadata template](g://search/quick-start/apply-template-to-file) to at least one file 4. [Construct a metadata query API call](g://search/quick-start/metadata-query-api) to obtain the content from step 3 I am ready to get started **Reference:** https://developer.box.com/guides/search/quick-start/ --- ## Untitled *Type: quick-start | Category: Search * Locate Information about a Metadata Template If you created your metadata template using the API and have the successful response on hand… # Locate Information about a Metadata Template If you created your metadata template using the API and have the successful response on hand, you can skip this step. If you created your metadata template via the Admin Console, you will need obtain an [Access Token](g://authentication/tokens) for an Admin or Co-Admin with permission to **Create and edit metadata templates for your company**. As mentioned in step 1, the easiest way to obtain a token meeting these requirements is to log in as an Admin or Co-Admin, pull up the application in the [Developer Console](https://account.box.com/developers/console), and click **Generate Developer Token** under the **Configuration** tab. Use this token to make an API call to the [list all metadata templates for enterprise endpoint](e://get-metadata-templates-enterprise/), as shown below. You should be able to find information about your template in the response. Specifically, note the `scope` and `templateKey`. I obtained the details about my template **Reference:** https://developer.box.com/guides/search/quick-start/locate-template-info/ --- ## Untitled *Type: quick-start | Category: Search * Use the Metadata Query API Finally, build a metadata query API call. Here is an example of what the body of the API call looks like: This… # Use the Metadata Query API Finally, build a [metadata query API call](e://post-metadata-queries-execute-read/). Here is an example of what the body of the API call looks like: ``` { "from": "enterprise_22201764.contact_role", "query": "departments = :departments", "query_params": {"departments": "legal"}, "ancestor_folder_id": "0", "fields": ["id"] } ``` This API call will return any file ID that meets the following criteria: - Has the Contact Role template applied - Has a value of departments is legal - Is located anywhere under the root folder, since "0" is the `ancestor_folder_id` As you can see below, this results in a successful call showing information about the file we added the template to in step 2. I found my content using a search query **Reference:** https://developer.box.com/guides/search/quick-start/metadata-query-api/ --- ## Untitled *Type: quick-start | Category: Search * Next Steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. Created a metadata template… # Next Steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. 1. [Created a metadata template](g://search/quick-start/create-metadata-template) 2. [Located information about the metadata template](g://search/quick-start/locate-template-info) from step 1 via API 3. [Added a metadata template](g://search/quick-start/apply-template-to-file) to at least one file 4. [Used the metadata query API](g://search/quick-start/metadata-query-api) to locate the file(s) from step 3 ## Next Steps We recommend the following resources to learn more: - [Metadata query guide](g://metadata/queries) - Review [common errors](g://metadata/queries/errors) and [limitations](g://metadata/queries/limitations) - Reference documentation for the [metadata query](e://post-metadata-queries-execute-read) API Our SDKs that support the metadata query API: - [Python SDK](https://github.com/box/box-python-sdk/blob/main/docs/usage/search.md#metadata-query) - [.NET SDK](https://github.com/box/box-node-sdk/blob/3fcc0d8bbd1ca11f1a3a78d741e4572718af53f0/docs/metadata.md#query) - [iOS SDK](https://github.com/box/box-ios-sdk/blob/c5ff8396e28c31fcf3c433f1b9e8f2f0d7a0e0db/docs/usage/search.md#metadata-search) - [Java SDK](https://github.com/box/box-java-sdk/blob/5e3a96c903fffa198c97e981ce75765a69bd6cb6/doc/metadata_template.md#execute-metadata-query) - [Node](https://github.com/box/box-node-sdk/blob/3fcc0d8bbd1ca11f1a3a78d741e4572718af53f0/docs/metadata.md#query) **Reference:** https://developer.box.com/guides/search/quick-start/next-steps/ --- ## Untitled *Type: guide | Category: Security * Find Terms for Collaboration Information about the Terms of Service that is in effect for any Collaboration can be inspected by calling the… # Find Terms for Collaboration Information about the Terms of Service that is in effect for any [Collaboration](r://collaboration) can be inspected by calling the [`GET /collaborations/:id`](e://get-collaborations-id) API and passing the query parameter `fields=acceptance_requirements_status`. ``` curl -X GET https://api.box.com/2.0/collaborations/2342342?fields=acceptance_requirements_status \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` The resulting response will include a new `acceptance_requirements` object that includes a mini `terms_of_service` object. ``` { "type": "collaboration", "id": 2342342>, "acceptance_requirements": { "terms_of_service": { "type": "terms_of_service", "id": 6766677 } } } ``` This information is only returned if the Terms of Service for external users is enabled for the enterprise, and the user making the request has the [permission](g://security/terms-of-service/permissions) to see the Terms of Service. This holds true for both admin and end users, even though admins can generally view Terms of User information via the API even if the specific Terms of Service type is turned off. If the Terms of Service type is not enabled, the API will return an empty result. ``` { "type": "collaboration", "id": 2342342>, "acceptance_requirements": { "terms_of_service": null } } ``` The `terms_of_service` information is returned within the `acceptance_requirements` even if they have already been accepted by the user. **Reference:** https://developer.box.com/guides/security/terms-of-service/for-colaboration/ --- ## Untitled *Type: guide | Category: Security * Application Flow In general, applications use Terms of Services as follows. When an application, authenticated as a user, tries to access an… # Application Flow In general, applications use Terms of Services as follows. When an application, authenticated as a user, tries to access an item in Box that requires the user to have accepted the relevant Terms of Service it receives a `TERMS_OF_SERVICE_REQUIRED` error. ``` { "type": "error", "status": 400, "code": "terms_of_service_required", "context_info": { "tos_id": 261346614, "tos_user_status_id": 4562456 }, "help_url": "https://developer.box.com/guides/api-calls/permissions-and-errors/common-errors/", "message": "User must accept custom terms of service before action can be taken", "request_id": "ADF7722DD" } ``` The application requests the Terms of Service's information by calling [`GET /terms_of_services/:id`](e://get_terms_of_services_id). ``` { "id": 261346614, "type": "terms_of_service", "status": "enabled", "enterprise": { "id": 11446498, "type": "enterprise", "name": "Acme Inc." }, "tos_type": "managed", "text": "By using this service, you agree to ...", "created_at": "2012-12-12T10:53:43-08:00", "modified_at": "2012-12-12T10:53:43-08:00" } ``` The application can then show the text from the Terms of Service to the user. When the user accepts or rejects the terms, it makes a call to either [`PUT /terms_of_service_user_statuses/:id`](e://put_terms_of_service_user_statuses_id) or [`POST /terms_of_service_user_statuses`](e://post_terms_of_service_user_statuses) depending on if the initial error returned a `tos_user_status_id` in the response. **Reference:** https://developer.box.com/guides/security/terms-of-service/flow/ --- ## Untitled *Type: guide | Category: Security * Terms of Service The Box API allows administrators to configure Terms of Services for working on Box, and for users to accept & re-accept… # Terms of Service The Box API allows administrators to configure Terms of Services for working on Box, and for users to accept & re-accept Terms of Services for custom applications. ## Terminology ### Terms of Services A Terms of Service is a enterprise-level record that represent the conditions within which all users are allowed to work with an enterprise's data in Box. There are currently two types of Terms of Service for any enterprise that can be enabled independently. The **Managed Terms of Service** can be enabled for the enterprise's own users, where the **External Terms of Service* can be enabled for users from other enterprises that collaborated in on the primary enterprise's data. ## Terms of Service User Statuses A Terms of Service User Status represents the status of the Terms of Service acceptance for a specific user. There is exactly one Terms of Service User Status for any given combination of Terms of Service and a user. There are multiple Terms of Service User Statuses for any Terms of Service, specifically one for each each user. There could be multiple Terms of Service User Statuses for a given user. The user could accept or reject multiple External Terms of Services for different enterprises they have been collaborated into, in addition to accepting or rejecting their own enterprise’s Managed Terms of Service. ## APIs Applications that are authenticated as a Box Admin that has the Edit settings for your company permissions can view, create, and edit Terms of Services for their enterprise via the API. - [`GET /terms_of_services/:id`](e://get-terms-of-services-id): To get the information for a specific Terms of Service - [`GET /terms_of_services`](e://get-terms-of-services): To get a list of all the Terms of Services used within an enterprise, either for managed or external users. - [`POST /terms_of_services`](e://post-terms-of-services): To create Terms of Service settings for either an external or managed user. [`PUT /terms_of_services/:id`](e://put-terms-of-services-id): To update a specific Terms of Service setting Additionally, application can view and accept Terms of Services for a regular user via the API. - [`GET /terms_of_service_user_statuses`](e://get-terms-of-service-user-statuses): To get a list of all the Terms of Services for a user - [`POST /terms_of_service_user_statuses`](e://post-terms-of-service-user-statuses): To accept or reject a specific Terms of Service for the first time - [`PUT /terms_of_service_user_statuses/:id`](e://put-terms-of-service-user-statuses-id): To accept or reject a specific Terms of Service that had been previously accepted or rejected. ## Scopes The following scopes should be granted to the application in order to take the outlined actions. - **Manage Enterprise Properties**: Required to enable or edit the enterprise's settings for Terms of Services as well as to view them for external users. - **Manage Users**: Required to accept Terms of Services for other users. **Reference:** https://developer.box.com/guides/security/terms-of-service/ --- ## Untitled *Type: guide | Category: Box Skills * Handle Skills Payloads Within the application or site that is set up as your invocation URL you will generally need to perform two tasks… # Handle Skills Payloads Within the application or site that is set up as your [invocation URL](guide://skills/invocation-url) you will generally need to perform two tasks. - [Handle the Skill payload](guide://skills/handle/payload) - Every time a Box Skills detects a new file is uploaded, copied, or moved to a folder it sends a JSON notification to the invocation URL. This URL needs to be parsed. - [Apply a Skill Card to a file](guide://skills/handle/metadata) - The metadata returned from the processing service will need to be stored back as metadata on the file that triggered the event. **Reference:** https://developer.box.com/guides/skills/handle/ --- ## Untitled *Type: guide | Category: Security * Permissions The following is a list of permissions users, admins, and co-admins need to have when working with Terms of Services and Terms… # Permissions The following is a list of permissions users, admins, and co-admins need to have when working with Terms of Services and Terms of Service Statuses. ## Terms of Service An end user is considered subject to Terms of Service when: - User belongs to or is collaborated into an enterprise that has a Terms of Service enabled The type of Terms of Service reflects the user's relationship to the Enterprise - A managed Terms of Service for a user that is part of the same enterprise - An external Terms of Service for users collaborating into the enterprise Terms of Service settings can be viewed by an end user if: - The user is subject to a Terms of Service; and - The Terms of Service Type is enabled on the enterprise A Terms of Service's settings can be viewed by an enterprise admin or co-admin if: - They have **View settings for your company** permissions - The application has the **Manage enterprise properties** scope enabled - The Terms of Service belongs to their enterprise Terms of Service settings can be edited by an enterprise admin or co-admin if: - They have **'Edit settings for your company** permissions - The application has the **Manage enterprise properties** scope enabled - The Terms of Service belongs to their enterprise Enterprise admins and co-admins can view, create, and edit Terms of Service settings for both external and managed Terms of Service without having accepted managed the managed Terms of Service for their own enterprise. ## Terms of Service User Status Terms of Service User Status can be viewed and edited by an end user if: - The User Status belongs to the end user - The Terms of Service type is enabled on the enterprise - The end user is subject to the Terms of Service Terms of Service User Statuses belonging to other users can be viewed by enterprise admins and co-admins if: - They have **Manager users** permissions - The application has the **Manage users** scope enabled - The Terms of Service belongs to their enterprise - They have accepted the managed Terms of Service for their own enterprise, if applicable Terms of Service User Status belonging to other users can be edited by enterprise admins and co-admins if: - They have **Manager users** permissions - The application has the **Manage users** scope enabled - The end user is subject to the Terms of Service - The end user is not an admin or co-admin - The Terms of Service belongs to their enterprise - They have accepted the managed Terms of Service for their own enterprise, if applicable An end user cannot accept, reject, view external Terms of Service settings for an enterprise they are collaborating into until the end user accepts the managed Terms of service for their own enterprise, where applicable. Trying to do so will result in a `TERMS_OF_SERVICE_REQUIRED` error. **Reference:** https://developer.box.com/guides/security/terms-of-service/permissions/ --- ## Untitled *Type: guide | Category: Box Skills * Box Skills Payload When a new file is uploaded, copied, or moved to a folder monitored by a Skills app, the invocation URL that was… # Box Skills Payload When a new file is uploaded, copied, or moved to a folder monitored by a Skills app, the invocation URL that was specified during application setup and authentication will receive an event payload from Box. The event payload will contain all information needed to read in the content of the uploaded file to send to a processing system, such as a machine learning system, and to write metadata back to the file once the processing system has completed. Example payload and reference ## Access Tokens Every Skills payload includes a set of Access Tokens that can be used to access the file that triggered the event. ``` { ... "token": { "write": { "access_token": "c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ", "expires_in": 1540924150, "restricted_to": ..., "token_type": "bearer" }, "read": { "access_token": "Z3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQc3FIOG9vSGV4VHo4QzAyg5T1JvNnJo", "expires_in": 1540924150, "restricted_to": ..., "token_type": "bearer" } }, ... } ``` The `token.write.access_token` can be used to write metadata to the file, while the `token.read.access_token` can be only used to read the file content. The read-only token is useful when creating a download URL for the file which can then be shared with other services. ## Downloadable file URL Many machine learning services support directly passing a file URL to that service for processing. To create a download URL for a Box file, you will need to parse the `token.read.access_token` as well as the `source.id` from the event payload. ``` { ... "source": { "type": "file", "id": 12345, }, "token": { ... "read": { "access_token": "Z3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQc3FIOG9vSGV4VHo4QzAyg5T1JvNnJo", "expires_in": 1540924150, "restricted_to": ..., "token_type": "bearer" } }, ... } ``` The download URL for a file can be constructed as follows. ``` https://api.box.com/2.0/files/{source.id}/content?access_token={token.read.access_token} ``` In our example, this URL would be as follows. ``` https://api.box.com/2.0/files/12345/content?access_token=Z3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQc3FIOG9vSGV4VHo4QzAyg5T1JvNnJo ``` **Reference:** https://developer.box.com/guides/skills/handle/payload/ --- ## Untitled *Type: guide | Category: Box Skills * Skills Cards Metadata Once a processing service has determined the metadata for the file, your application can write that data back to the… # Skills Cards Metadata Once a processing service has determined the metadata for the file, your application can write that data back to the file stored on Box as metadata. This process involves the following steps. 1. Prepare the Skill Cards metadata 2. Write the metadata to the file ## Prepare Skill Cards metadata The Skills metadata uses a globally available metadata template called `boxSkillsCards`. This template follows a specific format for the JSON structure that will be stored on the associated files. Box currently supports 4 kinds of cards. | | | | | --- | --- | --- | | Keyword | Displays a list of keywords next to the file. | | | Timeline | Displays a set of text/images, and when clicked shows when those images appear in a timeline. | | | Transcript | Displays a transcript with the corresponding timestamps. | | | Status | Displays a status to the user, which can be used to inform the user of the status of the Skill while it is processing the file. | | ## Write metadata cards to file To write one or more cards to a file, you can use the [`POST /files/:id/metadata/global/boxSkillsCards`](e://post_files_id_metadata_global_boxSkillsCards) API and pass along a list of Box Skill `cards`. ``` curl -X POST https://api.box.com/2.0/files/12345/metadata/global/boxSkillsCards \ -H 'Authorization: Bearer <ACCESS_TOKEN>' \ -H 'Content-Type: application/json' \ -d '{ "cards": [{ "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } }], }' ``` ``` const metadata = { cards: [{ "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } }] } client.files.addMetadata('12345', 'global', 'boxSkillsCards', metadata) .then(metadata => { // ... }) ``` ``` metadata = { cards: [{ "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } }] } client.file(file_id='12345').metadata(scope='global', template='boxSkillsCards').create(metadata) ``` ``` BoxFile file = new BoxFile(api, "12345"); Metadata metadata = new Metadata() file.createMetadata("global", "boxSkillsCards", metadata); ``` ``` var metadataValues = new Dictionary<string, object>() { cards: [{ "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } }] }; Dictionary<string, object> metadata = await client.MetadataManager .CreateFileMetadataAsync(fileId: "12345", metadataValues, "global", "boxSkillsCards"); ``` If Box Skill cards have already been applied to this file, this API call will return an error with a HTTP status code of `409`. ## Update metadata card on file If Box Skill cards have already been applied to to a file then it can be updated using the [`PUT /files/:id/metadata/global/boxSkillsCards`](e://put_files_id_metadata_global_boxSkillsCards) API. This API accepts a number of operations (`op`) to perform, and each operation can be used to replace a card at a position (`path`). ``` curl -X PUT https://api.box.com/2.0/files/12345/metadata/global/boxSkillsCards \ -H 'Authorization: Bearer <ACCESS_TOKEN>' \ -H 'Content-Type: application/json-patch+json' \ -d '[ "op": "replace", "path": "/cards/0", "value": { "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } } ]' ``` ``` const updates = [ { 'op': 'replace', 'path': '/cards/0', 'value': { "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } } } ] client.files.updateMetadata('12345', 'global', 'boxSkillsCards', updates) .then(metadata => { // ... }) ``` ``` file_metadata = client.file(file_id='12345').metadata(scope='global', template='boxSkillsCards') card = { "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } } updates = file_metadata.start_update() updates.replace('/cards/0', card) file_metadata.update(updates) ``` ``` BoxFile file = new BoxFile(api, "12345"); Metadata metadata = new Metadata() file.updateMetadata("global", "boxSkillsCards", metadata); ``` ``` var card = new Dictionary<string, object>() { "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } }; var updates = new List<BoxMetadataUpdate>() { new BoxMetadataUpdate() { Op = MetadataUpdateOp.replace, Path = "/cards/0", Value = card } }; Dictionary<string, object> updatedMetadata = await client.MetadataManager .UpdateFileMetadataAsync("12345", updates, "global", "boxSkillsCards"); ``` **Reference:** https://developer.box.com/guides/skills/handle/metadata/ --- ## Untitled *Type: guide | Category: Box Skills * Setup Setting up a Custom Skill is a multi-step process. Prerequisites To set up a Platform App using OAuth 2.0 authentication, you will… # Setup Setting up a Custom Skill is a multi-step process. ## Prerequisites To set up a Platform App using OAuth 2.0 authentication, you will need to ensure you have access the [Developer Console](https://app.box.com/developers/console) from your Box enterprise account. Alternatively, you may sign up for a [developer account](https://account.box.com/signup/n/developer). ## App creation steps ### 1. Log in to the Developer Console Log into Box and navigate to the [Developer Console](https://app.box.com/developers/console). Select **Create New App**. ### 2. Create a Custom Skill Select **Box Custom Skill** option from the list of application types. A modal will appear to prompt the next step. ### 3. Provide a name Finally, select a unique name for your application and click **Create Platform App**. ## Approval You must select a folder that will trigger your skill before you can start using it. Learn more about approving Custom Skills ## Basic configuration Before a Custom Skill can be enabled enabled on a folder, you must complete some additional configuration. ### Invocation URL For every file uploaded, copied, or moved into the selected folder, your skill will send a payload to a remote URL. This URL is called the invocation URL. The Invocation URL can be any HTTP endpoint representing a server, development machine, or serverless function. The only requirement is that the URL is publicly available and accessible by Box servers. For this reason, `localhost` is not a valid address. To set up the Invocation URL, navigate to the **Configuration** tab of the [Developer Console](https://app.box.com/developers/console) and scroll down to the "Invocation URL" section. Fill in a secure HTTPS address and save the form. The invocation URL is now configured. ### File Extensions By default a Custom Skill will trigger for any file type in the folder. To specify only selected file extensions to trigger the skill, navigate to the **Configuration** tab of the [Developer Console](https://app.box.com/developers/console) and scroll down to the **File Extensions** section. **Reference:** https://developer.box.com/guides/skills/handle/setup/ --- ## Untitled *Type: quick-start | Category: SSO & App users * Configure Box Once we have created a login experience with Okta we need to have a Box application available that will permit us to use the… # Configure Box Once we have created a login experience with Okta we need to have a Box application available that will permit us to use the Box APIs to search for and create users that are associated with the Okta user account. ## Set up a Box app # Create a new Box app Create and configure a new Box JWT application to start with a clean user list. # Use an existing approved app Use one of your existing admin approved Box JWT applications from the Box developer console. # Create a new Box app To create a new Box application that may be used to call the Box APIs, use the following steps. 1. Go to the [Developer Console](https://cloud.app.box.com/developers/console) 2. Select **Create Platform App** 3. Select **Platform App** as the type of application to create, and click **Next** 4. Select **OAuth 2.0 with JWT** as the authentication method, and click **Next** 5. Give your Box app a unique name and click **Create App** 6. Go to the app's configuration by clicking **View Your App**. Scroll to the **Required Access Scopes** section of the same screen and ensure that at least the following scopes are enabled: - Read and write all files and folders stored in Box - Manage Users 7. Under **Advanced Features** ensure that both options are enabled to perform actions as users and generate user access tokens. 8. At the top of the page click the button to **Save Changes** Once the application is created it will still need to be approved by an enterprise admin before you will be able to make calls to the Box APIs. Follow [this guide](g://authorization/custom-app-approval) to have the application approved in your enterprise. # Use an Existing JWT Box application If you have an existing JWT based Box application in your [developer console](https://cloud.app.box.com/developers/console) that you would like to use, ensure that the following options are set in the **Configuration** section of your application. - Authentication Method: Should be set to OAuth 2.0 with JWT (Server Authentication). Application Scopes: Set at least the following scopes. - Read and write all files and folders stored in Box - Manage Users Advanced Features: Both options should be enabled to perform actions as users and generate user access tokens. ## Download Required Data To begin working with the Box SDKs used in this tutorial, you will need the application configuration file from the **Configuration** page of your application. This will include all information needed to verify your application to start making API requests with the Box SDKs. Within the **Add and Manage Public Keys** section of the **Configuration** page, click to **Generate a Public/Private Keypair**. This will send you through 2FA verification before downloading the configuration file for your application. Store that file as `config.json` in a location accessible by your application. ## Summary - You created a new, or are using an existing, Box app which is approved by an enterprise admin. - You downloaded your application configuration file and stored it in a location accessible by your application. I downloaded my application configuration file **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/configure-box/ --- ## Untitled *Type: quick-start | Category: SSO & App users * Configure Okta Our next step in the Okta / Box integration is to create and configure the Okta application and users, then extract a few… # Configure Okta Our next step in the Okta / Box integration is to create and configure the Okta application and users, then extract a few pieces of information that we will need to connect to Okta in our application. For this tutorial we will be starting with a blank Okta application and user dashboard to avoid any negative effects on existing installations that may be in place, and to ensure that we have admin rights to the instance. ## Create an Okta Application Starting from the [Okta developer site](https://developer.okta.com/), sign up for a new developer account, or log in under your personal account if you already have one. If you're logging in with an existing account, you should see the Okta dashboard. Click on the **Admin** button at the top right. If you've created a new developer account rather than logging into an existing account, you will have already be redirected to the admin dashboard. You should now see the admin panel. Click on the **Applications** option at the top. On the application page, click the **Add Application** button. Select **Web** as the application type and click the **Next** button. Okta employs both [OAuth 2](https://oauth.net/2/) and [OpenID Connect](https://openid.net/) (OIDC) for application authorization and user authentication, respectively. The OpenID Connect integration allows us to use baked in OIDC connectors within a number of popular language frameworks to simplify application and user management by handling the callback routes and providing methods for logging in, logging out, and protecting routes into your application. To simplify this first integration, we're going to use the default callback routes and settings for the language and framework OIDC connector. Depending on your preferred integration type, the configuration settings will slightly change. Fill out the application details with the following configuration settings: - Name: Any - Base URIs: `http://localhost:3000/` - Login redirect URIs: `http://localhost:3000/authorization-code/callback` - Logout redirect URIs: `http://localhost:3000/logout` - Grant type allowed: Only **Authorization Code** selected - Name: Any - Base URIs: `http://localhost:8080/` - Login redirect URIs: `http://localhost:8080/authorization-code/callback` - Logout redirect URIs: `http://localhost:8080/logout` - Grant type allowed: Only **Authorization Code** selected - Name: Any - Base URIs: `http://127.0.0.1:5000/` - Login redirect URIs: `http://127.0.0.1:5000/oidc/callback` - Logout redirect URIs: `http://127.0.0.1:5000/logout` - Grant type allowed: Only **Authorization Code** selected - Name: Any - Base URIs: `https://localhost:5001/` - Login redirect URIs: `https://localhost:5001/authorization-code/callback` - Logout redirect URIs: `https://localhost:5001/logout` - Grant type allowed: Only **Authorization Code** selected # Incomplete previous step Please select a preferred language / framework in step 1 to get started. Click the **Done** button to create the application and be dropped on to the general settings of the application. ## Copy Application Credentials Using the configuration files set up in the last step, we next have to add in the Okta application org and app details within the files. Most Okta application information can be found on the general settings page, with the exception of the `Org URL` that is used in the configuration URIs to reference back to your Okta organization. To obtain the `Org URL`, go to the dashboard of your Okta admin console. The `Org URL` will be in the top right corner of the screen. Depending on the language and framework previously chosen, we'll set up the appropriate configuration files. - Open `config.json` within the local application directory in your preferred editor. Update the following line items with the appropriate Okta configuration info: - `oktaClientId`: Obtained from the **Client Credentials** section of the application general settings. - `oktaClientSecret`: Obtained from the **Client Credentials** section of the application general settings. - `oktaOrgUrl`: Obtained from the top right of the main admin dashboard page. Save the file. Your `config.json` file should look similar to the following. ``` const oktaClientId = exports.oktaClientId = '0oa48567frkg5KW4x6'; const oktaClientSecret = exports.oktaClientSecret = 'cugDJy2ERfIQHDXv-j2134DfTTes-Sa3'; const oktaOrgUrl = exports.oktaOrgUrl = 'YOURDOMAIN.okta.com'; const oktaBaseUrl = exports.oktaBaseUrl = 'http://localhost:3000'; const oktaRedirect = exports.oktaRedirect = '/authorization-code/callback'; ``` Open the `/src/main/resources/application.properties` file and update the following lines: - `okta.oauth2.issuer`: Your Org URL, obtained from the top right of the main admin dashboard page, followed by `/oauth2/default`. For example, if your Org URL was `https://dev-123456.okta.com`, the issuer string should be `https://dev-123456.okta.com/oauth2/default`. - `okta.oauth2.clientId`: Obtained from the **Client Credentials** section of the application general settings. - `okta.oauth2.clientSecret`: Obtained from the **Client Credentials** section of the application general settings. Save the file Your `/src/main/resources/application.properties` file should look similar to the following. ``` okta.oauth2.redirect-uri=/authorization-code/callback okta.oauth2.issuer=https://YOURDOMAIN.okta.com/oauth2/default okta.oauth2.clientId=0oa48567frkg5KW4x6 okta.oauth2.clientSecret=cugDJy2ERfIQHDXv-j2134DfTTes-Sa3 security.oauth2.sso.loginPath=/authorization-code/callback ``` In addition to the standard configuration information for the org and app, the Python / Flask integration requires an additional auth token. To create an auth token: - Go to the **API** -> **Token** section of the Okta admin dashboard. - Click the **Create Token** button. - Enter a name for the token and click **Create**. - Copy the token that is generated. Next, update the local application configuration file. - Open `config.py` within the local application directory in your preferred editor. Update the following line items with the appropriate Okta configuration info: - `okta_client_secret`: Obtained from the **Client Credentials** section of the application general settings. - `okta_org_url`: Obtained from the top right of the main admin dashboard page. - `okta_auth_token`: The token created above. Save the file. Your `config.py` file should look similar to the following. ``` okta_client_id = '0oa48567frkg5KW4x6' okta_client_secret = 'cugDJy2ERfIQHDXv-j2134DfTTes-Sa3' okta_org_url = 'http://YOURDOMAIN.okta.com' okta_auth_token = '01KkTQTRfs1yKLr4Ojy26iqoIjK_4fHyq132Dr5T' okta_callback_route = '/oidc/callback' ``` Lastly, update the Flask configuration file - Open `client_secrets.json` within the local application directory in your preferred editor. Update the following line items with the appropriate Okta configuration info: - `client_id`: Obtained from the **Client Credentials** section of the application general settings. - `client_secret`: Obtained from the **Client Credentials** section of the application general settings. - `auth_uri`: Your Org URL, obtained from the top right of the main admin dashboard page, followed by `/oauth2/default/v1/authorize`. For example, if your Org URL was `https://dev-123456.okta.com`, the issuer string should be `https://dev-123456.okta.com/oauth2/default/v1/authorize`. - `token_uri`: Your Org URL, obtained from the top right of the main admin dashboard page, followed by `/oauth2/default/v1/token`. For example, if your Org URL was `https://dev-123456.okta.com`, the issuer string should be `https://dev-123456.okta.com/oauth2/default/v1/token`. - `issuer`: Your Org URL, obtained from the top right of the main admin dashboard page, followed by `/oauth2/default`. For example, if your Org URL was `https://dev-123456.okta.com`, the issuer string should be `https://dev-123456.okta.com/oauth2/default`. - `userinfo_uri`: Your Org URL, obtained from the top right of the main admin dashboard page, followed by `/oauth2/default/userinfo`. For example, if your Org URL was `https://dev-123456.okta.com`, the issuer string should be `https://dev-123456.okta.com/oauth2/default/userinfo`. Save the file. Your `client_secrets.json` file should look similar to the following. ``` { "web": { "client_id": "0oa48567frkg5KW4x6", "client_secret": "cugDJy2ERfIQHDXv-j2134DfTTes-Sa3", "auth_uri": "https://YOURDOMAIN.okta.com/oauth2/default/v1/authorize", "token_uri": "https://YOURDOMAIN.okta.com/oauth2/default/v1/token", "issuer": "https://YOURDOMAIN.okta.com/oauth2/default", "userinfo_uri": "https://YOURDOMAIN.okta.com/oauth2/default/userinfo", "redirect_uris": [ "http://127.0.0.1:5000/oidc/callback" ] } } ``` - Open `Startup.cs` within the local application directory in your preferred editor. Update the following line items within the `ConfigureServices` method with the appropriate Okta configuration info: - `OktaDomain`: Obtained from the top right of the main admin dashboard page. - `ClientId`: Obtained from the **Client Credentials** section of the application general settings. - `ClientSecret`: Obtained from the **Client Credentials** section of the application general settings. Save the file. Your `ConfigureServices` method should look similar to the following. ``` services.AddControllersWithViews(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OktaDefaults.MvcAuthenticationScheme; }) .AddCookie() .AddOktaMvc(new OktaMvcOptions { OktaDomain = "https://YOURDOMAIN.okta.com", ClientId = "0oa48567frkg5KW4x6", ClientSecret = "cugDJy2ERfIQHDXv-j2134DfTTes-Sa3" }); ``` # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Create a User Our last step in the Okta setup is to create a test user that we will use to log in to the application. 1. Go to the **Users** section of the Okta admin dashboard. 2. Click on the **Add Person** button. 3. Enter all appropriate user info. Under password, select **Set by admin** and input a password for the user. Also deselect the **User must change password on first login** option. You will use the username and password to log in. These settings will only be used for testing purposes and are not best practices for user creation and security. 4. Click the **Save** button to create the user. ## Summary - You created an Okta application. - You updated the Okta configuration information in the local application. - You created a test Okta user. I've created my Okta app and set up user / local configuration **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/configure-okta/ --- ## Untitled *Type: quick-start | Category: SSO & App users * Connect Okta identities to Box App Users in a web app Okta is a popular access management and identity platform used by companies to provide… # Connect Okta identities to Box App Users in a web app [Okta](https://www.okta.com/) is a popular access management and identity platform used by companies to provide a unified method for managing and authenticating into multiple applications with a single set of credentials and a single secure dashboard. When connected to a custom Box application, the [Okta APIs](https://developer.okta.com/) may be used to provide a single login mechanism to identify users within the Box application, allowing you to have a unified experience between your unified identity system (Okta) and the Box APIs. ## Overview This quick start guide will walk you through how to programmatically use Okta to log in to a Box application, provision an app user in Box that is linked to the Okta user, then make Box API calls on behalf of that user. This will take you through the following steps. 1. [Scaffold your application code](g://sso-identities-and-app-users/connect-okta-to-app-users/scaffold-application-code) so that we have a web application that we can log in to. 2. [Setup and configure your Okta application](g://sso-identities-and-app-users/connect-okta-to-app-users/configure-okta) and create a first user that we can use to log into the web app with, and eventually create a Box account for. 3. [Setup and configure your Box application](g://sso-identities-and-app-users/connect-okta-to-app-users/configure-box) so that we can connect your web application to Box. 4. [Create a log in flow for your application](g://sso-identities-and-app-users/connect-okta-to-app-users/logging-into-app), allowing the Okta user to log in to your web application. 5. [Find an existing Box user, and optionally create a Box user](g://sso-identities-and-app-users/connect-okta-to-app-users/find-or-create-box-users) the first time that Okta user logs into your web application. 6. [And finally, run the application](g://sso-identities-and-app-users/connect-okta-to-app-users/run-the-app) and the see the complete flow in action. At the end of the tutorial we will output a single message to the browser. If this is the first time an Okta user logs in to Box via the application, an associated Box user will be created and the message `New user created: {{USERNAME}}` will be output to the browser. When attempting to log in with this user in subsequent attempts, a message stating `Hello {{USERNAME}}` will now be output to the browser. To simplify this guide we will not create any user interface for the web application. Instead we will provide some output via the application console / terminal and directly as text output in the browser. I am ready to get started **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/ --- ## Untitled *Type: quick-start | Category: SSO & App users * Find or create Box app users At this point we have application code that will handle traffic from users visiting, forward them to Okta to… # Find or create Box app users At this point we have application code that will handle traffic from users visiting, forward them to Okta to login, provide Okta user information, before finally handing off to a yet to be created handler for Box. This section will cover the final Box components: - Validating if an Okta user has an associated Box app user account. - Creating a new app user for the associated Okta record if they don't. - Fetching tokens for the Box user to make user-specific API calls. ## Create Platform App Users Before validating users we need a method for creating an associated Box user account if one doesn't already exist for the Okta user. In your local application directory, load the `server.js` file created in step 1. Add the following `box` object into the file and save. ``` const box = (() => { const configJSON = JSON.parse(fs.readFileSync(path.resolve(__dirname, './config.json'))); const sdk = boxSDK.getPreconfiguredInstance(configJSON); const client = sdk.getAppAuthClient('enterprise'); let oktaRecord = {}; let userId = ''; let userClient; function validateUser(userInfo, res) { // TODO: VALIDATE USER } function createUser(res) { // TODO: CREATE USER } return { validateUser, createUser }; })(); ``` This object defines a number of items: - Configuration: A new instance of the Box Node SDK is instantiated and made available to the object functions, along with a number of variables. - `validateUser` function: Will house the code to validate whether a Box user exists for an associated Okta user. - `createUser` function: Creates a new Box user bound to the associated Okta user ID. With that structure defined, replace the `// TODO: CREATE USER` section with the following code. ``` const spaceAmount = 1073741824; // ~ 1gb client.enterprise.addAppUser( this.oktaRecord.name, { space_amount: spaceAmount, external_app_user_id: this.oktaRecord.sub } ).then(appUser => { res.send(`New user created: ${appUser.name}`); }); ``` This code will create a new Box app user and will set the `external_app_user_id` parameter of the user object to the unique Okta user ID, which will define the binding between the two user records. In your local application directory, load the `/src/main/java/com/box/sample/Application.java` file created in step 1, or similar directory if an alternate application name was used. Within the `public class Application` definition, add the following methods: ``` static String validateUser(OidcUser user) throws IOException { // TODO: VALIDATE USER } static String createUser(OidcUser user) { // TODO: CREATE USER } ``` These methods will handle the Box user validation and creation. Breaking them down: - `validateUser`: Will house the code to validate whether a Box user exists for an associated Okta user. - `createUser`: Creates a new Box user bound to the associated Okta user ID. With those methods defined, replace `# TODO: CREATE USER` with the following code: ``` String oktaName = (String) user.getAttributes().get("name"); Object oktaSub = user.getAttributes().get("sub"); CreateUserParams params = new CreateUserParams(); params.setExternalAppUserId((String) oktaSub); BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, oktaName, params); return "New User Created: " + createdUserInfo.getName(); ``` This code will create a new Box app user and will set the `external_app_user_id` parameter of the user object to the unique Okta user ID, which will define the binding between the two user records. In your local application directory, load the `server.py` file created in step 1. Add the following `Box` class object to the existing code, below the route definitions. ``` # Box user class class Box(object): def __init__(self): # Instantiate Box Client instance auth = JWTAuth.from_settings_file('../config.json') self.box_client = Client(auth) # Validate if Box user exists def validateUser(self, g): # TODO: VALIDATE USER # Create new Box user def createUser(self, ouser): # TODO: CREATE USER ``` This class defines: - `init`: When initialized, a new instance of the Box Python SDK is instantiated and made available to the object methods. - `validateUser` method: Accepting a user object as input, this will house the code to validate whether a Box user exists for an associated Okta user. - `createUser` method: Accepting a user object as input, this creates a new Box user bound to the associated Okta user ID. With that class defined, replace the `# TODO: CREATE USER` section with the following code. ``` user_name = f'{ouser.profile.firstName} {ouser.profile.lastName}' uid = ouser.id space = 1073741824 user = self.box_client.create_user(user_name, None, space_amount=space, external_app_user_id=uid) return f'New user created: {user_name}' ``` This code will create a new Box app user and will set the `external_app_user_id` parameter of the user object to the unique Okta user ID, which will define the binding between the two user records. Within the `Controllers` > `AccountController.cs` file, inside the associated `AccountController` class, add the following method. ``` static async Task validateUser(string name, string sub) { // Configure Box SDK instance var reader = new StreamReader("config.json"); var json = reader.ReadToEnd(); var config = BoxConfig.CreateFromJsonString(json); var sdk = new BoxJWTAuth(config); var token = sdk.AdminToken(); BoxClient client = sdk.AdminClient(token); // Search for matching Box app user for Okta ID BoxCollection<BoxUser> users = await client.UsersManager.GetEnterpriseUsersAsync(externalAppUserId:sub); System.Diagnostics.Debug.WriteLine(users.TotalCount); if (users.TotalCount > 0) { // TODO: VALIDATE USER } else { // TODO: CREATE USER } } ``` Within the code block a new Box .NET SDK client is created using the `config.json` file downloaded in step 2. In the case of this code sample, that `config.json` file is stored at the root of the local application directory. That client is then used to search all users in the Box enterprise, passing in the Okta `sub` unique ID as the `externalAppUserId` search parameter. The number of users returned is then checked to see if a valid user was found. With that structure defined, replace the // TODO: CREATE USER section with the following code. ``` var userRequest = new BoxUserRequest() { Name = name, ExternalAppUserId = sub, IsPlatformAccessOnly = true }; var user = await client.UsersManager.CreateEnterpriseUserAsync(userRequest); System.Diagnostics.Debug.WriteLine("New user created: " + user.Name); ``` This code will create a new Box app user and will set the `external_app_user_id` parameter of the user object to the unique Okta user ID, which will define the binding between the two user records. A diagnostic message is then written back stating that the new user was created. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Validate Okta Users With the create user functionality defined, let's turn our attention to defining the code for validating whether an Okta user record has an associated Box user record by searching all Box enterprise users for the associated `external_app_user_id`. Replace the `// TODO: VALIDATE USER` comment with the following: ``` this.oktaRecord = userInfo client.enterprise.getUsers({ "external_app_user_id": this.oktaRecord.sub }) .then((result) => { if (result.total_count > 0) { // TODO: MAKE AUTHENTICATED USER CALL } else { // User not found - create user this.createUser(); } }); ``` Using the Box Node SDK, we call `enterprise.getUsers` to search all enterprise users, and pass in the unique Okta user ID as the `external_app_user_id` value to search specifically for that user. If found (number of records is greater than 0) we can make an authenticated call to the Box APIs using that user record, which will be defined in the next section. If not found, we call the `createUser` function we defined in the last section to create a new Box user with that `external_app_user_id` association. Replace the `// TODO: VALIDATE USER` comment with the following: ``` // Set up Box enterprise client Reader reader = new FileReader("config.json"); BoxConfig config = BoxConfig.readFrom(reader); api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(config); // Get Okta user sub for unique ID attachment to Box user Object oktaSub = user.getAttributes().get("sub"); // Check enterprise users for matching external_app_user_id against Okta sub URL url = new URL("https://api.box.com/2.0/users?external_app_user_id=" + oktaSub); BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); BoxJSONResponse jsonResponse = (BoxJSONResponse) request.send(); JsonObject jsonObj = jsonResponse.getJsonObject(); JsonValue totalCount = jsonObj.get("total_count"); // Set return string String outputString = ""; if (totalCount.asInt() > 0) { // TODO: MAKE AUTHENTICATED USER CALL } else { outputString = createUser(user); } return outputString; ``` Using the Box Java SDK generic request method, we make a call directly to the `https://api.box.com/2.0/users` endpoint to search enterprise users, passing in the unique Okta user ID as the `external_app_user_id` value to search specifically for that user. If found (number of records is greater than 0) we can make an authenticated call to the Box APIs using that user record, which will be defined in the next section. If not found, we call the `createUser` function we defined in the last section to create a new Box user with that `external_app_user_id` association. Replace the `# TODO: VALIDATE USER` comment with the following: ``` # Fetch Okta user ID uid = g.user.id # Validate is user exists url = f'https://api.box.com/2.0/users?external_app_user_id={uid}' response = self.box_client.make_request('GET', url) user_info = response.json() # If user not found, create user, otherwise fetch user token if (user_info['total_count'] == 0): self.createUser(g.user) else: # TODO: MAKE AUTHENTICATED USER CALL ``` Using the Box Python SDK generic request method, we make a call directly to the `https://api.box.com/2.0/users` endpoint to search enterprise users, passing in the unique Okta user ID as the `external_app_user_id` value to search specifically for that user. If found (number of records is greater than 0) we can make an authenticated call to the Box APIs using that user record, which will be defined in the next section. If not found, we call the `createUser` function we defined in the last section to create a new Box user with that `external_app_user_id` association. Replace the `// TODO: VALIDATE USER` comment with the following: ``` var userId = users.Entries[0].Id; var userToken = sdk.UserToken(userId); BoxClient userClient = sdk.UserClient(userToken, userId); // TODO: MAKE AUTHENTICATED USER CALL ``` If a valid user is found, the Box ID is extracted and used to generate a Box SDK client that is scoped specifically for that user, rather than the application. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Make Authenticated Box User Calls Once an associated Box user is found for the Okta user we're going to generate an access token specifically [scoped for that user](g://authentication/jwt/user-access-tokens) to make Box API calls, then make a call to get the current user to ensure that everything is working and that we have a valid user access token. Replace `// TODO: MAKE AUTHENTICATED USER CALL` from the previous section with the following: ``` this.userId = result.entries[0].id; this.userClient = sdk.getAppAuthClient('user', this.userId); this.userClient.users.get(this.userClient.CURRENT_USER_ID) .then(currentUser => { res.send(`Hello ${currentUser.name}`); }); ``` With a user found we capture the Box user ID, then generate a user client object scoped for that user. We finish by making a call to fetch the current user with the user client object, which should return the user profile information for the Okta associated Box app user. Replace `// TODO: MAKE AUTHENTICATED USER CALL` from the previous section with the following: ``` // User found, authenticate as user // Fetch user ID JsonArray entries = (JsonArray) jsonObj.get("entries"); JsonObject userRecord = (JsonObject) entries.get(0); JsonValue userId = userRecord.get("id"); // Get user scoped access token and fetch current user with it BoxDeveloperEditionAPIConnection userApi = BoxDeveloperEditionAPIConnection.getAppUserConnection(userId.asString(), config); BoxUser currentUser = BoxUser.getCurrentUser(userApi); BoxUser.Info currentUserInfo = currentUser.getInfo(); outputString = "Hello " + currentUserInfo.getName(); ``` With a user found we capture the Box user ID, then generate a user client object scoped for that user. We finish by making a call to fetch the current user with the user client object, which should return the user profile information for the Okta associated Box app user. Replace `# TODO: MAKE AUTHENTICATED USER CALL` from the previous section with the following: ``` # Create user client based on discovered user user = user_info['entries'][0] user_to_impersonate = self.box_client.user(user_id=user['id']) user_client = self.box_client.as_user(user_to_impersonate) # Get current user current_user = user_client.user().get() return f'Hello {current_user.name}' ``` With a user found we capture the Box user ID, then generate a user client object scoped for that user. We finish by making a call to fetch the current user with the user client object, which should return the user profile information for the Okta associated Box app user. Replace `// TODO: MAKE AUTHENTICATED USER CALL` from the previous section with the following: ``` BoxUser currentUser = await userClient.UsersManager.GetCurrentUserInformationAsync(); System.Diagnostics.Debug.WriteLine("Current user name: " + currentUser.Name); ``` Using that user scoped client, the current user record is then extracted from Box, and a diagnostic message is written back stating the current user name. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Summary - You've validated whether an Okta user exists as a Box user. - You've creating a new app user if they don't exist. - You're making a Box API call for an existing Box user. I have set up Box user validation and creation **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/find-or-create-box-users/ --- ## Untitled *Type: quick-start | Category: SSO & App users * Run the application With all the components of the sample in place, it's time to run our program to see if everything is working correctly… # Run the application With all the components of the sample in place, it's time to run our program to see if everything is working correctly. From the terminal / command prompt in the local application directory, type `node server.js` and click enter. The server will start up and output `Server started: Listening on port 3000`. From your browser, go to `http://localhost:3000/`. Since this is the first time we'll be testing out the user sign in flow, you'll see the Okta login. Sign in with the credentials for the Okta user you created in the last section of [step 2](g://sso-identities-and-app-users/connect-okta-to-app-users/configure-okta). Once signed in, you will see a message stating `New user created: {{USERNAME}}` output to the browser. When attempting to log in with this user in subsequent attempts, you will now see `Hello {{USERNAME}}` output to the browser. From Eclipse (or your preferred editor) click to run the application. You will see console output stating that the Spring boot application is now running on port 8080. From your browser, go to `http://localhost:8080/`. Since this is the first time we'll be testing out the user sign in flow, you'll see the Okta login. Sign in with the credentials for the Okta user you created in the last section of [step 2](g://sso-identities-and-app-users/connect-okta-to-app-users/configure-okta). Once signed in, you will see a message stating `New User Created: {{USERNAME}}` output to the browser. When attempting to log in with this user in subsequent attempts, you will now see `Hello {{USERNAME}}` output to the browser. From the terminal / command prompt in the local application directory, type `env FLASK_APP=server.py flask run` and click enter. The server will start up and output `Running on http://127.0.0.1:5000/`. From your browser, go to `http://127.0.0.1:5000/`. Since this is the first time we'll be testing out the user sign in flow, you'll see the Okta login. Sign in with the credentials for the Okta user you created in the last section of [step 2](g://sso-identities-and-app-users/connect-okta-to-app-users/configure-okta). Once signed in, you will see a message stating `New user created: {{USERNAME}}` output to the browser. When attempting to log in with this user in subsequent attempts, you will now see `Hello {{USERNAME}}` output to the browser. From Visual Studio Code (or your preferred editor) click `Run` -> `Start Debugging` from the menu. You will see debug console output as the application loads, then a browser window will be loaded with the application at `https://localhost:5001/`. Since this is the first time testing the application, the sign in link will be displayed. Once clicked, the Okta login will be automatically loaded. Sign in with the credentials for the Okta user you created in the last section of [step 2](g://sso-identities-and-app-users/connect-okta-to-app-users/configure-okta). Once signed in, you will see a message in the debug console stating `New user created: {{USERNAME}}` output to the browser. When attempting to log in with this user in subsequent attempts, you will now see `Current user name: {{USERNAME}}` output to the browser. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Summary You've reached the end of this Quick Start guide. By now you should have taken the following steps. 1. [Created a web application scaffold](g://sso-identities-and-app-users/connect-okta-to-app-users/scaffold-application-code). 2. [Setup and configured an Okta application](g://sso-identities-and-app-users/connect-okta-to-app-users/configure-okta) and created a first user that could be used to log into the web app. 3. [Setup and configured a Box application](g://sso-identities-and-app-users/connect-okta-to-app-users/configure-box) so that the web app can connect to Box. 4. [Created a log in flow for the web application](g://sso-identities-and-app-users/connect-okta-to-app-users/logging-into-app), allowing the Okta user to log in. 5. [Added a check to find an existing Box user](g://sso-identities-and-app-users/connect-okta-to-app-users/find-or-create-box-users), and optionally create a Box user the first time that Okta user logs into the web application. 6. [And finally, ran the application](g://sso-identities-and-app-users/connect-okta-to-app-users/run-the-app) and saw the complete flow in action. ## Next Steps We recommend the following resource for anyone who wants to learn more about more advanced capabilities that may be attached into the user creation and access process. - [User provisioning](g://users/provision) best practices for advanced user folder architecture setup. - [User deprovisioning](g://users/deprovision) best practices cleaning up inactive users and transferring user content to another account. - [Uploading content](g://uploads) into Box, including running preflight checks and large file (chunked) uploading. **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/run-the-app/ --- ## Untitled *Type: quick-start | Category: SSO & App users * Logging into the app with Okta With the Okta, Box, and basic application set up, we can turn our attention to the first step in the… # Logging into the app with Okta With the Okta, Box, and basic application set up, we can turn our attention to the first step in the application code flow, the Okta login. During the Okta login we will employ the OpenID Connect (OIDC) frameworks of the language used to redirect the user to Okta to log in and pass Okta user information back to the application. Those Okta user details will in turn be used to validate and create Box users in the next step. This section will walk you through: - Setting up the application configuration skeleton. - Defining the routes for the chosen framework to handle user traffic. - Passing Okta user information to the next Box user validation step. ## Set up the Skeleton In your local application directory, load the `server.js` file created in step 1. Start by copying the following package definitions and configuration information into the file. ``` const session = require('express-session'); const { ExpressOIDC } = require('@okta/oidc-middleware'); const bodyParser = require('body-parser'); const boxSDK = require('box-node-sdk'); const config = require('./config.js'); const express = require('express')(); const http = require('http'); const path = require('path'); const fs = require('fs'); express.use(session({ secret: 'this should be secure', resave: true, saveUninitialized: false })); const oidc = new ExpressOIDC({ issuer: `https://${config.oktaOrgUrl}/oauth2/default`, client_id: config.oktaClientId, client_secret: config.oktaClientSecret, appBaseUrl: config.oktaBaseUrl, loginRedirectUri: `${config.oktaBaseUrl}${config.oktaRedirect}`, scope: 'openid profile' }); express.use(oidc.router); express.use(bodyParser.json()); express.use(bodyParser.urlencoded({ extended: true })); ``` This sets up the Express configuration and Okta OIDC connector information. Express is set to use the OIDC connector and the Okta information that we saved in step 2 of this quick start is used to configure the connector for our Okta integration. Now add the routing details. ``` // Redirect to Okta login express.get('/', (req, res) => { // TODO: HANDLE ROUTE }); ``` This defines the entry route for our application. When a user attempts to visit our application root (`/`) the code within this route will be run. Lastly, add the Express server initialization to listen for traffic. ``` // Create server const port = process.env.PORT || 3000; http.createServer(express).listen(port, () => { console.log(`Server started: Listening on port ${port}`); }); ``` In your local application directory, load the `/src/main/java/com/box/sample/Application.java` file created in step 1, or similar directory if an alternate application name was used. Copy the following basic application structure into the file. ``` package com.box.okta.sample; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.net.URL; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.box.sdk.BoxAPIRequest; import com.box.sdk.BoxConfig; import com.box.sdk.BoxDeveloperEditionAPIConnection; import com.box.sdk.BoxJSONResponse; import com.box.sdk.BoxUser; import com.box.sdk.CreateUserParams; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; @RestController @EnableAutoConfiguration public class Application { static BoxDeveloperEditionAPIConnection api; // TODO: SET ROUTE // TODO: INITIALIZE SERVER } ``` This sets up the needed imports, the `Application` class, and a standard shared Box API connection attribute, to be defined in the next step. Replace `// TODO: SET ROUTE` with the following. ``` @RequestMapping("/") String home(@AuthenticationPrincipal OidcUser user) throws IOException { // TODO: HANDLE ROUTE } ``` The route mapping defines the entry route for our application. When a user attempts to visit our application root (`/`) in a logged out state, the OIDC connector will automatically push them through the Okta login, so we don't need to setup a redirect. When the user is in a logged in state, the code within this route will be run. Replace `// TODO: INITIALIZE SERVER` with the following to initialize the Spring Boot server to listen for traffic. ``` public static void main(String[] args) { SpringApplication.run(Application.class, args); } ``` In your local application directory, load the `server.py` file created in step 1. Copy the following basic application structure into the file. ``` from flask import Flask, redirect, g, url_for from flask_oidc import OpenIDConnect from okta import UsersClient from boxsdk import Client from boxsdk import JWTAuth import requests import config import json app = Flask(__name__) app.config.update({ 'SECRET_KEY': config.okta_client_secret, 'OIDC_CLIENT_SECRETS': './client_secrets.json', 'OIDC_DEBUG': True, 'OIDC_ID_TOKEN_COOKIE_SECURE': False, 'OIDC_SCOPES': ["openid", "profile"], 'OIDC_CALLBACK_ROUTE': config.okta_callback_route }) oidc = OpenIDConnect(app) okta_client = UsersClient(config.okta_org_url, config.okta_auth_token) ``` This sets up the Flask configuration, Okta client, and Okta OIDC connector information. Flask is set to use the OIDC connector and the Okta information that we saved in step 2 of this quick start is used to configure the connector for our Okta integration. Next, add a `before_request` definition to be run before route handling is engaged. We'll be using this to capture our Okta user information, if available. ``` # Fetch Okta user record if logged in @app.before_request def before_request(): # TODO: HANDLE BEFORE REQUEST ``` Lastly, define the entry route for our application, as well as a `box_auth` route. ``` # Main application route @app.route('/') def start(): # TODO: HANDLE MAIN ROUTE # Box user verification @app.route("/box_auth") @oidc.require_login def box_auth(): # TODO: HANDLE BOX AUTH ROUTE return 'Complete' ``` When a user attempts to visit our application root (`/`) the code within this route will be run. When we validate an Okta user, the code within the `box_auth` route will be run. In your local application, load `Views` > `Shared` > `Layout.cshtml`. Once the ASP.NET application loads this will be the visual component that is rendered. At the top of the page, insert the following. ``` @using System.Security.Claims; @if (User.Identity.IsAuthenticated) { <p class="navbar-text">Hello, @User.Identity.Name</p> } else { <a asp-controller="Account" asp-action="SignIn">Sign In</a> } ``` If a user who is logged in to Okta visits, they will see the hello message. If the user is not logged in a sign in link will be provided to them. Within the line `<a asp-controller="Account" asp-action="SignIn">Sign In</a>`, `asp-controller="Account"` means that the to be created Account controller will handle the request, and `asp-action="SignIn"` states that the `SignIn` method in that controller will be enacted. Save and close that file. Within the `Controllers` directory create a new file, `AccountController.cs`. This will be the controller that is enacted when that sign in link is clicked. Copy the following basic application structure into the file. ``` using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Okta.AspNetCore; using Box.V2; using Box.V2.Config; using Box.V2.JWTAuth; using Box.V2.Models; public class AccountController : Controller { public IActionResult SignIn() { if (!HttpContext.User.Identity.IsAuthenticated) { return Challenge(OktaDefaults.MvcAuthenticationScheme); } return RedirectToAction("Profile", "Account"); } [Authorize] [Route("~/profile")] public IActionResult Profile() { // TODO: HANDLE ROUTE } } ``` When the user clicks on the sign in link the `SignIn` method in this controller will be run. If the user is not already authenticated they will be sent to `Challenge`, which will redirect the user to Okta to log in. This functionality is handled by the routing framework and does not require any additional code to enact. If the user is authenticated, they will be redirected to the `Profile` routing method. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Setup Application Route We now need to define the code that will run when our main route (`/`) is engaged. Replace `// TODO: HANDLE ROUTE` in the main route with the following code. ``` if (req.userContext && req.userContext.userinfo) { const tokenSet = req.userContext.tokens; const userInfo = req.userContext.userinfo; // If Okta ID is present, pass to Box user validation if (userInfo.sub) { box.validateUser(userInfo, res); } else { console.log('No Okta ID identified'); } } else { res.redirect('/login'); } ``` What we are doing in the above is first checking to see if there is any Okta user information available from the OIDC connector. When a user logs in the connector will make the Okta user and configuration information available to our route within `req.userContext`. If user information is present, meaning the user is logged in to Okta, we pass the user information to `box.validateUser` along with the Express response object to see if there is an associated Box user available, which we'll define in the next step. If no user information is present, we redirect the user to `/login`. The OIDC connector will automatically handle this route and force the user through to the Okta login. Replace `// TODO: HANDLE MAIN ROUTE` in the main route with the following code. ``` // Validate OIDC user against Box return validateUser(user); ``` The Java OIDC connector handles most of the heavy lifting for us. When a logged out user accesses this route they will automatically be pushed to the Okta login. Once logged in, an OIDC user object will be made available to the route. We pass that user object to a `validateUser` function, which we'll define in the next step. Replace `// TODO: HANDLE BEFORE REQUEST` in the main route with the following code. ``` if oidc.user_loggedin: g.user = okta_client.get_user(oidc.user_getfield('sub')) else: g.user = None ``` This will check if an OIDC user is available, meaning that the user has already logged in to Okta. If available we set a user object using the Okta client object, and if not we set the user object to `None`. Next, replace `// TODO: HANDLE ROUTE` in the main route with the following code. ``` return redirect(url_for(".box_auth")) ``` When this code is engaged, if the user is not logged in to Okta they will be redirected to Okta to log in by the OIDC connector. After login, or if the user is already logged in, they will then be forwarded to the `box_auth` route code. Finally, replace `// TODO: HANDLE BOX AUTH ROUTE` in the `box_auth` route with the following code. ``` box = Box() return box.validateUser(g) ``` This creates a new instance of the Box class and calls the `validateUser` method, passing in the Okta user object. We'll define this class and methods in the next step. Replace `// TODO: HANDLE ROUTE` in the main route with the following code. ``` var subClaim = HttpContext.User.Claims.First(c => c.Type == "sub"); var sub = subClaim.Value; var nameClaim = HttpContext.User.Claims.First(c => c.Type == "name"); var name = nameClaim.Value; Task userSearch = validateUser(name, sub); Task.WaitAll(userSearch); return Content(name); ``` This block will capture the Okta user account sub (unique ID) and name, then sends that data to the to be created `validateUser` method to find a matching Box user, which will be created in the next step. # Incomplete previous step Please select a preferred language / framework in step 1 to get started. ## Summary - You set up the skeleton routes and configuration for Okta. - You set up the main route handler to pass to Box user verification. I have set up the Okta login **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/logging-into-app/ --- ## Untitled *Type: guide | Category: Tasks * Assign a task to a user To assign a task to a user you will need to provide the POST /task_assignments API with the id of the task and the… # Assign a task to a user To assign a task to a user you will need to provide the [`POST /task_assignments`](e://post_task_assignments) API with the `id` of the task and the user's details. For the user an application can either use the user `id` or the user's login email, which Box refers to as their `login`. # Notifications When creating a task an email notification is sent to the user who the task is assigned to. # Permissions Both the user assigning the task and the user the task is being assigned to needs to be a collaborator on the file. **Reference:** https://developer.box.com/guides/tasks/assignments/assign/ --- ## Untitled *Type: quick-start | Category: SSO & App users * Scaffold application code Our first step in this guide is to create a local application to house our code and configuration data as we start… # Scaffold application code Our first step in this guide is to create a local application to house our code and configuration data as we start to create the Okta and Box applications that will be needed. Depending on your language / framework preference, create a blank application, install the required dependencies, as well as all configuration and program files. Choose your preferred language / framework below to get started. # Node Using the Express.js framework. # Java Using the Spring Boot framework. # Python Using the Flask framework. # .NET Using the ASP.NET Core framework. - Create a local directory for your application. - Create a `package.json` file inside the local directory, open it in your preferred editor, copy / paste the following into it, and save / exit the file. ``` { "name": "okta-box", "version": "1.0.0", "description": "Box / Okta sample integration", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node server.js" }, "author": "Box", "license": "ISC", "dependencies": { "@okta/oidc-middleware": "^4.0.0", "@okta/okta-sdk-nodejs": "^3.2.0", "box-node-sdk": "^1.31.0", "express-session": "^1.17.0" } } ``` - Run `npm init` from the terminal / console to install dependencies. - Create two files, `server.js` and `config.js` in the local directory. - Open `config.js` and save the following default configuration. ``` const oktaClientId = exports.oktaClientId = ''; const oktaClientSecret = exports.oktaClientSecret = ''; const oktaOrgUrl = exports.oktaOrgUrl = ''; const oktaBaseUrl = exports.oktaBaseUrl = 'http://localhost:3000'; const oktaRedirect = exports.oktaRedirect = '/authorization-code/callback'; ``` - From Eclipse, create a new project. When prompted, select a Gradle project. - Enter a unique name for the project, we used `okta.sample` for this guide. - Open your `build.gradle` file and add the following dependencies. Once saved, refresh the Gradle project. ``` dependencies { implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'com.okta.spring:okta-spring-boot-starter:1.4.0' testImplementation('org.springframework.boot:spring-boot-starter-test') { exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' } testImplementation 'org.springframework.security:spring-security-test' compile 'com.box:box-java-sdk:2.44.1' } ``` - Open your `/src/main/resources/application.properties` file and save the following defaults. ``` okta.oauth2.redirect-uri=/authorization-code/callback okta.oauth2.issuer= okta.oauth2.clientId= okta.oauth2.clientSecret= security.oauth2.sso.loginPath=/authorization-code/callback ``` - Create a local directory for your application. - Install needed dependencies using the following `pip` command from your terminal / command prompt: `pip install flask flask_oidc okta boxsdk config` - Create three files in the local directory, `client_secrets.json`, `config.py`, and `server.py`. - Open `config.py` and save the following into it. This will be some of Okta app configuration information needed. We'll fill in the remaining information in the next step. ``` okta_client_secret = 'YOUR OKTA CLIENT SECRET' okta_org_url = 'YOUR OKTA ORG URL' okta_auth_token = 'YOUR OKTA APP TOKEN' okta_callback_route = '/oidc/callback' ``` - Open `client_secrets.json` and save the following into it. This will be a standard object that the Flask OpenID Connect integration will use during configuration. We'll fill in the remaining information in the next step. ``` { "web": { "client_id": "OKTA CLIENT ID", "client_secret": "OKTA CLIENT SECRET", "auth_uri": "OKTA AUTHORIZE URI", "token_uri": "OKTA TOKEN URI", "issuer": "OKTA APP DEFAULT", "userinfo_uri": "OKTA APP USER INFO URI", "redirect_uris": [ "http://127.0.0.1:5000/oidc/callbac" ] } } ``` - Create a local directory for your application. - Open a command prompt / terminal window and go to the local application directory. Using the [.NET Core CLI](https://docs.microsoft.com/en-us/dotnet/core/tools/) type `dotnet new mvc` and hit enter. This will create the main scaffolding for a ASP.NET Core MVC (Model-View-Controller) web app. Alternately, create the application [directly from Visual Studio](https://docs.microsoft.com/en-us/visualstudio/ide/quickstart-aspnet-core). - From the command prompt / terminal window in the local application directory, add the Okta ASP.NET Core dependencies by typing `dotnet add package Okta.AspNetCore`and the Box dependencies by typing `dotnet add package Box.V2.Core`. - Load your new application into Visual Studio or your preferred editor. - Within the root of the project, open `Startup.cs`. - Add the following package declarations to the top of the file. ``` using Microsoft.AspNetCore.Authentication.Cookies; using Okta.AspNetCore; ``` - Replace the content of the `ConfigureServices` method with the following. We will fill in the specific Okta application values in the next step. ``` services.AddControllersWithViews(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OktaDefaults.MvcAuthenticationScheme; }) .AddCookie() .AddOktaMvc(new OktaMvcOptions { // Replace these values with your Okta configuration OktaDomain = "", ClientId = "", ClientSecret = "" }); ``` Add the following line to the **top** of the `Configure` method. ``` app.UseAuthentication(); ``` # Incomplete previous step Please select a preferred language / framework to get started. ## Summary - You created a new local application, files, and basic configuration details. - You installed all project dependencies. I have my local application set up **Reference:** https://developer.box.com/guides/sso-identities-and-app-users/connect-okta-to-app-users/scaffold-application-code/ --- ## Untitled *Type: guide | Category: Tasks * Change task assignment state To update a task assignment's state call the PUT /tasks/:task_id/assignments API and include a resolution_state… # Change task assignment state To update a task assignment's state call the [`PUT /tasks/:task_id/assignments`](e://put_task_assignments_id) API and include a `resolution_state`, such as `completed`, `incomplete`, `approved`, or `rejected`. ## Resolution states Box currently supports two types of tasks defined by the `action` value: `review` tasks and `complete` tasks. The type of task determines the possible resolution states a task can be in and the interface shown to a user in the web and mobile apps. | Task action | Possible resolution states | | --- | --- | | review | incomplete, approved, rejected | | complete | incomplete, complete | A `review` task starts out in an `incomplete` state and can be marked as `incomplete`, `approved`, or `rejected`. In the user interface a user is provided with a text box and an pair of buttons to approve or reject the task. A `complete` task starts out in an `incomplete` state and can be marked `incomplete` or `completed`. Once a this task is marked completed, no further changes can be made to the task's state. In the user interface a user is provided with a text box and an button to mark the task as completed. **Reference:** https://developer.box.com/guides/tasks/assignments/change-state/ --- ## Untitled *Type: guide | Category: Tasks * Get task assignment information To get information about an assigned task, call the GET /tasks/:task_id/assignments API with the id of the… # Get task assignment information To get information about an assigned task, call the [`GET /tasks/:task_id/assignments`](e://get_task_assignments_id) API with the `id` of the task assignment. **Reference:** https://developer.box.com/guides/tasks/assignments/get/ --- ## Untitled *Type: guide | Category: Tasks * Assigning tasks When a task is delegated to a user in Box it creates a task assignment. A task assignment is a request for that user to… # Assigning tasks When a task is delegated to a user in Box it creates a task assignment. A task assignment is a request for that user to complete the task. The way a task is resolved depends on the `action` type of a task and the `resolution_state` used to define how a task is resolved. Learn about types of tasks **Reference:** https://developer.box.com/guides/tasks/assignments/ --- ## Untitled *Type: guide | Category: Tasks * List a task's assignments To list all of the assignments for a specific tasks, call the GET /tasks/:task_id/assignments with the task id. # List a task's assignments To list all of the assignments for a specific tasks, call the [`GET /tasks/:task_id/assignments`](e://get_task_assignments_id) with the task `id`. **Reference:** https://developer.box.com/guides/tasks/assignments/list/ --- ## Untitled *Type: guide | Category: Tasks * Unassign a task To unassign a task, you will need to provide the DELETE /task_assignments API with the id of the task assignment… # Unassign a task To unassign a task, you will need to provide the [`DELETE /task_assignments`](e://delete_task_assignments_id) API with the `id` of the task assignment. # Permissions The user deleting the assignment needs to be a collaborator on the file. **Reference:** https://developer.box.com/guides/tasks/assignments/unassign/ --- ## Untitled *Type: guide | Category: Tasks * Change an assignment's message To update a task assignment's message call the PUT /tasks/:task_id/assignments API, and include the new… # Change an assignment's message To update a task assignment's message call the [`PUT /tasks/:task_id/assignments`](e://put_task_assignments_id) API, and include the new `message` for the task assignment. **Reference:** https://developer.box.com/guides/tasks/assignments/update-message/ --- ## Untitled *Type: guide | Category: Tooling * Retrieve an Access Token Every API call requires an Access Token to identify the authenticated user. For security purposes, Access Tokens… # Retrieve an Access Token Every API call requires an **Access Token** to identify the authenticated user. For security purposes, Access Tokens expire after 60 minutes. If you are using [OAuth 2.0](g://authentication/oauth2), use the provided [Refresh Token](g://authentication/tokens/refresh/) to obtain a new Access Token. If you are using server authentication, [JWT](g://authentication/jwt) or [Client Credentials Grant](g://authentication/client-credentials), make an API call to the [token endpoint](e://post-oauth2-token) to request a new Access Token. ## OAuth 2.0 If your application leverages [OAuth 2.0](g://authentication/oauth2) for authentication, you can follow the steps below to obtain a token pair via [Postman](g://tooling/postman/install). - The `grant_type` will always be `authorization_code`. - The `client_id` and `client_secret` values can be obtained from the **Configuration** tab for your application in the [Developer Console](https://app.box.com/developers/console). To obtain the value for `code`, build and visit your [authorization URL](g://authentication/oauth2/without-sdk) in your browser. Complete the OAuth 2.0 flow and, upon redirecting to your configured redirect URL, the authorization code will be at the end of the URL. As a reminder, this authorization code is only valid for 30 seconds. This means you must enter it to the designated field in Postman and click **Send** before it expires. Therefore, we recommend entering the other values so the API call is ready to send as soon as you get the code. **Reference:** https://developer.box.com/guides/tooling/postman/access-token/ --- ## Untitled *Type: guide | Category: Metadata * Get a metadata template Information for a metadata template can be retrieved using the template's name and scope, or the template's… # Get a metadata template Information for a metadata template can be retrieved using the template's name and scope, or the template's identifier. The authenticated user can only get Information about metadata templates [scoped](g://metadata/scopes) within the `global` scope or the `enterprise_:id` scope where `:id` is the ID of their enterprise. ## Get a metadata template by name To get a metadata template by name, call the [`GET /metadata_templates/:scope/:templateKey/schema`](e://get_metadata_templates_id_id_schema) API endpoint with the template's `scope` and `templateKey`. To get the `scope` and `templateKey` for a template, either [list all metadata templates](g://metadata/templates/list), or [list all instances on an item](g://metadata/instances/list). ## Get a metadata template by ID To get a metadata template by ID, you will need to pass the template's `id` to the [`GET /metadata_templates/:id`](e://get_metadata_templates_id) API endpoint. To get the `id` for a template, either [list all metadata templates](g://metadata/templates/list), or [list all instances on an item](g://metadata/instances/list). **Reference:** https://developer.box.com/guides/metadata/templates/get/ --- ## Untitled *Type: guide | Category: Tooling * Postman Collection Postman is a tool that lets you build and test HTTP requests in an easy-to-use interface without configuring a full… # Postman Collection [Postman](https://postman.com) is a tool that lets you build and test HTTP requests in an easy-to-use interface without configuring a full development environment. The **Box Postman Collection** is a set of preconfigured requests that make it possible to get started with the Box API without having to manually configure the requests. The simplest way to get started with Postman is with our Postman Quick Start guide. Get Started with the Box Postman Collection ## Latest Collection Clicking the following button will fork our latest Postman collection. It is a complete Postman collection that covers every API endpoint and is auto-generated from our [OpenAPI specification](https://github.com/box/box-openapi). It is expected to get many more updates including some to make authentication a lot easier. **Reference:** https://developer.box.com/guides/tooling/postman/ --- ## Untitled *Type: guide | Category: Metadata * Metadata templates A metadata template describes a set of key/value pairs that can be assigned to a file or folder. For example, an… # Metadata templates A metadata template describes a set of key/value pairs that can be assigned to a file or folder. For example, an `invoiceData` template might hold data about an invoice, having a field for the invoice ID as well as the customer ID. A file or folder can have multiple distinct template [instances](g://metadata/instances) associated with it, such as a `marketingCollateral` instance and a `retentionPolicy` instance. ## Metadata scopes Metadata templates are grouped into two distinct groups, or **scopes**. Learn more about Metadata Scopes ## Permissions and restrictions There is a limit of 500 templates per enterprise. Creating metadata templates is restricted to users with admin permission. This means that only admins, or co-admins who have been granted rights to Create and edit metadata templates for your company by the admin can use the web app or the API to manage templates. **Reference:** https://developer.box.com/guides/metadata/templates/ --- ## Untitled *Type: guide | Category: Tooling * Install Postman & Collection To use the Box Postman Collection you will need to have Postman installed on your device. Postman is available… # Install Postman & Collection To use the **Box Postman Collection** you will need to have [Postman](https://getpostman.com) installed on your device. Postman is available for Windows, Mac, and Linux environments. [Download the appropriate version for you operating system](https://www.postman.com/downloads/) Next, install Postman on your machine, [create an account, and sign in](https://identity.getpostman.com/signup). ## Loading a collection and environment With the Postman App installed the **Box Postman Collection** can be loaded into it. Clicking the button below you will load the Box Postman Collection into Postman. **Reference:** https://developer.box.com/guides/tooling/postman/install/ --- ## Untitled *Type: guide | Category: Tooling * Box for Agentforce Extension package The Box for Agentforce Extension package is an extension of the Box for Salesforce managed package… # Box for Agentforce Extension package The [Box for Agentforce Extension package](https://support.box.com/hc/en-us/articles/40370228349331-Installing-Box-for-Agentforce) is an extension of the Box for Salesforce managed package. This extension provides reusable Agentforce [actions](g://tooling/salesforce-toolkit/flow-actions) that help automate workflows and enhance intelligent agent—based processes within Salesforce. It builds on the core features of the Box for Salesforce package and uses global, invocable Apex methods to improve functionality. The Box for Agentforce Extension package references the methods by using the Box name space in Agentforce Actions. ## Methods in Agentforce Flows The list below contains example [methods](g://tooling/salesforce-toolkit/methods) that can be invoked in Agentforce. ### Folder & File Management - Create Folder - Create Folder Association - Create Folder for Record ID - Create Folder for Record ID from Template - Get Folder Contents by Folder ID - Get Folder ID by Record ID - Get Folder URL - Move Folder - Get Object Folder by Record ID - Get Record ID by Folder ID - Get URL for Folder ### Metadata Management - Create Box Metadata by File ID - Create Box Metadata by Folder ID - Delete Box Metadata by File ID - Delete Box Metadata by Folder ID - Update Box Metadata by Folder ID - Get Box Metadata by File ID - Get Box Metadata by Folder ID ### Collaboration - Create Collaboration - Create Collaboration on Record - Edit Collaboration - Delete Collaboration ### Additional Actions - Create File from Attachment - Get DocGen Batch - Get Folder Associations by Salesforce Record ID - Get Metadata Cascade Policies by Folder ID - Get Metadata Cascade Policy by ID - Create Metadata Cascade Policy - Delete Metadata Cascade Policy - Create Slack Channel Mapping - Set Slack Channel Access Management Disabled **Reference:** https://developer.box.com/guides/tooling/salesforce-toolkit/box-agentforce-package/ --- ## Untitled *Type: guide | Category: Tooling * Flow Actions Salesforce toolkit includes wrappers that allow admins to invoke the following methods. It allows Box for Salesforce users to… # Flow Actions Salesforce toolkit includes wrappers that allow admins to invoke the following [methods](g://tooling/salesforce-toolkit/methods). It allows Box for Salesforce users to build automated solutions, such as folder structure, using [Salesforce Flows](https://help.salesforce.com/s/articleView?id=sf.flow.htm&type=5). ## Methods in Salesforce Flows The list below contains all methods that can be invoked in [Salesforce Flows](https://help.salesforce.com/s/articleView?id=sf.flow.htm&type=5). - Create Box Metadata by Folder Id (`createBoxMetadataByFolderId`) - Create Collaboration (`createCollaboration`) - Create Collaboration On Record (`createCollaborationOnRecord`) - Create File From Attachment (`createFileFromAttachment`) - Create Folder (`createFolder`) - Create Folder Association (`createFolderAssociation`) - Create Folder For Record ID (`createFolderForRecordId`) - Create Folder For Record ID From Template (`createFolderForRecordIdFromTemplate`) - Create Metadata Cascade Policy (`createMetadataCascadePolicy`) - Create Object Folder For Record ID (`createObjectFolderForRecordId`) - Create Slack Channel Mapping (`mapSfdcRecordToSlackChannel`) - Delete Box Metadata by Folder Id (`deleteBoxMetadataByFolderId`) - Delete Collaboration (`deleteCollaboration`) - Delete Metadata Cascade Policy (`deleteMetadataCascadePolicyById`) - Edit Collaboration (`editCollaboration`) - Enable Integration Activity (`enableAppActivity`) - Get Box Metadata by Folder Id (`getBoxMetadataByFolderId`) - Get Folder Associations By Salesforce Record ID (`getFolderAssociationsByRecordId`) - Get Folder ID By Record ID (`getFolderIdByRecordId`) - Get Folder URL (`getFolderUrl`) - Get Metadata Cascade Policies by Folder Id (`getMetadataCascadePoliciesByFolderId`) - Get Metadata Cascade Policy by Id (`getMetadataCascadePolicyById`) - Get Object Folder By Record ID (`getObjectFolderByRecordId`) - Get Record ID By Folder ID (`getRecordIdByFolderId`) - Get Root Folder ID (`getRootFolderId`) - Get URL For Folder (`getUrlForFolder`) - Move Folder (`moveFolder`) - Set Slack Channel Access Management Disabled (`setSlackChannelAccessManagementDisabled`) - Update Box Metadata by Folder Id (`updateBoxMetadataByFolderId`) **Reference:** https://developer.box.com/guides/tooling/salesforce-toolkit/flow-actions/ --- ## Untitled *Type: guide | Category: Tooling * Refresh an Access Token To authenticate to the Box API the Postman collection will use an Access Token to identify you, the User to the API… # Refresh an Access Token To authenticate to the Box API the Postman collection will use an Access Token to identify you, the **User** to the API. Access tokens expire after 1 hour and therefore need to be refreshed every hour. ## Using a Refresh Token If you set up your own **Box App** in step 2 of the Postman Quick Start guide then your Box environment in Postman should include a valid `client_id` and `client_secret`. These client credentials and the `refresh_token` can be used to create a new value for the `access_token`. To refresh the access token, select the **Refresh access token** API call within the **Authorization** folder of the Postman collection. Next, click the **Send** button to request a new `access_token`. At the end of this API call, your environment should have a new `access_token` and `refresh_token` value, and you should be able to make any of the other API calls. Refresh tokens are only valid once and need to be used within 60 days. If used within 60 days, a new one is created together with a new access token and the 60 day period starts again. A refresh token expires if not used within 60 days, after which a new refresh token and access token need to be requested by going through the Quick Start guide again. ## Automatically refreshing an access token The Postman collection can automatically detect an expired `access_token` value and request a new one by using the `refresh_token`. By default this feature is enabled but it can be turned off by setting the `enable_auto_refresh_access_token` Postman environment variable to `false`. To set this value, click the edit button in the top right of your Box Postman environment variables. Find the row in the table for the `enable_auto_refresh_access_token` variable and set the **Current Value** to `true`. Next, click **Update** to save your changes. From now on, any time you make any API call the **Postman collection** will check if your `access_token` has expired and try to refresh it automatically before making your desired API call. ## Re-authenticating your Postman collection In some cases you might need to re-authenticate your Postman collection by going through the [Quick Start](g://tooling/postman/quick-start) guide again. A common reason for this is because you haven't used the Postman collection in over 60 days and your `refresh_token` has expired. To re-authenticate, first remove your old **Box Postman environment**. To do so, click the little **gear** icon in the top right and select your environment from the list. Select **Delete** to delete the environment. Then, restart the Postman Quick Start guide again from the start. When re-importing the **Box Postman Collection** for a second time the Postman app might ask you to import the new collection as a copy or replace the old one. We recommend importing it as a copy in order to preserve any custom configuration you might have made to any of the APIs. **Reference:** https://developer.box.com/guides/tooling/postman/refresh/ --- ## Untitled *Type: guide | Category: Tooling * Make an API call With the Box Postman Collection loaded into the Postman App it is possible to make API calls to the Box API on behalf of… # Make an API call With the **Box Postman Collection** loaded into the **Postman App** it is possible to make API calls to the **Box API** on behalf of the user logged in as. The Box Postman Collection will require a valid `access_token` environment variable to make API calls. To get your Postman App set up with a valid Access Token we recommend following our Quick Start guide. ## Make an API request To make an API request, select a **Request** from the Box Postman Collection. In this example, we will use the **List items in folder** API which can be found in the **Folders** folder. By default the `folder_id` for this API endpoint is set to `0` which represents every user's root folder. You can leave this value as is or set it to the folder ID of a folder you want to inspect. Next, click the **Send** button in the top right to make the API request. The API call should return quickly and show you a list of items in your folder in the response **Body** tab in the bottom half of the screen. # Authentication error At this point Postman might return an error instead of a list. Often, this means your **Access Token** has expired. Check our guide on refreshing an access token in Postman for more details. **Reference:** https://developer.box.com/guides/tooling/postman/make-api-call/ --- ## Untitled *Type: guide | Category: Tooling * Salesforce Developer Toolkit The Box for Salesforce Developer Toolkit allows customers to programmatically customize the behavior of the Box… # Salesforce Developer Toolkit The Box for Salesforce Developer Toolkit allows customers to programmatically customize the behavior of the Box for Salesforce integration. The Toolkit consists of several global APEX methods that can be used to trigger and extend the default behavior. The global methods can update the internal Salesforce record to Box folder mapping and handle permission management. This functionality is part of the latest Box for [Salesforce package](https://support.box.com/hc/en-us/articles/360044195713-Installing-and-Configuring-Box-For-Salesforce). # What the Toolkit does NOT provide The Toolkit is not a full-featured APEX wrapper for the BOX Content API. If this is what you are looking for, have a look at the [Box SDK for Salesforce](https://github.com/box/box-salesforce-sdk). ## Authentication A solution for authentication is to allow API calls to use the service account credentials. This means that Salesforce Admins need to restrict access to the Toolkit global APEX class. As these methods allow direct modification of Box content and collaborations, Salesforce administrators should take appropriate precautions by restricting access to the global Toolkit APEX class. Toolkit methods that take `accessToken` as a parameter can use the service account credentials by sending `null` for the `accessToken` value. If a value is passed in `accessToken`, the API call to Box is done with the access token sent. It is up to the developer to ensure the token being passed is valid and the user associated with the token has permissions to perform the requested operation. **Reference:** https://developer.box.com/guides/tooling/salesforce-toolkit/ --- ## Untitled *Type: guide | Category: Tooling * UI Elements in Salesforce The Box for Salesforce managed package offers the following UI Elements as Lightning Components: content picker… # UI Elements in Salesforce The Box for Salesforce managed package offers the following [UI Elements](g://embed/ui-elements) as Lightning Components: [content picker](g://embed/ui-elements/picker), [explorer](g://embed/ui-elements/explorer), [preview](g://embed/ui-elements/preview), and [uploader](g://embed/ui-elements/uploader). You can use them on Lightning Pages, or in Flows. ## Content picker [Options](g://embed/ui-elements/picker/#options) available in picker with Box for Salesforce are: - `folderId` - if the lightning component is on a record page, it defaults to the record folder - `chooseButtonLabel` - `cancelButtonLabel` - `canSetShareAccess` - `canCreateNewFolder` - `canUpload` - `maxSelectable` ## Content explorer [Options](g://embed/ui-elements/explorer/#options) available in explorer with Box for Salesforce are: - `folderId` - if the lightning component is on a record page, it defaults to the record folder - `canSetShareAccess` - `canCreateNewFolder` - `canUpload` - `canPreview` - `canDownload` - `canDelete` - `canRename` - `canShare` ## Content preview [Options](g://embed/ui-elements/preview/#options) available in preview with Box for Salesforce are: - `fileId` ([find your file ID](g://files/get)) - **File Id API Field Name** - Salesforce specific; on a record page, you can use an API field name that holds the file ID to be displayed ## Content uploader [Options](g://embed/ui-elements/uploader/#options) available in uploader with Box for Salesforce are: - `folderId` - if the lightning component is on a record page, it defaults to the record folder - `fileLimit` **Reference:** https://developer.box.com/guides/tooling/salesforce-toolkit/ui-elements/ --- ## Untitled *Type: guide | Category: Tooling * Code Samples Generic Method The following code will create metadata on a Box folder in Salesforce using the generic Toolkit method: New… # Code Samples ## Generic Method The following code will create metadata on a Box folder in Salesforce using the generic Toolkit method: ``` // Instantiate the Toolkit object box.Toolkit toolkit = new box.Toolkit(); // Get the Salesforce record id associated with a Box folder String recordId = toolkit.getRecordIdByFolderId('{some folder id}'); // Construct an object containing all the metadata you want Map<String, Object> metadata = new Map<String, Object>{ 'salesforce_id' => recordId, 'salesforce_url' => System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + recordId, 'salesforce_user_name' => UserInfo.getName(), 'salesforce_user_email' => UserInfo.getUserEmail() }; // Specify the Box API endpoint to call String endpoint = 'https://api.box.com/2.0/folders/' + '{some folder id}' + '/metadata/global/properties'; // Create a new HttpRequest object and set appropriate values HttpRequest request = new HttpRequest(); request.setMethod('POST'); request.setEndpoint(endpoint); request.setBody(JSON.serialize(metadata)); request.setHeader('content-type', 'application/json'); // Send the HttpRequest through the generic Toolkit method, which will handle the authentication details HttpResponse response = toolkit.sendRequest(request); ``` ## New Folder Association The following code will create a folder for a specific Salesforce record Id: ``` // Instantiate the Toolkit object box.Toolkit boxToolkit = new box.Toolkit(); // Create a folder and associate it with an account Id accountId = '001j000000FBozw'; String accountFolderId = boxToolkit.createFolderForRecordId(accountId, null, true); system.debug('new item folder id: ' + accountFolderId); // If there was an error, accountFolderId will be null. mostRecentError will contain the error message if(accountFolderId == null) { system.debug('most recent error: ' + boxToolkit.mostRecentError); } // ALWAYS call this method when finished.Since salesforce doesn't allow http callouts after dml operations, we need to commit the pending database inserts/updates or we will lose the associations created boxToolkit.commitChanges(); ``` ## Folder Templates The following code will create a folder for a record, create subfolders (folder template), and collaborate the current user: ``` // Instantiate the Toolkit object box.Toolkit boxToolkit = new box.Toolkit(); // Create a folder and associate it with an account Id accountId = '001j000000FBozz'; String accountFolderId = boxToolkit.createFolderForRecordId(accountId, null, true); system.debug('new item folder id: ' + accountFolderId); // Create two sub-folders in the newly created account folder String legalFolderId = boxToolkit.createFolder('Legal Documents', accountFolderId, null); system.debug('Legal Folder id: ' + legalFolderId); String pictureFolderId = boxToolkit.createFolder('Pictures', accountFolderId, null); system.debug('Picture Folder id: ' + pictureFolderId); // Collaborate the current user on the account folder. Note that we're sending false for the optCreateFolder param that shouldn't actually matter since the folder(s) already exists Id userId = UserInfo.getUserId(); box.Toolkit.CollaborationType collabType = box.Toolkit.CollaborationType.EDITOR; String collabId = boxToolkit.createCollaborationOnRecord(userId, accountId, collabType, false); system.debug('new collaboration id: ' + collabId); // ALWAYS call this method when finished. Since salesforce doesn't allow http callouts after dml operations, we need to commit the pending database inserts/updates or we will lose the associations created boxToolkit.commitChanges(); ``` ## Metadata The following code will get, add, delete, and update Box folder metadata and cascade policies. ``` // Get metadata & attributes types Box.toolkit tk = new Box.Toolkit(); Box.MetadataTemplate mdt = tk.getMetadataTemplateByName('enterprise', 'testtemplate'); System.debug(mdt); System.debug(mdt.getAttributeTypes()); //get Map<String, String> of values and types. // Get Metadata Box.Toolkit tk = new Box.Toolkit(); Box.FolderMetadata fmd = tk.getBoxMetadataByFolderId('193488737189', 'enterprise', 'testTemplate'); System.debug(tk.mostRecentError); System.debug(fmd); // Create Metadata Box.KeyValuePair kvp = new Box.KeyValuePair(); kvp.key = 'recordName'; kvp.value = 'Account Test Name'; Box.KeyValuePair kvp2 = new Box.KeyValuePair(); kvp2.key = 'recordUrl'; kvp2.value = 'https://speed-nosoftware-3605-dev- ed.scratch.lightning.force.com/lightning/r/Account/001DR00001PsY7YYAV/view'; List<Box.KeyValuePair> kvps = new List<Box.KeyValuePair>(); kvps.add(kvp); kvps.add(kvp2); Box.Toolkit tk = new Box.Toolkit(); Box.FolderMetadata newfmd = tk.createBoxMetadataByFolderId('193488737189', 'enterprise', 'testTemplate', kvps); System.debug(tk.mostRecentError); System.debug(newfmd); // Update Metadata List<Box.FolderMetadataUpdate> updates = new List<Box.FolderMetadataUpdate>(); Box.FolderMetadataUpdate up1 = new Box.FolderMetadataUpdate(); Box.FolderMetadataUpdate up2 = new Box.FolderMetadataUpdate(); up1.op = 'replace'; up1.path = '/recordName'; up1.value = 'Account Name Test 2'; updates.add(up1); up2.op = 'replace'; up2.path = '/recordUrl'; up2.value = 'https://speed-nosoftware-2356-dev- ed.scratch.lightning.force.com/lightning/r/Account/001DR00001PsY7YYAV/view'; updates.add(up2); Box.Toolkit tk = new Box.Toolkit(); Box.FolderMetadata fmd = tk.UpdateBoxMetadataByFolderId('193488737189', 'global', 'lobSalesforceRecord', updates); System.debug(fmd); // Delete Metadata Box.Toolkit tk = new Box.Toolkit(); Boolean fmd = tk.deleteBoxMetadataByFolderId('193488737189', 'global', 'lobSalesforceRecord'); System.debug(tk.mostRecentError); System.debug(fmd); // Get Cascade Policy List Box.Toolkit tk = new Box.Toolkit(); List<Box.MetadataCascadePolicy> mcp = tk.getMetadataCascadePoliciesByFolderId('193488737189', null, 0, null); System.debug(mcp); System.debug(tk.mostRecentError); // Get Cascade Policy Box.Toolkit tk = new Box.Toolkit(); Box.MetadataCascadePolicy mcp = tk.getMetadataCascadePolicyById('MTkzNDg4NzM3MTg5I2cjbG9iU2FsZXNmb3JjZVJlY29yZC0wMTIwMTI0ZC03YWUxLTQzNjItYjdlMC05Y2RiYzhkMzIzZjM'); System.debug(mcp); System.debug(tk.mostRecentError); // Create Cascade Policy Box.Toolkit tk = new Box.Toolkit(); Box.MetadataCascadePolicy mcp = tk.createMetadataCascadePolicy('193488737189', 'global', 'lobSalesforceRecord'); System.debug(mcp); System.debug(tk.mostRecentError); // Delete Cascade Policy Box.Toolkit tk = new Box.Toolkit(); Boolean mcp = tk.deleteMetadataCascadePolicyById('MTkzNDg4NzM3MTg5I2cjbG9iU2FsZXNmb3JjZVJlY29yZC0wMTIwMTI0ZC03YWUxLTQzNjItYjdlMC05Y2RiYzhkMzIzZjM'); System.debug(mcp); System.debug(tk.mostRecentError); ``` More examples: ``` // Get metadata example 1 Box.toolkit tk = new Box.Toolkit(); Box.FolderMetadata fmt = tk.getBoxMetadataByFolderId('205776356105', 'enterprise', 'testTemplate'); for(KeyValuePair kvp : fmt.keyValuePairs){ System.debug(kvp); } // Get metadata example 2 Box.toolkit tk = new Box.Toolkit(); System.debug(tk.getBoxMetadataByFolderId('205776356105', 'global', 'lobSalesforceRecord')); ``` ``` // Create metadata Box.toolkit tk = new Box.Toolkit(); List<Box.KeyValuePair> kvps = new List<Box.KeyValuePair>(); Box.KeyValuePair kvp1 = new Box.KeyValuePair(); kvp1.key = 'name'; kvp1.value = 'test'; kvps.add(kvp1); Box.KeyValuePair kvp2 = new Box.KeyValuePair(); kvp2.key = 'revenue'; kvp2.value = '5000'; kvps.add(kvp2); Box.KeyValuePair kvp3 = new Box.KeyValuePair(); kvp3.key = 'typeMulti'; kvp3.value = 'Customer;Other'; kvps.add(kvp3); System.debug(tk.createBoxMetadataByFolderId('205776356105', 'enterprise', 'testtemplate', kvps)); System.debug(tk.mostRecentError); ``` ``` // Update Metadata Box.toolkit tk = new Box.Toolkit(); System.debug(tk.getBoxMetadataByFolderId('205776356105', 'enterprise', 'mitchtemplate')); List<Box.FolderMetadataUpdate> fmus = new List<Box.FolderMetadataUpdate>(); Box.FolderMetadataUpdate fmu = new Box.FolderMetadataUpdate(); fmu.op = 'replace'; fmu.path = '/name'; fmu.value = 'Test 2'; fmus.add(fmu); Box.FolderMetadataUpdate fmu2 = new Box.FolderMetadataUpdate(); fmu2.op = 'replace'; fmu2.path = '/revenue'; fmu2.value = '3000'; fmus.add(fmu2); Box.FolderMetadataUpdate fmu3 = new Box.FolderMetadataUpdate(); fmu3.op = 'add'; fmu3.path = '/typeMulti'; fmu3.value = 'Customer'; fmus.add(fmu3); System.debug(tk.updateBoxMetadataByFolderId('205776356105', 'enterprise', 'testTemplate', fmus)); System.debug(tk.mostRecentError); ``` **Reference:** https://developer.box.com/guides/tooling/salesforce-toolkit/samples/ --- ## Untitled *Type: guide | Category: Uploads * Commit Upload Session The final step in a chunked upload is to commit the session. To commit a file upload session, call the POST /files… # Commit Upload Session The final step in a chunked upload is to commit the session. To commit a file upload session, call the [`POST /files/upload_sessions/:id/commit`](e://post_files_upload_sessions_id_commit) with a list of uploaded parts to commit. Additionally, any file `attributes` can be passed along with the `parts` to further add information to the file. See the [`POST /files/content`](e://post_files_content) API for more details. ## Response When successful, the API returns a HTTP `201 Created` status code with a [`File`](r://file) object. In some cases, creating the parts might not be ready yet and the API will return a `202 Accepted` status code instead. In this case the application should check the `retry-after` header and retry committing after the number of seconds specified. **Reference:** https://developer.box.com/guides/uploads/chunked/commit-session/ --- ## Untitled *Type: guide | Category: Uploads * Chunked Uploads The Chunked Upload API provides a way to reliably upload large files to Box by chunking them into a sequence of parts that… # Chunked Uploads The Chunked Upload API provides a way to reliably upload large files to Box by chunking them into a sequence of parts that can be uploaded individually. By using this API the application uploads a file in part, allowing it to recover from a failed request more reliably. It means an application only needs to retry the upload of a single part instead of the entire file. An additional benefit of chunked uploads is that parts can be uploaded in parallel, allowing for a potential performance improvement. ## Overview Chunked uploads require a sequence of API calls to be made. 1. **[Create an upload session](g://uploads/chunked/create-session)**: The application creates an upload session for a new file or new version of a file. The session defines the (new) name of the file, its size, and the parent folder. 2. **[Upload parts](g://uploads/chunked/upload-part)**: The application uploads the separate parts of the file as chunks. 3. **[Commit session](g://uploads/chunked/commit-session)**: The application commits the session, at which moment the integrity of the file is checked before it is placed in the location specified when the session was created. Most of [the Box SDKs support chunked uploads](g://uploads/chunked/with-sdks) out of the Box, removing the complexity from the application code. ## Restrictions The Chunked Upload API is intended for large files with a minimum size of 20MB. The API does not support uploads of files with a size smaller than this. This API does not support re-uploading or overwriting of parts in a session. Once a part has been uploaded, it is immutable. The lifetime of an upload session is 7 days. During this time, the client can upload parts at their own pace. To avoid wasting resources, and avoid potential data corruption, client should make sure that the underlying file has not been changed on disk since beginning the upload. **Reference:** https://developer.box.com/guides/uploads/chunked/ --- ## Untitled *Type: guide | Category: Uploads * Create Upload Session To create an upload session, call the POST /files/upload_sessions API with the desired file_name and folder_id to put… # Create Upload Session To create an upload session, call the [`POST /files/upload_sessions`](e://post_files_upload_sessions) API with the desired `file_name` and `folder_id` to put the file in, as well as the `file_size` of the file to be uploaded. To create a session for a new version of an existing file, call the [`POST /files/:id/upload_sessions`](e://post_files_id_upload_sessions) API instead. In this case, the `file_name` and `folder_id` are only required when renaming or moving the file in the process. ## Pre-flight Check Creating an upload session also performs a [preflight check](g://uploads/check), making it unnecessary to do so separately when working with chunked uploads. ## Response When a session is created successfully the response includes an Upload Session that includes a session ID, the number of parts, the part sizes, as well as links to the relevant next API endpoints to use. ``` { "id": "F971964745A5CD0C001BBE4E58196BFD", "type": "upload_session", "session_expires_at": "2012-12-12T10:53:43-08:00", "part_size": 1024, "total_parts": 1000, "num_parts_processed": 455, "session_endpoints": { "upload_part": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD", "commit": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/commit", "abort": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD", "list_parts": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/parts", "status": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD", "log_event": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/log" } } ``` The upload session defines the size of the parts to use when uploading the individual parts. **Reference:** https://developer.box.com/guides/uploads/chunked/create-session/ --- ## Untitled *Type: guide | Category: Tooling * Methods and Operations Toolkit Details Class Name: box.Toolkit Instance Variables mostRecentError String to indicate the most recent error… # Methods and Operations ## Toolkit Details Class Name: `box.Toolkit` ## Instance Variables ### mostRecentError String to indicate the most recent error that occurred when calling instance methods. The presence of this string does not mean the operation did not succeed. It is possible the error was recoverable; however, the lack of a value in this string does indicate the operation was successful. ### Enum CollaborationType Enum to indicate the [type of collaboration](https://support.box.com/hc/en-us/articles/360044196413-Understanding-Collaborator-Permission-Levels). Possible values: `EDITOR`, `VIEWER`, `PREVIEWER`, `UPLOADER`, `COOWNER`, `OWNER`, `PREVIEWERUPLOADER`, or `VIEWERUPLOADER` ## Static Methods ### deleteServiceUserAssociation Method to clear association between Service Account and Box for Salesforce integration. This can be used to change the service account if an incorrect one is being used. Parameters: - None Returns: - `true` if the user's account existed and was deleted. - `false` if the user's account was not deleted for any reason (including because it didn't exist). ### deleteUserAssociation | Parameter | Type | Description | | --- | --- | --- | | userId | id | The Id of the user whose credentials are to be cleared. | Returns: - `true` if the user's account existed and was deleted. - `false` if the user's account was not deleted for any reason (including because it didn't exist). ## Instance Methods - Constructors, Destructors ### box.Toolkit() Parameters: - None ### commitChanges Treat this method as a destructor for the `box.Toolkit()` method. This method is critical. It must be called after all folder / collaboration operations are complete. Every time. No Exceptions. Since Salesforce doesn't allow callouts after database updates / inserts / deletes have occurred, the Toolkit class maintains some collections of objects to be inserted once all callout operations are complete. If this method is not called, those objects won't be in the database, and the tables that keep track of user / record / folder associations will be out of sync and will need some advanced debugging to fix. Parameters: - None Returns: - `Void` ### commitChanges with platform event Treat this method as a destructor for the `box.Toolkit()` method. This method is very similar to the `commitChanges` above. However, it uses a platform event to commit changes to the database to perform DML statements in a different transaction and avoid governor limits in some scenarios. | Parameter | Type | Description | | --- | --- | --- | | usePlatformEvent | boolean | true if you're using a platform event. false to call the original method. | Returns: - `Void` ## Generic Methods The Box for Salesforce Developer Toolkit provides a global method that accepts an [HttpRequest](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_httprequest.htm) object as a parameter and returns an [HttpResponse](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_httpresponse.htm#apex_classes_restful_http_httpresponse) object. This method will utilize the authentication details of the Service Account to make callouts to Box's APIs, allowing you to focus on the business logic of your integration. ### sendRequest | Parameter | Type | Description | | --- | --- | --- | | request | HttpRequest | An HttpRequest object with a set endpoint and method. | Returns: - An [HttpResponse](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_httpresponse.htm#apex_classes_restful_http_httpresponse) object with the response details from calling Box's APIs. - `Toolkit.BoxApiException` if there is any missing information from the HttpRequest input. - `null` if there was an issue getting the authentication details for the Service Account. In this case, check `mostRecentError`. ## File Operations ### createFileFromAttachment Available in version 3.46 and above. Salesforce has a String length limit of 6 million characters. Due to string bloat in the base64 encoding/decoding process, this results in an effective file size limit of 4.3 megabytes for synchronous Apex and 8.6 megabytes for asynchronous Apex. | Parameter | Type | Description | | --- | --- | --- | | att | Attachment | The attachment to be converted into a File in Box. | | fileNameOverride | string | Optional - Name of the new file. If no value is passed in, the name of the attachment is used. | | folderIdOverride | string | Optional - Box folder id to place this attachment in. If no value is passed in, the file will be placed in the folder associated with the record that is the parentId of the attachment. If the record-specific folder doesn't exist, it will be created. | | accessToken | string | Optional - if accessToken is sent, that value is used for the Box API call. Otherwise, the default account credentials are used. | Returns: - `string` returned is the id of the Box file that was created. - `null` if there was an error. In this case, check `mostRecentError`. ### getObjectFolderByRecordId | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record id whose root folder id you want to get. | Returns: - `string` returned is the Box folder id of the object root folder for the record id passed in. ## Folder Operations ### getRootFolderId Parameters: - None Returns: - `string` returned is the Box folder id of the Salesforce root folder. ### getObjectFolderByRecordId | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record id whose root folder id you want to get. | Returns: - `string` returned is the Box folder id of the object root folder for the record id passed in. ### getFolderUrl - This method gets the embed widget URL for a particular record so customers can use their own embed logic if desired. - This method respects seamless login settings so the URL will automatically log the user in if seamless login is enabled. | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record id whose root folder id you want to get. | | isMobileContext | boolean | Boolean to indicate whether the URL should be mobile (true) or not (false). | Returns: - `string` returned is a URL that points to the folder associated with the Salesforce record Id passed. This URL is for the Box Embed Widget and can be embedded in any Visualforce page. ### createObjectFolderForRecordId | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record id whose root folder id you want to get. | Returns: - `string` returned is the Box folder Id of the root folder that was created. - If the root folder already existed, the value returned is the Box folder id of the root folder that already existed. ### createFolder | Parameter | Type | Description | | --- | --- | --- | | folderName | string | Name of the folder to be created. Folder names are subject to some restrictions. See here for more details. | | parentFolderId | string | Parent Box folder this folder will be created in. | | accessToken | string | Optional - If accessToken is sent, that value is used for the Box API call,; otherwise, the default service account credentials are used. | Returns: - `string` returned is the Box folder id of the folder that was created. - `null` is returned if a folder is not created. In this case, check `mostRecentError` for details. ### createFolderForRecordId | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record id that a Box folder will be created for. | | folderNameOverride | string | By default, the record's name will be the folder name. If you want to name it something else, send that value here. | | optCreateRootFolder | boolean | Boolean to indicate whether to create the object root folder if it doesn't exist. If false is sent and the root folder does not exist, the call will fail. | Returns: - `string` returned is the Box folder id of the folder that was created. - `null` is returned if a folder is not created. In this case, check `mostRecentError` for details. - If the Salesforce record was already associated with a Box folder, the existing Box folder id is returned. ### moveFolder | Parameter | Type | Description | | --- | --- | --- | | folderId | string | Box folder Id of the folder to be moved. | | newParentFolderId | string | Box folder Id of the folder that will be the new parent folder. | | accessToken | string | Optional - If accessToken is sent, that value is used for the Box API call. Otherwise, the default service account credentials are used. | Returns: - `true` if the folder was moved successfully. - `false` if the folder was not moved successfully. Check `mostRecentError` for details. ### getUrlForFolder | Parameter | Type | Description | | --- | --- | --- | | recordId | id | ID of the record. | Returns: - `pageReference` object with provided URL. - `null` if the parameters are incorrect. ### createFolderForRecordIdFromTemplate | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record ID. | | templateFolderId | string | Source folder which should be the template. | | folderNameOverride | string | Name override of the new folder. | | optCreateRootFolder | boolean | Flag that determines if a root folder is created if it doesn't exist. | Returns: - Newly created `folder Id`. - `null` if the parameters are incorrect. ## Folder Association Methods ### getFolderAssociationsByRecordId | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record id that the folder mapping entries returned are related to. | Returns: - List returned is a collection of all folder mapping entries associated with this record. - Generally, it will be an empty list if no folder mapping entries exist, but under some circumstances, it could be `null`. ### getFolderIdByRecordId | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record id whose folder id you wish to get. | Returns: - `string` returned is the Box folder id associated with the Salesforce record id passed in. ### getRecordIdByFolderId | Parameter | Type | Description | | --- | --- | --- | | folderId | string | Box folder id. | Returns: - `id` returned is the Salesforce record id associated with the Box folder id passed in. ### createFolderAssociation | Parameter | Type | Description | | --- | --- | --- | | recordId | id | Salesforce record Id that is being associated with a box folder. | | folderId | string | Box folder Id being associated with a Salesforce record. | Returns: - `box__FRUP__c` object - The FRUP object returned will be `null` if there was an error (check `mostRecentError`). Upon calling the `commitChanges` method, this FRUP entry will be inserted into the database. This method ensures consistency with other folder associations by not allowing the same folder to be associated with multiple records or vice versa. ## Collaboration Methods Collaborations created by the Box for Salesforce Developer Toolkit will not send collaboration emails to collaborators. Only the service account used for the Box for Salesforce integration will receive a collaboration email. ### createCollaboration | Parameter | Type | Description | | --- | --- | --- | | folderId | string | Box folder id to create a collaboration on. | | boxUserId | string | Box user id to be collaborated (either boxUserId or emailAddress is required but not both). | | emailAddress | box.Toolkit.CollaborationType | Email address of the box user to be. | | collabType | string | Type of collaboration (see the CollaborationType enum definition). | | accessToken | string | Optional - If sent, this value is used for authentication for the box API call; if null, the service account credentials are used. | Returns: - `string` returned is the id of the box collaboration that was created. - `null` returned if there was an error. In this case, check `mostRecentError`. ### createCollaborationOnRecord | Parameter | Type | Description | | --- | --- | --- | | userId | id | Salesforce user id to be collaborated. | | recordId | id | Salesforce record id of the record folder to be collaborated on. | | collabType | box.Toolkit.CollaborationType | Type of collaboration (see the CollaborationType enum definition). | | optCreateFolder | boolean | Boolean to indicate whether to create the Box folder associated for the Salesforce record id if it does not already exist. This also creates the root folder if it did not already exist. If set to false and the folder does not already exist, the call will fail. | Returns: - `string` returned is the id of the Box collaboration that was created. - `null` returned if there was an error. In this case, check `mostRecentError`. ### editCollaboration | Parameter | Type | Description | | --- | --- | --- | | collabId | string | Collaboration ID | | collabType | enum | Box.Toolkit.CollaborationType enum | | accessToken | string | | Returns: - Boolean based on the transaction success. - `false` if the parameters are incorrect. ### deleteCollaboration | Parameter | Type | Description | | --- | --- | --- | | collabId | string | Collaboration ID | | accessToken | string | | Returns: - Boolean based on the transaction success. - `false` if the parameters are incorrect. ## Metadata Check the `toolkit.mostRecentError` value for detailed error responses for all the methods. ### getBoxMetadataByFolderId This method calls the [get metadata instance on folder endpoint](e://get-folders-id-metadata-id-id). | Parameter | Type | Description | | --- | --- | --- | | folderId | string | The ID of the Box Folder for which you want to create metadata. | | scope | string | The scope of the metadata template. Value is one of [global, enterprise]. | | template_key | string | The name of the metadata template. | Returns: - `FolderMetadata` record associated with this folder, scope, and template key. You can find the custom values in `keyValuePairs` variable of this object. `null`, if: - the parameters are incorrect, - access to the folder is missing, - metadata cascade policy is not found. ### createBoxMetadataByFolderId This method calls the [create metadata instance on folder](e://post-folders-id-metadata-id-id) endpoint. | Parameter | Type | Description | | --- | --- | --- | | folderId | string | ID of the Box Folder for which you want to create metadata. | | scope | string | Scope of the metadata template. Value is one of [global, enterprise]. | | template_key | string | Name of the metadata template. | | keyValuePairs | List<KeyValuePair> | This class work as a map. Provide key/value pairs as a list, for the attributes to send to Box Metadata. The key/value mappings follow the same pattern as the API. Number types '3000'and multi select values such as 'Customer;Order'are represented as string inputs in the value field, as regular metadata values seen in the code samples. | Returns: - Newly created `FolderMetadata` object. `null`, if: - the parameters are incorrect, - access to the folder is missing, - metadata cascade policy is not found. ### updateBoxMetadataByFolderId Calls the [update metadata instance on folder](e://put-folders-id-metadata-id-id) endpoint. | Parameter | Type | Description | | --- | --- | --- | | folderId | string | ID of the Box folder for which you want to update metadata. | | scope | string | The scope of the metadata template. Value is one of [global, enterprise] | | template_key | string | The name of the metadata template. | | mdUpdates | List<FolderMetadataUpdate> | Metadata updates. Provide the operation, path, and value. The metadata update records follow the same pattern as the API. Number types (3000) and multi select values such as Customer;Order are represented as string inputs in the value field, just as the regular metadata values in the code samples. | Returns: - Updated `FolderMetadata` object. `null`, if: - the parameters are incorrect, - access to the folder is missing, - metadata cascade policy is not found. ### deleteBoxMetadataFolderId This method call the [delete metadata instance from folder](e://delete-folders-id-metadata-id-id) endpoint. | Parameter | Type | Description | | --- | --- | --- | | folderId | string | ID of the Box folder for which you want to update metadata. | | scope | string | The scope of the metadata template. Value is one of [global, enterprise] | | template_key | string | The name of the metadata template. | Returns: - Boolean based on the transaction success. - `false` can be returned if parameters are incorrect parameters or metadata is not found. ### getMetadataCascadePolicyById This method calls the [get metadata cascade policy from folder](e://get-metadata-cascade-policies-id) endpoint. As it requires an ID, you need to call the `getMetadataCascadePoliciesByFolderId` method first. | Parameter | Type | Description | | --- | --- | --- | | policyId | string | The ID of the cascade policy you want to retrieve. | Returns: - `MetadataCascadePolicy` object retrieved from Box. `null`, if: - the parameters are incorrect, - access to the folder is missing, - metadata cascade policy is not found. ### getMetadataCascadePoliciesByFolderId This method retrieves the cascade policies by providing a folder ID and calling the [get metadata cascade policies](e://get-metadata-cascade-policies) endpoint. | Parameter | Type | Description | Required | | --- | --- | --- | --- | | folderId | string | Specifies for which folder to return the policies. This can't be used on the root folder with ID 0. | Yes | | paginationMarker | string | Defines the position marker at which to begin returning results. This is used for marker-based pagination. | No | | Offset | integer | The offset of the item at which to begin the response. | No | | ownerEnterpriseId | string | Enterprise ID for which to find the metadata cascade policies. If not specified, it defaults to the current enterprise. | No | Returns: - List of `MetadataCascadePolicy` objects retrieved from Box. `null`, if: - the parameters are incorrect, - access to the folder is missing, - metadata cascade policy is not found. ### createMetadataCascadePolicy This method creates cascade policies by providing a Box folder ID, scope, template key, and by calling the [post metadata cascade policies](e://post-metadata-cascade-policies) endpoint. | Parameter | Type | Description | | --- | --- | --- | | folderId | string | ID of the Box folder for which you want to create the metadata cascade policy. | | scope | string | The scope of the metadata cascade policy. Value is one of [global, enterprise] | | template_key | string | The name of the template key. | Returns: - Newly generated `MetadataCascadePolicy`. `null`, if: - the parameters are incorrect, - access to the folder is missing, - metadata cascade policy details are not found. ### deleteMetadataCascadePolicy This method deletes the cascade policies by providing a cascade policy ID and calling the [delete metadata cascade policies ID](e://delete-metadata-cascade-policies-id) endpoint. | Parameter | Type | Description | | --- | --- | --- | | policyId | string | The ID of the cascade policy you want to delete. | Returns: - Boolean based on the transaction success. - `false` is returned if parameters are incorrect, access to the folder is missing, or the metadata cascade policy is not found. ### enableAppActivity This method enables the given folder for App Activities by applying metadata on the folder and cascading it down. | Parameter | Type | Description | | --- | --- | --- | | folderId | string | The ID of the Box folder for which you want to delete metadata. | Returns: - Boolean based on the transaction success. - `false` in case of incorrect parameters. ## Salesforce and Slack ### getIntegrationMappings This toolkit method calls the [get integration mappings](e://get-integration-mappings-slack) endpoint to get the existing mappings. | Parameter | Type | Description | | --- | --- | --- | | integration | String | Slack is currently the only supported value. | | partnerItemId | String | ID of the mapped item on the provided integration side. Example: a Slack channel ID. | Returns: - A list of `IntegrationMapping` objects, - `null` is returned if there are incorrect parameters, the access is missing, or the integration mappings is not found. ### createIntegrationMapping This toolkit method calls the [get integration mappings](e://get-integration-mappings-slack) endpoint to create the mappings. When you map to a Slack channel, `access_management_disabled` is set to `FALSE` by default. This causes an automatic removal of collaborators that are not part of the Slack channel member list. Depending on how your organization sets up sharing in Box, we recommend to either enable `access_ management_disabled` to `TRUE` by using the `setSlackChannelAccessManagementDisabled` method, or use [groups](https://support.box.com/hc/articles/360043694554-Creating-and-Managing-Groups). This ensures no users are removed, regardless of Slack settings. Collaborations are added or removed from Slack when a file is uploaded to a Slack channel. | Parameter | Type | Description | | --- | --- | --- | | integration | String | Slack is currently the only supported value. | | mapping | IntegrationMapping | Apex defined type IntegrationMapping. | Returns: - Boolean based on the transaction success. ### deleteIntegrationMapping This toolkit method calls the [delete integration mappings](e://delete-integration-mappings-slack-id) endpoint to delete a mapping. | Parameter | Type | Description | | --- | --- | --- | | integration | String | Slack is currently the only supported value. | | integrationMappingId | String | Retrieved from getIntegrationMappings. | Returns: - Boolean based on the transaction success. ### mapSfdcRecordToSlackChannel This toolkit method uses the above integration mapping methods and provides a wrapper with four different use cases: 1. If a mapping does not exist in Salesforce or Slack, it creates a folder under the Box for Salesforce folder structure, and an integration mapping to link it with the Slack channel. 2. If a mapping only exists from Salesforce, it continues to use the folder and does not change the location. Creates an integration mapping to link it with the Slack Channel. 3. If a mapping only exists from Slack, it continues to use the folder and create an FRUP record for the Salesforce record to use the existing folder. This folder is likely to be outside of the Salesforce root folder. 4. If Salesforce and Slack have existing mappings but are not related to each other, it throws an error through `Toolkit.mostRecentError` or within a flow action, stating that the mappings already exist. This method/invocable is used in a flow template provided in the Box for Salesforce package `Create Box Folder/Slack Channel Mapping`. When you map to a Slack channel, `access_management_disabled` is set to `FALSE` by default. This causes an automatic removal of collaborators that are not part of the Slack channel member list. Depending on how your organization sets up sharing in Box, we recommend to either enable `access_ management_disabled` to `TRUE` by using the `setSlackChannelAccessManagementDisabled` method, or use [groups](https://support.box.com/hc/articles/360043694554-Creating-and-Managing-Groups). This ensures no users are removed, regardless of Slack settings. Collaborations are added or removed from Slack when a file is uploaded to a Slack channel. | Parameter | Type | Description | | --- | --- | --- | | recordId | ID | Salesforce record ID. | | slackChanneld | String | | | slackWorkspaceOrOrgId | String | If Box for Slack is installed org-wide, provide the Org ID (for example E1234567), or the Workspace ID (e.g. T5555555). | Returns: - Boolean based on the transaction success. ### setSlackChannelAccessManagementDisabled This toolkit method calls the [put integration mappings](e://put-integration-mappings-slack-id) endpoint to update the access management deactivated setting. This method/invocable is used in a flow template provided in the Box for Salesforce package `Create Box Folder/Slack Channel Mapping`. | Parameter | Type | Description | | --- | --- | --- | | channelId | String | | | disabled | Boolean | Indicates whether or not a channel member access to the underlying Box item should be automatically managed. Depending on the type of the channel, access is managed through creating collaborations or shared links. | Returns: - Boolean based on the transaction success. **Reference:** https://developer.box.com/guides/tooling/salesforce-toolkit/methods/ --- ## Untitled *Type: guide | Category: Uploads * Upload All Files in Folder Sometimes an application might want to upload all files from a folder. To do so with the SDKs and the CLI… # Upload All Files in Folder Sometimes an application might want to upload all files from a folder. To do so with the SDKs and the CLI requires traversing the folder tree, finding every file and uploading it accordingly. ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Box.V2; using Box.V2.Auth; using Box.V2.Config; using Box.V2.Converter; using Box.V2.Exceptions; using Box.V2.JWTAuth; using Box.V2.Models; using Newtonsoft.Json; namespace BoxPlayground { public class Program { static void Main (string[] args) { ExecuteMainAsync ().Wait (); } const long CHUNKED_UPLOAD_MINIMUM = 200000; private static async Task ExecuteMainAsync () { var directoryName = "dotnetUploadFolder"; var parentFolderId = "0"; var files = Directory.EnumerateFiles (directoryName); using (FileStream fs = new FileStream ("./config.json", FileMode.Open)) { var session = new BoxJWTAuth (BoxConfig.CreateFromJsonFile (fs)); var client = session.AdminClient (session.AdminToken ()); var folderId = ""; try { var createdFolder = await client.FoldersManager.CreateAsync ( new BoxFolderRequest { Parent = new BoxRequestEntity { Id = parentFolderId }, Name = directoryName }); folderId = createdFolder.Id; } catch (BoxConflictException<BoxFolder> e) { folderId = e.ConflictingItems.FirstOrDefault ().Id; System.Console.WriteLine ($"Found existing folder: {folderId}"); } var fileUploadTasks = new List<Task<BoxFile>> (); foreach (var file in files) { fileUploadTasks.Add (Task.Run ( async () => { System.Console.WriteLine (file); var fileName = file.Split (Path.DirectorySeparatorChar) .Where ((item) => { return item != directoryName; }).FirstOrDefault (); System.Console.WriteLine (fileName); var fileInfo = new FileInfo (file); var preflightRequest = new BoxPreflightCheckRequest { Name = fileName, Size = fileInfo.Length, Parent = new BoxRequestEntity { Id = folderId } }; using (FileStream toUpload = new FileStream (file, FileMode.Open)) { try { var preflightCheck = await client.FilesManager.PreflightCheck (preflightRequest); if (toUpload.Length < CHUNKED_UPLOAD_MINIMUM) { using (SHA1 sha1 = SHA1.Create ()) { var fileUploadRequest = new BoxFileRequest { Name = fileName, Parent = new BoxRequestEntity { Id = folderId } }; var fileSHA = sha1.ComputeHash (toUpload); System.Console.WriteLine (fileSHA); return await client.FilesManager.UploadAsync (fileRequest: fileUploadRequest, stream: toUpload, contentMD5: fileSHA); } } else { return await client.FilesManager.UploadUsingSessionAsync (stream: toUpload, fileName: fileName, folderId: folderId); } } catch (BoxPreflightCheckConflictException<BoxFile> e) { if (toUpload.Length < CHUNKED_UPLOAD_MINIMUM) { using (SHA1 sha1 = SHA1.Create ()) { var fileSHA = sha1.ComputeHash (toUpload); return await client.FilesManager.UploadNewVersionAsync (fileName: e.ConflictingItem.Name, fileId: e.ConflictingItem.Id, stream: toUpload, contentMD5: fileSHA); } } else { await client.FilesManager.UploadFileVersionUsingSessionAsync (fileId: e.ConflictingItem.Id, stream: toUpload); return await client.FilesManager.GetInformationAsync (e.ConflictingItem.Id); } } } })); } var uploaded = await Task.WhenAll (fileUploadTasks); foreach (var file in uploaded) { System.Console.WriteLine (file.Id); } } } } } ``` ``` public class UploadAllFilesInFolder { public static final int CHUNKED_UPLOAD_MINIMUM = 20000; public static void main(String[] args) throws Exception { String directoryName = "javaUploadFolder"; Path configPath = Paths.get("config.json"); Path uploadFolderPath = Paths.get(directoryName); try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) { BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection client = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig); String parentFolderId = "0"; String createdFolderId; BoxFolder createFolderInParentFolder = new BoxFolder(client, parentFolderId); try { BoxFolder.Info createdFolder = createFolderInParentFolder.createFolder(directoryName); System.out.println("Creating folder..."); System.out.println(createdFolder.getID()); createdFolderId = createdFolder.getID(); } catch (BoxAPIException e) { String existingFolderId = getIdFromConflict(e.getMessage()); System.out.println("Found existing folder..."); System.out.println(existingFolderId); createdFolderId = existingFolderId; } ArrayList < BoxFile.Info > uploadedFiles = new ArrayList < > (); try (DirectoryStream < Path > directory = Files.newDirectoryStream(uploadFolderPath)) { for (Path path: directory) { String fileName = path.getFileName().toString(); System.out.println(path); System.out.println(fileName); byte[] fileBytes = Files.readAllBytes(path); int fileSize = fileBytes.length; boolean useChunkedUpload = (fileSize > CHUNKED_UPLOAD_MINIMUM) ? true : false; uploadedFiles.add(uploadEachFile(client, createdFolderId, fileName, fileSize, fileBytes, useChunkedUpload)); } } for (BoxFile.Info file: uploadedFiles) { System.out.println(file.getID()); } } } private static BoxFile.Info uploadEachFile(BoxDeveloperEditionAPIConnection client, String folderId, String fileName, int fileSize, byte[] fileBytes, boolean useChunkedUpload) throws IOException, InterruptedException, NoSuchAlgorithmException { try { BoxFolder folder = new BoxFolder(client, folderId); folder.canUpload(fileName, fileSize); if (useChunkedUpload) { System.out.println("Using chunked upload..."); return folder.uploadLargeFile(new ByteArrayInputStream(fileBytes), fileName, fileSize); } else { System.out.println("Using normal upload..."); MessageDigest md = MessageDigest.getInstance("SHA-1"); try (Formatter formatter = new Formatter()) { for (byte b: md.digest(fileBytes)) { formatter.format("%02x", b); } String fileSHA = formatter.toString(); FileUploadParams fileUpload = new FileUploadParams(); fileUpload.setContent(new ByteArrayInputStream(fileBytes)); fileUpload.setSHA1(fileSHA); fileUpload.setName(fileName); return folder.uploadFile(fileUpload); } } } catch (BoxAPIException e) { if (e.getResponseCode() == 409) { // You can use the ID returned from the conflict error to continue String conflictId = getIdFromConflict(e.getResponse()); System.out.println("Found existing file: " + conflictId); BoxFile uploadFileVersion = new BoxFile(client, conflictId); if (useChunkedUpload) { System.out.println("Using chunked upload..."); return uploadFileVersion.uploadLargeFile(new ByteArrayInputStream(fileBytes), fileSize); } else { System.out.println("Using normal upload..."); MessageDigest md = MessageDigest.getInstance("SHA-1"); try (Formatter formatter = new Formatter()) { for (byte b: md.digest(fileBytes)) { formatter.format("%02x", b); } String fileSHA = formatter.toString(); uploadFileVersion.uploadVersion(new ByteArrayInputStream(fileBytes), fileSHA); return uploadFileVersion.getInfo(); } } } else { throw e; } } } private static String getIdFromConflict(String message) { String id = ""; Pattern p = Pattern.compile("\"id\":\"[0-9]+\""); Pattern p2 = Pattern.compile("[0-9]+"); Matcher m = p.matcher(message); if (m.find()) { String sub = m.group(); Matcher m2 = p2.matcher(sub); if (m2.find()) { id = m2.group(); } } return id; } } ``` ``` "use strict"; const fs = require("fs"); const path = require("path"); const box = require("box-node-sdk"); const crypto = require("crypto"); let configFile = fs.readFileSync("config.json"); configFile = JSON.parse(configFile); let session = box.getPreconfiguredInstance(configFile); let client = session.getAppAuthClient("enterprise"); const CHUNKED_UPLOAD_MINIMUM = 200000; const parentFolderId = "0"; const directoryName = "uploadFolder"; let files = []; fs.readdirSync(directoryName).forEach(file => { files.push({ fileName: file, content: fs.readFileSync(path.join(__dirname, directoryName, file)) }); }); client.folders .create(parentFolderId, directoryName) .then(createdFolder => { console.log(createdFolder); return processFiles(client, files, createdFolder.id); }) .catch(err => { let conflictId = handleFolderConflictError(err); if (conflictId) { console.log(`Found an existing folder: ${conflictId}`); return processFiles(client, files, conflictId); } else { throw err; } }) .then(results => { console.log(results); }) .catch(err => { console.log(err); }); function processFiles(client, files, folderId) { let fileUploadPromises = []; files.forEach(file => { fileUploadPromises.push( uploadAFile(client, folderId, file.fileName, file.content) ); }); return Promise.all(fileUploadPromises); } function uploadAFile(client, folderId, fileName, toUploadFile) { return client.files .preflightUploadFile(folderId, { name: fileName, size: toUploadFile.length }) .then(preflightResults => { console.log(preflightResults); if (toUploadFile.length < CHUNKED_UPLOAD_MINIMUM) { console.log("Using normal upload..."); let fileSha = crypto .createHash("sha1") .update(toUploadFile) .digest("hex"); client.setCustomHeader("content-md5", fileSha); return client.files.uploadFile(folderId, fileName, toUploadFile); } else { console.log("Using chunked upload..."); client.setCustomHeader("content-md5", null); return client.files .getChunkedUploader( folderId, toUploadFile.length, fileName, toUploadFile ) .then(uploader => { return new Promise((resolve, reject) => { uploader.on("error", err => { reject(err); }); uploader.on("chunkUploaded", part => { console.log("Part uploaded..."); console.log(part); }); uploader.on("uploadComplete", file => { console.log("File upload complete!"); resolve(file); }); console.log("Starting chunked uploader..."); uploader.start(); }); }); } }) .catch(err => { let conflictId = handleFileConflictError(err); if (conflictId) { console.log(`Found existing file with that name: ${conflictId}`); return uploadANewFileVersion(client, conflictId, toUploadFile); } else { throw err; } }); } function uploadANewFileVersion(client, conflictId, toUploadFile) { if (toUploadFile.length < CHUNKED_UPLOAD_MINIMUM) { console.log("Using normal upload..."); let fileSha = crypto .createHash("sha1") .update(toUploadFile) .digest("hex"); client.setCustomHeader("content-md5", fileSha); // You can optionally rename a folder while uploading a new version. // let newFileName = "ubuntu-no-gui.iso"; // let options = { // name: newFileName // } // return client.files.uploadNewFileVersion(conflictId, options, toUploadFile); return client.files.uploadNewFileVersion(conflictId, toUploadFile); } else { console.log("Using chunked upload..."); // You can optionally rename a folder while uploading a new version. // let newFileName = "ubuntu-no-gui.iso"; // let options = { // name: newFileName // } // return client.files.getNewVersionChunkedUploader(conflictId, toUploadFile.length, toUploadFile, options) client.setCustomHeader("content-md5", null); return client.files .getNewVersionChunkedUploader( conflictId, toUploadFile.length, toUploadFile, null ) .then(uploader => { return new Promise((resolve, reject) => { uploader.on("error", err => { reject(err); }); uploader.on("chunkUploaded", part => { console.log("Part uploaded..."); console.log(part); }); uploader.on("uploadComplete", file => { console.log("File upload complete!"); resolve(file); }); console.log("Starting chunked uploader..."); uploader.start(); }); }); } } function handleFileConflictError(e) { if (e && e.response && e.response.body) { let errorBody = e.response.body; if (errorBody.status === 409) { if ( errorBody.context_info && errorBody.context_info.conflicts && errorBody.context_info.conflicts ) { let conflict = errorBody.context_info.conflicts; if (conflict && conflict.id) { return conflict.id; } } } } } function handleFolderConflictError(e) { if (e && e.response && e.response.body) { let errorBody = e.response.body; if (errorBody.status === 409) { if ( errorBody.context_info && errorBody.context_info.conflicts && errorBody.context_info.conflicts.length > 0 ) { let conflict = errorBody.context_info.conflicts[0]; if (conflict && conflict.id) { return conflict.id; } } } } } ``` ``` box folders:upload ./folder_name_to_upload --parent-folder=$folder_id ``` ## Breakdown The scripts above use the Box SDKs and the CLI to upload an entire folder. For the SDK scripts, they start by creating a directory in Box to match the local folder. After the new directory is created, it uploads all files within the directory making sure to use all available Box features to make the uploads successful. Using the [Preflight](g://uploads/check) API the files are checked for conflicts and size restrictions before they are uploaded. If a naming conflict is found, the script instead uploads a new version of that file. Using the the `SHA` hash of the file the scripts add a `content-md5` header on upload to make sure the file is successfully uploaded to Box without any bytes lost or tampered with. Finally, if a file size exceeds 20MB`, the script uses the Chunked Upload feature to make sure uploads are more reliable for larger files. **Reference:** https://developer.box.com/guides/uploads/chunked/folder/ --- ## Untitled *Type: guide | Category: Uploads * Upload Part When you want to upload a large file, you can split it into smaller parts and upload them using the Upload Part API. Create… # Upload Part When you want to upload a large file, you can split it into smaller parts and upload them using the Upload Part API. ## Create Upload Session First, [create an upload session](g://uploads/chunked/create-session). The resulting object defines the size of each part and the number of parts to upload. ``` { "id": "F971964745A5CD0C001BBE4E58196BFD", "type": "upload_session", "session_expires_at": "2012-12-12T10:53:43-08:00", "part_size": 1024, "total_parts": 1000, "num_parts_processed": 455, "session_endpoints": { "upload_part": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD", "commit": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/commit", "abort": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD", "list_parts": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/parts", "status": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD", "log_event": "https://upload.box.com/api/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/log" } } ``` ## Split File Split the file into parts to be uploaded. If you want to use the command line, use the `split` command: ``` split -b <PART_SIZE> <FILE_NAME> <YOUR_PART_NAME> ``` For example: ``` split -b 8388608 video.mp3 videopart ``` This will result in your file divided into several files. ## Get SHA Digest To get the value for the `SHA` digest, use the following openSSL command to encode the file part: ``` openssl sha1 -binary <FILE_PART_NAME> | base64 ``` For example: ``` openssl sha1 -binary videoparta | base64 ``` The result is a base-64 encoded message used to verify the upload. ## Upload Part Upload the bytes for the part you want to upload, specifying the byte range for the part and the `SHA` digest to ensure the content is uploaded correctly. ### Content Range Each part’s size must be exactly equal in size to the part size specified in the upload session that you created. One exception is the last part of the file, as this can be smaller. The `Content-Range` parameter definition follows this pattern: ``` -H "Content-Range: bytes <LOWER_BOUND>-<HIGHER_BOUND>/<TOTAL_SIZE>" ``` When providing the value for `Content-Range`, remember that: - The lower bound of each part's byte range must be a multiple of the part size. - The higher bound must be a multiple of the part size - 1. For example, if the part size is `8388608`, the content range for the first two parts will be: ``` -H "Content-Range: bytes 0-8388607/32127641" \ ## first part -H "Content-Range: bytes 8388608-16777215/32127641" \ ## second part ``` ## Response After each upload, the resulting response includes the `ID` and `SHA` of the part uploaded. ``` { "part_id": "6F2D3486", "offset": 16777216, "size": 3222784, "sha1": "134b65991ed521fcfe4724b7d814ab8ded5185dc" } ``` Keep all the JSON responses from all part uploads as they are needed to [commit the session](g://uploads/chunked/commit-session). ## Range Overlap If a part upload request fails with any error code `range_overlaps_existing_part` then the application made a mistake in cutting up the file into parts and tried to upload a part into a range that already had content uploaded for it. The application should assume that this last part was not persisted to the session. ## Parallel uploads Although you can upload the parts in parallel, try to upload them in order as much as is possible. Parts with a lower byte offset should be uploaded before parts with a higher byte offset. The recommended approach is to upload 3 to 5 parts in parallel from a queue of parts, ordered by byte offset. If a part upload fails, retry it before you upload further parts. **Reference:** https://developer.box.com/guides/uploads/chunked/upload-part/ --- ## Untitled *Type: guide | Category: Uploads * Upload File Version To upload a new version of a file to Box via direct upload, make an API call to the POST /files/:id/content API with the… # Upload File Version To upload a new version of a file to Box via direct upload, make an API call to the [`POST /files/:id/content`](e://post_files_id_content) API with the content of the file, the desired file name, and the folder ID. # Preflight check To prevent wasting time and bandwidth uploading a file that is going to be rejected it is recommended to perform a [pre-flight check](g://uploads/check) before uploading the file. ## Request Format The request body of this API uses a content type of `multipart/form-data`. This is used to transmit two parts, namely the file attributes and the file's actual content. The first part is called `attributes` and contains a JSON object with information about the file, including the name of the file and the `id` of the parent folder. The following is an example a `test.txt` being uploaded to the root folder of the user. ``` POST /api/2.0/files/123/content HTTP/1.1 Host: upload.box.com Authorization: Bearer [ACCESS_TOKEN] content-length: 343 content-type: multipart/form-data; boundary=------------------------9fd09388d840fef1 --------------------------9fd09388d840fef1 content-disposition: form-data; name="attributes" {"name":"test.txt", "parent":{"id":"0"}} --------------------------9fd09388d840fef1 content-disposition: form-data; name="file"; filename="test.txt" content-type: text/plain Test file text. --------------------------9fd09388d840fef1-- ``` The `attributes` JSON part of the multi-part body must come before the `file` part of the multipart form data. When out of order, the API will return a HTTP `400` status code with an error code of `metadata_after_file_contents`. ## Options To learn more about all the parameters available when uploading files, head over to the [reference documentation for this API call](e://post_files_id_content). These parameters include a `content-md5` that can be set to ensure a file is not corrupted in transit, and the ability to explicitly specify the file creation time at a different time than the upload time. For file versions an additional [`if-match` header](g://api-calls/ensure-consistency) can be passed along to prevent overwriting a file that has already been updated since the application last inspected the content. ## Restrictions Direct uploads are limited to a maximum file size of 50MB. For larger files, please use the [chunked upload APIs](g://uploads/chunked). Upload limits are dictated by the type of account of the authenticated user. More information can be found [in our community article on this topic](https://support.box.com/hc/en-us/articles/360043697314-Understand-the-Maximum-File-Size-You-Can-Upload-to-Box). **Reference:** https://developer.box.com/guides/uploads/direct/file-version/ --- ## Untitled *Type: guide | Category: Uploads * Chunked Upload with SDKs The Box SDKs make it possible to perform a chunked upload with the built-in SDK methods. The SDKs also support… # Chunked Upload with SDKs The Box SDKs make it possible to perform a chunked upload with the built-in SDK methods. The SDKs also support uploading new versions of files through similar methods. **Reference:** https://developer.box.com/guides/uploads/chunked/with-sdks/ --- ## Untitled *Type: guide | Category: Uploads * Direct Uploads The most straightforward way to upload a file to Box is using a direct upload. Direct uploads allow an application to upload… # Direct Uploads The most straightforward way to upload a file to Box is using a direct upload. Direct uploads allow an application to upload a file in one request. For file sizes over 50MB we recommend using the [chunked upload endpoint](g://uploads/chunked). The maximum file size limit for uploads to Box varies depending on your account type. For more details, please refer to our [pricing comparison page](https://www.box.com/pricing). - Free personal: 250 MB - Starter: 2 GB - Business: 5 GB - Business Plus: 15 GB - Enterprise: 50 GB - Digital Workplace Suite: 50 GB - Digital Workplace Global Suite: 50 GB - Digital Business Suite: 50 GB - Digital Business Global Suite: 50 GB - Enterprise Plus: 150 GB - Enterprise Advanced: 500 GB To confirm the file size limit for your account, log into Box. Click on the circle in the top right corner and select **Account Settings** from the dropdown menu. On the page that displays, scroll down to the **Account Details** section. Your **Max File Size** is listed here. ## Upload domain Uploads to Box happen via a different domain (`upload.box.com`) than regular API calls. This is something to keep in mind when writing your own upload code. All official Box SDKs will take care of choosing the right domain for each API call. **Reference:** https://developer.box.com/guides/uploads/direct/ --- ## Untitled *Type: guide | Category: Uploads * Upload New File To upload a file to Box via direct upload, make an API call to the POST /files/content API with the content of the file, the… # Upload New File To upload a file to Box via direct upload, make an API call to the [`POST /files/content`](e://post_files_content) API with the content of the file, the desired file name, and the folder ID. To upload files to the Archive folder, you need to first enable the Global Content Manager (GCM) scope in the Developer Console. # Preflight check To prevent wasting time and bandwidth uploading a file that is going to be rejected it is recommended to perform a [pre-flight check](g://uploads/check) before uploading the file. ## Request Format The request body of this API uses a content type of `multipart/form-data`. This is used to transmit two parts, namely the file attributes and the file's actual content. The first part is called `attributes` and contains a JSON object with information about the file, including the name of the file and the `id` of the parent folder. The following is an example a `test.txt` being uploaded to the root folder of the user. ``` POST /api/2.0/files/content HTTP/1.1 Host: upload.box.com Authorization: Bearer [ACCESS_TOKEN] content-length: 343 content-type: multipart/form-data; boundary=------------------------9fd09388d840fef1 --------------------------9fd09388d840fef1 content-disposition: form-data; name="attributes" {"name":"test.txt", "parent":{"id":"0"}} --------------------------9fd09388d840fef1 content-disposition: form-data; name="file"; filename="test.txt" content-type: text/plain Test file text. --------------------------9fd09388d840fef1-- ``` The `attributes` JSON part of the multi-part body must come before the `file` part of the multipart form data. When out of order, the API will return a HTTP `400` status code with an error code of `metadata_after_file_contents`. ## Options To learn more about all the parameters available when uploading files, head over to the [reference documentation for this API call](e://post_files_content). These parameters include a `content-md5` that can be set to ensure a file is not corrupted in transit, and the ability to explicitly specify the file creation time at a different time than the upload time. ## Restrictions Direct uploads are limited to a maximum file size of 50MB. For larger files, please use the [chunked upload APIs](g://uploads/chunked). Upload limits are dictated by the type of account of the authenticated user. More information can be found [in our community article on this topic](https://community.box.com/t5/Upload-and-Download-Files-and/Understand-the-Maximum-File-Size-You-Can-Upload-to-Box/ta-p/50590). **Reference:** https://developer.box.com/guides/uploads/direct/file/ --- ## Untitled *Type: guide | Category: Tooling * Install .NET SDK (Generated) You can use Box .NET SDK to call Box APIs in a .NET project. The SDK is available for both .NET Framework 4.… # Install .NET SDK (Generated) You can use Box .NET SDK to call Box APIs in a .NET project. The SDK is available for both .NET Framework 4.5 and .NET Core 1.0 or above. The installation of the SDK depends on the framework used. Learn more about .NET SDK on GitHub To install the .NET SDK in the .NET framework, run the following command using the [Nuget](https://www.nuget.org/) package manager. ``` PM> Install-Package Box.Sdk.Gen ``` **Reference:** https://developer.box.com/guides/tooling/sdks/dotnet-gen/ --- ## Untitled *Type: guide | Category: Tooling * Install Java SDK You can use Box Java SDK to call Box APIs in a Java project. To install Java SDK, add a Gradle dependency or Maven… # Install Java SDK You can use Box Java SDK to call Box APIs in a Java project. To install Java SDK, add a Gradle dependency or Maven dependency, or clone the source into a project. Additionally, you can download one of the precompiled JARs from the releases page on GitHub. Learn more about Java SDK on GitHub ## Gradle Add the following dependency to the `build.gradle` file. ``` compile 'com.box:box-java-sdk:2.32.0' ``` For the most up-to-date version number of the Java SDK, please refer to the [Java SDK Open Source page](http://opensource.box.com/box-java-sdk/). ## Maven Add the following to Maven dependency. ``` <dependency> <groupId>com.box</groupId> <artifactId>box-java-sdk</artifactId> <version>2.32.0</version> </dependency> ``` For the most up-to-date version number of the Java SDK, please refer to the [Java SDK Open Source page](http://opensource.box.com/box-java-sdk/). ## Installation from source Download the SDK source from the [Java SDK GitHub repository](https://github.com/box/box-java-sdk/tree/master/src/main/java/com/box/sdk) and add it to a project. ## Precompiled JAR Download one of the precompiled JARs for the Java SDK from the GitHub releases page. When using one of the precompiled JARs, it is important to also add the following additional dependencies to the project. | Dependency | | --- | | minimal-json v0.9.1 | | jose4j v0.4.4 | | bouncycastle bcprov-jdk15on v1.52 | | bouncycastle bcpkix-jdk15on v1.52 | | Java Cryptography Extension (JCE) | **Reference:** https://developer.box.com/guides/tooling/sdks/java/ --- ## Untitled *Type: guide | Category: Tooling * Install .NET SDK (Deprecated) You can use Box .NET SDK to call Box APIs in a .NET project. .NET SDK is currently in maintenance mode and… # Install .NET SDK (Deprecated) You can use Box .NET SDK to call Box APIs in a .NET project. [.NET SDK](https://github.com/box/box-windows-sdk-v2) is currently in maintenance mode and will be deprecated soon. This means only critical security updates and bug fixes will be implemented. It is recommended to use the [auto-generated .NET SDK](https://github.com/box/box-dotnet-sdk-gen). The SDK is available for both .NET Framework 4.5 and .NET Core 1.0 or above. The installation of the SDK depends on the framework used. Learn more about .NET SDK on GitHub ## .NET Framework To install the .NET SDK in the .NET framework, run the following command using the [Nuget](https://www.nuget.org/) package manager. ``` PM> Install-Package Box.V2 ``` ## .NET Core To install the .NET SDK in the .NET Core framework, run the following command using the [Nuget](https://www.nuget.org/) package manager. ``` PM> Install-Package Box.V2.Core ``` **Reference:** https://developer.box.com/guides/tooling/sdks/dotnet/ --- ## Untitled *Type: guide | Category: Tooling * Install Node SDK (Deprecated) You can use Box Node SDK to call Box APIs in a Node project. Node SDK is currently in maintenance mode and… # Install Node SDK (Deprecated) You can use Box Node SDK to call Box APIs in a Node project. [Node SDK](https://github.com/box/box-node-sdk) is currently in maintenance mode and will be deprecated soon. This means only critical security updates and bug fixes will be implemented. It is recommended to use the [auto-generated TypeScript SDK](g://tooling/sdks/typescript-gen). Learn more about Node SDK on GitHub ## NPM installation To install the Node SDK run the following command from your terminal window or command prompt using the [Node Package Manager](https://www.npmjs.com/). ``` npm install box-node-sdk --save ``` ## Yarn installation Similarly, the SDK can be installed using the [Yarn package](https://yarnpkg.com/) manager. ``` yarn add box-node-sdk ``` **Reference:** https://developer.box.com/guides/tooling/sdks/node/ --- ## Untitled *Type: guide | Category: Tooling * SDKs Box offers a set of SDKs you can use to build your application. The next generation .NET SDK is the newest addition to the set. It is… # SDKs Box offers a set of SDKs you can use to build your application. The next generation .NET SDK is the newest addition to the set. It is still a beta feature, but you can give them a try to explore all the features they bring along. The tables below list SDKs along with additional information telling you if the project is maintained and has API parity. **Maintained:** Fully maintained projects are actively developed by Box. They receive the latest security updates and new features. For support with these projects please visit GitHub or [our Platform support forum](https://support.box.com/hc/en-us/community/topics/360001932973-Platform-and-Developer-Forum). **API Parity**: Projects with full API parity are actively updated with all platform functionality as this becomes available on the Box Platform. Projects with partial API parity lack some functionality while we work on bringing these projects to full parity. ## Next generation SDKs The latest generation Box Python SDK, Box TypeScript SDK, .NET SDK, and Swift SDK are designed to elevate the developer experience and streamline your integration with the Box Content Cloud. Swift SDK is in a Public Beta phase. Here's what you can expect from the new SDKs: - **Full API Support**: New Box SDKs empower developers with complete coverage of the Box API ecosystem. You can access all the latest features and functionalities offered by Box and build feature-rich applications. - **Rapid API Updates**: The new auto-generation development approach allows for adding Box APIs to SDKs at a much faster pace (in a matter of days). This means you can leverage the most up-to-date features in your applications without delay. - **Embedded Documentation**: All objects and parameters are documented directly in the source code of the SDK so all the necessary information is stored in one place. - **Enhanced Convenience Methods**: The newly introduced convenience methods cover various aspects such as authentication, chunk uploads, exponential back-offs, automatic retries, type checkers which help to ensure that you’re using variables correctly, and much more. Download the **Box Platform** SDK in a programming language of your choice and get started: | Platform | Maintained? | API Parity | | --- | --- | --- | | Python Gen SDK | Yes | Full | | TypeScript Gen SDK | Yes | Full | | .NET Gen SDK | Yes | Full | | Swift Gen SDK (Beta) | Yes | Full | | Java Gen SDK (Beta) | Yes | Full | ## Legacy SDKs The table lists legacy Box SDKs that you can use when building your applications. For latest API support and features, use the next generation SDKs. | Platform | Maintained? | API Parity | | --- | --- | --- | | Java SDK | Yes | Full | | iOS Content SDK | Yes | Full | | Android Content SDK | No | Partial | | .NET SDK | Deprecated. Only critical security updates and bug fixes are implemented. | Full | | Python SDK | Deprecated. Only critical security updates and bug fixes are implemented. | Full | | Node SDK | Deprecated. Only critical security updates and bug fixes are implemented. | Full | As of May 31, 2023 Android SDK is no longer supported. You can still use your existing Android SDK applications with no impact, but you won't receive new features, updates, or bug fixes. If you would like to continue getting the latest and greatest Android features, use Java SDK to build apps on Android. Refer to [this](https://github.com/box/box-java-sdk/blob/main/doc/android.md) documentation for more details. **Reference:** https://developer.box.com/guides/tooling/sdks/ --- ## Untitled *Type: guide | Category: Tooling * Install Python SDK (Generated) You can use the auto-generated Box Python SDK to call Box APIs in a Python project. This next generation SDK… # Install Python SDK (Generated) You can use the **auto-generated** Box Python SDK to call Box APIs in a Python project. This [next generation SDK](g://tooling/sdks#next-generation-sdks) brings along new functionality to designed to elevate the developer experience and streamline your integration with the Box Content Cloud. Learn more about auto-generated Python SDK on GitHub ## Installation To install the auto-generated Python SDK run the following command from your terminal window or command prompt using [pip](https://pypi.org/project/pip/). ``` pip install box-sdk-gen ``` ## JWT application When working with a Box App that uses server-side [JWT authentication](g://authentication/jwt), install the following additional module: ``` pip install "box-sdk-gen[jwt]" ``` **Reference:** https://developer.box.com/guides/tooling/sdks/python-gen/ --- ## Untitled *Type: guide | Category: Tooling * Install Python SDK (Deprecated) You can use Box Python SDK to call Box APIs in a Python project. Python SDK is currently in maintenance mode… # Install Python SDK (Deprecated) You can use Box Python SDK to call Box APIs in a Python project. [Python SDK](https://github.com/box/box-python-sdk) is currently in maintenance mode and will be deprecated soon. This means only critical security updates and bug fixes will be implemented. It is recommended to use the [auto-generated Python SDK](g://tooling/sdks/python-gen). Learn more about Python SDK on GitHub ## Installation To install the Python SDK run the following command from your terminal window or command prompt using [pip](https://pypi.org/project/pip/). ``` pip install boxsdk ``` ## JWT application When working with a Box App that uses server-side [JWT authentication](g://authentication/jwt), install the following additional module: ``` pip install "boxsdk[jwt]" ``` **Reference:** https://developer.box.com/guides/tooling/sdks/python/ --- ## Untitled *Type: guide | Category: Tooling * Install Salesforce SDK The Salesforce SDK can be deployed directly to Sandbox or Developer organizations by using the Deploy to Salesforce… # Install Salesforce SDK The Salesforce SDK can be deployed directly to Sandbox or Developer organizations by using the [Deploy to Salesforce](https://githubsfdeploy.herokuapp.com/?owner=box&repo=box-salesforce-sdk) functionality. "Deploy to Salesforce" functionality is not owned or maintained by Box. The SDK is also distributed as an unmanaged package: - [Production/Developer Package](https://cloud.box.com/Box-Apex-SDK) - [Sandbox Package](https://cloud.box.com/Box-Apex-SDK-Sandbox) Unmanaged packages can't be upgraded once installed in a Salesforce org so future upgrades will have to be applied by cloning the repositories locally and updating classes from your IDE. **Reference:** https://developer.box.com/guides/tooling/sdks/salesforce/ --- ## Untitled *Type: guide | Category: Tooling * Install Swift SDK (Generated) You can use Box Swift SDK to call Box APIs in a Swift project. Swift SDK is in a Public Beta phase. Learn more… # Install Swift SDK (Generated) You can use Box Swift SDK to call Box APIs in a Swift project. Swift SDK is in a Public Beta phase. Learn more about Swift SDK on GitHub ## Swift Package Manager [Swift Package Manager](https://www.swift.org/documentation/package-manager/) is a tool for managing the distribution of Swift code. It is integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies. To add a dependency to your Xcode project: 1. Select **File** > **Add Package Dependency** in your Xcode project. 2. Click the **plus** icon > **Add Package Collection**. 3. Enter the following repository URL: `https://github.com/box/box-swift-sdk-gen.git` and click **Load**. Alternatively you can add a dependency to the dependencies value of your `Package.swift`. For detailed instructions, please see the official documentation for [Swift Package Manager](https://www.swift.org/documentation/package-manager/) and [XCode documentation](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app). ## Carthage Carthage is a decentralized dependency manager which builds your dependencies and provides you with binary frameworks. To add a dependency to `BoxSdkGen`: 1. add the following line to your `Cartfile` : ``` git "https://github.com/box/box-swift-sdk-gen.git" ``` 1. Run: ``` carthage bootstrap --use-xcframeworks ``` 1. Drag the built `xcframework` from **Carthage/Build** into your project. For more detailed instructions, please see the [official documentation for Carthage](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application). **Reference:** https://developer.box.com/guides/tooling/sdks/swift-gen/ --- ## Untitled *Type: guide | Category: Users * Deprovision Users Part of regular Box enterprise maintenance is removing accounts for users that are no longer active in your enterprise… # Deprovision Users Part of regular Box enterprise maintenance is removing accounts for users that are no longer active in your enterprise. When removing a user from your enterprise, you'll need to move all content owned by the user into another account before deleting the user account. The delete user request will fail if the user account still has content in it. An optional `force` parameter is available in the API call, which will force delete the user account along with all content in the account. The standard best practice when decommissioning a user account is to move all content owned by that user into another admin level account or into the application service account. Once moved, you can transfer ownership of the content to a different user or collaborate a different user on the content if needed. ## Deprovisioning Example Use the following code samples to transfer a user's content and then delete the user. When content is being transferred, a new folder is created in the destination user's root folder following this pattern: `employee_email@email.com - employee_name's Files and Folders` ``` 'use strict' const box = require('box-node-sdk'); const fs = require('fs'); let configFile = fs.readFileSync('config.json'); configFile = JSON.parse(configFile); let session = box.getPreconfiguredInstance(configFile); let serviceAccountClient = session.getAppAuthClient('enterprise'); const transferUserID = '3278487052'; (async () => { let serviceAccount = await serviceAccountClient.users.get('me'); let transferredFolder = await serviceAccountClient.enterprise.transferUserContent(transferUserID,serviceAccount.id); console.log(transferredFolder); await serviceAccountClient.users.delete(transferUserID, null); console.log('Completed'); })(); ``` ``` Path configPath = Paths.get("config.json"); try (BufferedReader reader = Files.newBufferedReader(configPath,Charset.forName("UTF-8"))){ String transferUserId = "3277722534"; BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection serviceAccountClient = BoxDeveloperEditionAPIConnection .getAppEnterpriseConnection(boxConfig); BoxUser destinationUser = new BoxUser(serviceAccountClient, BoxUser.getCurrentUser(serviceAccountClient).getID()); try { destinationUser.moveFolderToUser(transferUserId); } catch (BoxAPIException e) {} BoxUser removeUser = new BoxUser(serviceAccountClient, transferUserId); removeUser.delete(false, false); } ``` ``` using(FileStream fs = new FileStream("./config.json", FileMode.Open)) { var config = BoxConfig.CreateFromJsonFile(fs); var session = new BoxJWTAuth(config); var serviceAccountClient = session.AdminClient(session.AdminToken()); var transferUserId = "3276247601"; var serviceAccount = await serviceAccountClient.UsersManager.GetCurrentUserInformationAsync(); var moveAction = await serviceAccountClient.UsersManager.MoveUserFolderAsync(transferUserId,serviceAccount.Id); System.Console.WriteLine(moveAction.Name); await serviceAccountClient.UsersManager.DeleteEnterpriseUserAsync(transferUserId,false,false); } ``` ``` box users:transfer-content $transfer_from_user_id $transfer_to_user_id box users:delete $transfer_from_user_id --yes ``` **Reference:** https://developer.box.com/guides/users/deprovision/ --- ## Untitled *Type: guide | Category: Tooling * Install Typescript SDK (Generated) You can use the auto-generated Box TypeScript SDK to call Box APIs in a TypeScript project. This next… # Install Typescript SDK (Generated) You can use the **auto-generated** Box TypeScript SDK to call Box APIs in a TypeScript project. This [next generation SDK](g://tooling/sdks#next-generation-sdks) brings along new functionality to designed to elevate the developer experience and streamline your integration with the Box Content Cloud. Learn more about auto-generated TypeScript SDK on GitHub ## NPM installation To install the TypeScript SDK run the following command from your terminal window or command prompt using the [Node Package Manager](https://www.npmjs.com/). ``` npm install box-typescript-sdk-gen ``` ## Yarn installation Similarly, the SDK can be installed using the [Yarn package](https://yarnpkg.com/) manager. ``` yarn add box-typescript-sdk-gen ``` **Reference:** https://developer.box.com/guides/tooling/sdks/typescript-gen/ --- ## Untitled *Type: guide | Category: Users * Transfer Files & Folders As part of user account deprovisioning, a common requirement is to transfer all files and folders that are stored… # Transfer Files & Folders As part of user account deprovisioning, a common requirement is to transfer all files and folders that are stored within the user account to another user account or into a location for long term storage, such as into the service account. There are two general methods that are employed to accomplish this within Box: - Using the direct [transfer owned folders](e://put_users_id_folders_0) API, which will move all content from one user directly to another. - Using the collaboration transfer method to change ownership of one file or folder at a time from one user to another. Files owned by a user will be inaccessible while they are being transferred. This also means that any shared content owned by the user may be inaccessible during the move. Depending on the volume of content, this operation may take a significant amount of time. ## Transfer Owned Folders API Method The [transfer owned folders endpoint](e://put_users_id_folders_0) is designed to move the entirety of content owned by one user over to another user. The transfer owned folders API is performed as a synchronous process, which might lead to a slow response when the source user has a large number of items in all of its folders. To call the transfer endpoint, you will supply the user ID to transfer from and the user ID to transfer to. ## Collaboration Transfer Method The collaboration transfer method is a process that uses the [collaboration endpoint](e://post_collaborations) to change the ownership of a single file or folder from one user to another instantaneously. This method will perform an instantaneous transfer of ownership of a single file or folder, but **cannot** be used to transfer the root (all files and folders) from one user to another. The general process, between `transfer_from_user` to `transfer_to_user`, will follow these steps: ### Add Transfer To User as Co-Owner The first step is to add the `transfer_to_user` account as a collaborator with `co-owner` access on the file or folder that should be transferred. Making the call as the `transfer_from_user` account, add the `transfer_to_user` as a co-owner using the [add collaboration endpoint](e://post_collaborations). ### Fetch Collaboration ID as Transfer To User The next step is make a request to get the collaboration information, making the request as the `transfer_to_user` account. The collaboration object returned will include a collaboration ID, which is used for the last step. Making the call as the `transfer_to_user` account, get the collaboration on the file or folder ID being transferred, using the [get collaboration endpoint](e://get_collaborations_id). Capture the collaboration ID. ### Remove Transfer From User as Owner The final step is to remove the `transfer_from_user` account as an owner of the file or folder, which is accomplished using the [delete collaboration endpoint](e://delete_collaborations_id). Making call as the `transfer_to_user` account, remove the `transfer_from_user` as a collaborator on the file or folder. The file or folder is now owned by the `transfer_to_user` account, and the `transfer_from_user` account no longer has access. **Reference:** https://developer.box.com/guides/users/deprovision/transfer-folders/ --- ## Untitled *Type: guide | Category: Users * Provision Users When setting up a brand new Box user account, a common need is to have that new account be populated with standard folders… # Provision Users When setting up a brand new Box user account, a common need is to have that new account be populated with standard folders, collaborations, and group associations. Typically there are some common questions that may be asked about the user account to determine when standard setup may be needed for the account: - Will the user need access to standard company files or folders immediately? - Are collaborations associated individually or through groups? If through a group association, are there any standard groups that the user should be added to? - Should the user be assigned any tasks to complete? - Would any instructional comments on any files be helpful? # New User Password Resets and Email Confirmation You may experience some errors when creating users and immediately trying to take actions with that user through the API. For example, a common error to receive is `user_email_confirmation_required` or `password_reset_required`. These kinds of errors may block some actions within the API, but you can still add the user as a collaborator on folders, add the user to groups, etc. ## Sample Overview In this scenario we'll focus on provisioning a new [Box Managed User](page://platform/user-types/#managed-users), as there are very different considerations when provisioning Box App User accounts. We'll start with solving the most repeatable aspects of provisioning a user's account, creating a general folder and file structure that everyone will have on first login, using groups to control access to shared files and folders for users. **Reference:** https://developer.box.com/guides/users/provision/ --- ## Untitled *Type: guide | Category: Users * Create Architecture Skeleton Our first requirement is to copy general files and folders into each individual user's root folder on account… # Create Architecture Skeleton Our first requirement is to copy general files and folders into each individual user's root folder on account creation. This problem has been solved within standard Linux distributions through a directory called `/etc/skel`, which we'll emulate with a Box specific solution here. When adding a new user in Linux, the files and folders within `/etc/skel` are copied to the new user's home directory. When creating a [JWT-based Box application](g://authentication/jwt/jwt-setup), a [Service Account](page://platform/user-types/#service-account) is created within the Box Enterprise. A Service Account is similar in functionality to a co-admin within a Box Enterprise, and most useful to this use case, can own, copy, and collaborate other users on files and folders. More importantly, you don't have to use a Service Account strictly for developing platform applications for users, and instead, can use a Service Account in more of an automation capacity. # Box Platform Application Requirements When creating your JWT-based custom Box application for this recipe, you'll need to enable the following scopes: **Manage users**, **Manage groups**, **Perform Actions as Users**, and **Generate User Access Tokens**. See [JWT Application Setup](g://authentication/jwt/jwt-setup) for more information on creating a JWT-based Box application and the scopes in a Box application. We'll start by creating the `etc` and `skel` folders and granting ownership of the folders to the Service Account. ``` { "name": "etc", "parent": { "id": "0" }, "children": [ { "name": "skel", "children": [] } ] } ``` ``` [ { "name": "Market Research", "parent": { "id": "44884797174" }, "children": [ { "name": "Statistics", "children": [ { "name": "Computed", "children": [] } ] } ] }, { "name": "Sales Plays", "parent": { "id": "44884797174" }, "children": [ { "name": "Big Pharma", "children": [] } ] } ] ``` The code here can optionally be reused to build any folder structure formatted as the JSON objects above demonstrate. ``` "use strict"; const fs = require("fs"); const box = require("box-node-sdk"); class BoxFolderTreeCreator { constructor(boxClient, options) { options = options || {}; if (options.boxClient) { throw new Error("Must include a boxClient field."); } options.boxFolderTreeName = options.boxFolderTreeName || "tree.json"; this.boxClient = boxClient; this.boxFolderTree = JSON.parse(fs.readFileSync(options.boxFolderTreeName)); this.createdBoxFolders = []; } async createFolderTree(branch = null, parentFolderId = "0") { this.createdBoxFolders = []; if (Array.isArray(this.boxFolderTree)) { let folderTasks = []; this.boxFolderTree.forEach(folder => { folderTasks.push(this._createFolder(folder, "")); }); await Promise.all(folderTasks); return this.createdBoxFolders; } else if (typeof this.boxFolderTree === "object") { console.log("Is object"); await this._createFolders(this.boxFolderTree, ""); return this.createdBoxFolders; } else { throw new Error("Incorrectly formatted JSON folder tree."); } } async _createFolders(branch, parentFolderId = "0") { if (branch.parent != null && branch.parent.id != null) { parentFolderId = branch.parent.id; } let folder; try { folder = await this.boxClient.folders.create(parentFolderId, branch.name); } catch (e) { let existingFolderId = BoxFolderTreeCreator.handleFolderConflictError(e); folder = await this.boxClient.folders.get(existingFolderId); } this.createdBoxFolders.push(folder); if (branch.children.length <= 0) { console.log("No more folders to create..."); return; } else { let createFolderTasks = []; branch.children.forEach(child => { console.log("Creating folder..."); console.log(child.name); createFolderTasks.push(this._createFolders(child, folder.id)); }); return await Promise.all(createFolderTasks); } } static handleFolderConflictError(e) { if (e && e.response && e.response.body) { let errorBody = e.response.body; if (errorBody.status === 409) { if ( errorBody.context_info && errorBody.context_info.conflicts && errorBody.context_info.conflicts.length > 0 ) { let conflict = errorBody.context_info.conflicts[0]; if (conflict && conflict.id) { return conflict.id; } } } } } } let configFile = fs.readFileSync("config.json"); configFile = JSON.parse(configFile); let session = box.getPreconfiguredInstance(configFile); let serviceAccountClient = session.getAppAuthClient("enterprise"); let treeCreator = new BoxFolderTreeCreator(serviceAccountClient); (async () => { let createdFolders = await treeCreator.createFolderTree(); console.log(createdFolders); })(); ``` ``` package com.box; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.box.sdk.BoxAPIException; import com.box.sdk.BoxConfig; import com.box.sdk.BoxDeveloperEditionAPIConnection; import com.box.sdk.BoxFolder; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; public class BoxFolderTreeCreator { private BoxDeveloperEditionAPIConnection _boxClient; private JsonValue _boxFolderTree; private ArrayList<BoxFolder.Info > _createdFolders; public BoxFolderTreeCreator(BoxDeveloperEditionAPIConnection boxClient) throws IOException { this(boxClient, "tree.json"); } public BoxFolderTreeCreator(BoxDeveloperEditionAPIConnection boxClient, String folderTreeFileName) throws IOException { this._boxClient = boxClient; try (BufferedReader tree = Files.newBufferedReader(Paths.get(folderTreeFileName))) { this._boxFolderTree = JsonValue.readFrom(tree); } this._createdFolders = new ArrayList<>(); } public ArrayList<BoxFolder.Info > createFolderTree() { if (this._boxFolderTree.isArray()) { for (JsonValue folder: this._boxFolderTree.asArray()) { System.out.println("Processing this folder: " + folder); _createFolders(folder.asObject(), null); } return this._createdFolders; } else { _createFolders(this._boxFolderTree.asObject(), null); return this._createdFolders; } } private void _createFolders(JsonObject branch, String parentFolderID) { if (parentFolderID == null && branch.get("parent") != null && branch.get("parent").asObject().get("id") != null) { System.out.println("Looking for parent folder id..."); System.out.println(branch.get("parent").asObject().get("id").asString()); parentFolderID = branch.get("parent").asObject().get("id").asString(); } System.out.println("Folder name:"); System.out.println(branch.get("name")); System.out.println("Parent Folder ID:"); System.out.println(parentFolderID); BoxFolder.Info createdFolder; try { BoxFolder parent = new BoxFolder(this._boxClient, parentFolderID); createdFolder = parent.createFolder(branch.get("name").asString()); } catch (BoxAPIException e) { if (e.getResponseCode() == 409) { // Use the ID returned from the conflict error to continue String conflictId = getIdFromConflict(e.getResponse()); createdFolder = new BoxFolder(this._boxClient, conflictId).getInfo(); } else { throw e; } } this._createdFolders.add(createdFolder); if (!branch.get("children").asArray().isEmpty()) { for (JsonValue child: branch.get("children").asArray()) { _createFolders(child.asObject(), createdFolder.getID()); } } else { return; } } private static String getIdFromConflict(String message) { String id = ""; Pattern p = Pattern.compile("\"id\":\"[0-9]+\""); Pattern p2 = Pattern.compile("[0-9]+"); Matcher m = p.matcher(message); if (m.find()) { String sub = m.group(); Matcher m2 = p2.matcher(sub); if (m2.find()) { id = m2.group(); } } return id; } public static void main(String[] args) throws Exception { Path configPath = Paths.get("config.json"); try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) { BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection serviceAccountClient = BoxDeveloperEditionAPIConnection .getAppEnterpriseConnection(boxConfig); BoxFolderTreeCreator treeBuilder = new BoxFolderTreeCreator(serviceAccountClient, "etc_skel.json"); ArrayList<BoxFolder.Info > folders = treeBuilder.createFolderTree(); for (BoxFolder.Info folder: folders) { System.out.println(folder.getID()); } } } } ``` ``` using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Box.V2; using Box.V2.Config; using Box.V2.Exceptions; using Box.V2.JWTAuth; using Box.V2.Models; using Newtonsoft.Json.Linq; namespace BoxPlayground { public class Program { static void Main(string[] args) { ExecuteMainAsync().Wait(); } private static async Task ExecuteMainAsync() { using(FileStream fs = new FileStream("./config.json", FileMode.Open)) { var session = new BoxJWTAuth(BoxConfig.CreateFromJsonFile(fs)); var client = session.AdminClient(session.AdminToken()); var treeCreator = new BoxFolderTreeCreator(client, "etc_skel.json"); var createdFolders = await treeCreator.CreateFolderTree(); foreach(var folder in createdFolders) { System.Console.WriteLine(folder.Name); System.Console.WriteLine(folder.Id); } } } public class BoxFolderTreeCreator { public BoxClient BoxClient { get; set; } public JToken BoxFolderTree { get; set; } public List < BoxFolder > CreatedBoxFolders { get; set; } public BoxFolderTreeCreator(BoxClient boxClient, string boxFolderTreeFileName = "tree.json") { this.BoxClient = boxClient; this.BoxFolderTree = JToken.Parse(File.ReadAllText(boxFolderTreeFileName)); this.CreatedBoxFolders = new List < BoxFolder > (); } public async Task < List < BoxFolder >> CreateFolderTree(dynamic branch = null, string parentFolderId = "0") { this.CreatedBoxFolders = new List < BoxFolder > (); if (this.BoxFolderTree is JArray) { var folderTasks = new List < Task > (); foreach(JObject folder in this.BoxFolderTree) { folderTasks.Add(_createFolder(folder, String.Empty)); } await Task.WhenAll(folderTasks); return this.CreatedBoxFolders; } else if (this.BoxFolderTree is JObject) { System.Console.WriteLine("Is object"); await _createFolder(this.BoxFolderTree as JObject, String.Empty); return this.CreatedBoxFolders; } else { throw new Exception("Incorrectly formatted JSON folder tree."); } } private async Task _createFolder(dynamic branch, string parentFolderId = "0") { if (branch.parent != null && branch.parent.id != null) { parentFolderId = branch.parent.id; } BoxFolder createdFolder; try { createdFolder = await this.BoxClient.FoldersManager.CreateAsync( new BoxFolderRequest { Parent = new BoxRequestEntity { Id = parentFolderId }, Name = branch.name }); } catch(BoxConflictException < BoxFolder > e) { createdFolder = await this.BoxClient.FoldersManager.GetInformationAsync(e.ConflictingItems.FirstOrDefault().Id); } this.CreatedBoxFolders.Add(createdFolder); if (branch.children.Count <= 0) { System.Console.WriteLine("No more folders to create..."); return; } else { var createFolderTasks = new List < Task > (); foreach(var child in branch.children) { System.Console.WriteLine("Creating folder..."); System.Console.WriteLine(child.name); createFolderTasks.Add(_createFolder(child as JObject, createdFolder.Id)); } await Task.WhenAll(createFolderTasks); } } } } } ``` **Reference:** https://developer.box.com/guides/users/provision/architecture/ --- ## Untitled *Type: guide | Category: Users * Populate Content Once the architecture files have been defined through the etc/skel structure in your service account, you can now use the… # Populate Content Once the architecture files have been defined through the `etc/skel` structure in your service account, you can now use the following script to copy anything under the `skel` directly to the new user's root directory. ``` 'use strict' const box = require('box-node-sdk'); const fs = require('fs'); const skelFolderId = "45117847998"; const userID = "275111793"; let configFile = fs.readFileSync('config.json'); configFile = JSON.parse(configFile); let session = box.getPreconfiguredInstance(configFile); let serviceAccountClient = session.getAppAuthClient("enterprise"); (async () => { // The userID can be obtained when creating the user via the // API or by using the search users feature. // The skel folder ID shouldn't ever change unless it's deleted and recreated. await copySkelDirectoryForUser(userID, skelFolderId, serviceAccountClient); })(); async function copySkelDirectoryForUser(userID, skelFolderId, boxClient) { // Enable iterators in case there are more than the // default limit of items under the skel directory. boxClient._useIterators = true; // You collaborate the user temporarily on the skel directory // to copy all items into that user's root folder. let collabSkelFolder; try { collabSkelFolder = await boxClient.collaborations.createWithUserID(userID, skelFolderId, boxClient.collaborationRoles.EDITOR); } catch (e) { // Handle that the collaboration on the skel folder could already exist. if (e.response.body.code === 'user_already_collaborator') { let collaborationsIterator = await boxClient.folders.getCollaborations(skelFolderId); let collaborations = await autoPage(collaborationsIterator); let results = collaborations.filter((collaboration) => { return collaboration.accessible_by.id === userID; }); console.log(results); if (results.length > 0) { collabSkelFolder = results[0]; } else { throw new Error("Couldn't create new collaboration or located existing collaboration."); } } else { throw e; } } console.log(collabSkelFolder); // Switching context to make calls on behalf of the user. // To access this user's root folder, the boxClient needs // to be scoped to make API calls as the user. boxClient.asUser(userID); // Iterate over all the items under the skel directory. let skelFolderItemsIterator = await boxClient.folders.getItems(skelFolderId); let skelFolderCollection = await autoPage(skelFolderItemsIterator); console.log(skelFolderCollection); // Now, as the user, copy the folders and files into // the user's root folder -- folder ID '0'. let copyTasks = []; skelFolderCollection.forEach((item) => { if (item.type === 'folder') { copyTasks.push(boxClient.folders.copy(item.id, '0') .catch((e) => { let itemId = handleConflictError(e); if (itemId) { console.log(itemId); return boxClient.folders.get(itemId); } else { throw e; } })); } else if (item.type === 'file') { copyTasks.push(boxClient.files.copy(item.id, '0') .catch((e) => { let itemId = handleConflictError(e); if (itemId) { console.log(itemId); return boxClient.files.get(itemId); } else { throw e; } })); } else { console.log("Unable to resolve item type to known types..."); } }); let copiedItems = await Promise.all(copyTasks); console.log(copiedItems); // Switching the boxClient context back to that of the service account. boxClient.asSelf(); /* Since the service account owns the skel directory, boxClient needs to make API calls as the service account to remove the temporary collaboration on the skel directory. */ try { await boxClient.collaborations.delete(collabSkelFolder.id); console.log("Removed collaboration on skel..."); } catch (e) { console.log("Couldn't remove skel collaboration..."); console.log(e.respose.body); } function handleConflictError(e) { if (e && e.response && e.response.body) { let errorBody = e.response.body; if (errorBody.status === 409) { if (errorBody.context_info && errorBody.context_info.conflicts && errorBody.context_info.conflicts) { let conflict = errorBody.context_info.conflicts; if (conflict && conflict.id) { return conflict.id; } } } } } function autoPage(iterator, collection = []) { let moveToNextItem = async () => { let item = await iterator.next(); if (item.value) { collection.push(item.value); } if (item.done !== true) { return moveToNextItem(); } else { return collection; } } return moveToNextItem(); } } ``` ``` package com.box; import java.io.BufferedReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.box.sdk.BoxAPIException; import com.box.sdk.BoxCollaboration; import com.box.sdk.BoxConfig; import com.box.sdk.BoxDeveloperEditionAPIConnection; import com.box.sdk.BoxFile; import com.box.sdk.BoxFolder; import com.box.sdk.BoxItem; import com.box.sdk.BoxUser; import com.eclipsesource.json.JsonObject; public class BoxPlayground { public static void main(String[] args) throws Exception { Path configPath = Paths.get("config.json"); try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) { String skelFolderId = "45117847998"; String userId = "275111793"; BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection serviceAccountClient = BoxDeveloperEditionAPIConnection .getAppEnterpriseConnection(boxConfig); BoxDeveloperEditionAPIConnection userClient = BoxDeveloperEditionAPIConnection.getAppUserConnection(userId, boxConfig); BoxFolder skelFolder = new BoxFolder(serviceAccountClient, skelFolderId); BoxCollaboration.Info skelFolderCollaboration; try { skelFolderCollaboration = skelFolder.collaborate(new BoxUser(serviceAccountClient, userId), BoxCollaboration.Role.EDITOR); } catch (BoxAPIException e) { System.out.println("Searching for existing collaborator."); JsonObject errorMessage = JsonObject.readFrom(e.getResponse()); String code = errorMessage.get("code").asString().intern(); if (code == "user_already_collaborator") { System.out.println("Already collaborated..."); Collection<BoxCollaboration.Info > collaborations = skelFolder.getCollaborations(); System.out.println(collaborations.size()); Optional<BoxCollaboration.Info > results = collaborations.stream().filter(c -> { return c.getAccessibleBy().getID().intern() == userId; }).findFirst(); if (results.isPresent()) { skelFolderCollaboration = results.get(); } else { throw new Exception("Couldn't create new collaboration or find existing collaboration."); } } else { throw e; } } System.out.println(skelFolderCollaboration.getID()); BoxFolder collabedSkelFolder = new BoxFolder(userClient, skelFolderId); ArrayList<BoxItem.Info > copiedItems = new ArrayList<>(); for (BoxItem.Info itemInfo: collabedSkelFolder) { if (itemInfo instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; BoxFile copyFile = new BoxFile(userClient, fileInfo.getID()); BoxFile.Info copiedFile; try { copiedFile = copyFile.copy(BoxFolder.getRootFolder(userClient)); } catch (BoxAPIException e) { System.out.println(e.getMessage()); String conflictId = getIdFromConflict(e.getMessage()); System.out.println(conflictId); copiedFile = new BoxFile(userClient, conflictId).getInfo(); } copiedItems.add((BoxItem.Info) copiedFile); } else if (itemInfo instanceof BoxFolder.Info) { BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; BoxFolder copyFolder = new BoxFolder(userClient, folderInfo.getID()); BoxFolder.Info copiedFolder; try { copiedFolder = copyFolder.copy(BoxFolder.getRootFolder(userClient)); } catch (BoxAPIException e) { System.out.println(e.getMessage()); String conflictId = getIdFromConflict(e.getMessage()); System.out.println(conflictId); copiedFolder = new BoxFolder(userClient, conflictId).getInfo(); } copiedItems.add((BoxItem.Info) copiedFolder); } } System.out.println("Copied " + copiedItems.size() + " items from the skel directory."); BoxCollaboration tempSkelCollab = new BoxCollaboration(serviceAccountClient, skelFolderCollaboration.getID()); tempSkelCollab.delete(); System.out.println("Removed temporary skel directory collaboration."); } } private static String getIdFromConflict(String message) { String id = ""; Pattern p = Pattern.compile("\"id\":\"[0-9]+\""); Pattern p2 = Pattern.compile("[0-9]+"); Matcher m = p.matcher(message); if (m.find()) { String sub = m.group(); Matcher m2 = p2.matcher(sub); if (m2.find()) { id = m2.group(); } } return id; } } ``` ``` using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Box.V2; using Box.V2.Config; using Box.V2.Exceptions; using Box.V2.JWTAuth; using Box.V2.Models; using Newtonsoft.Json.Linq; namespace BoxPlayground { public class Program { static void Main(string[] args) { ExecuteMainAsync().Wait(); } private static async Task ExecuteMainAsync() { using(FileStream fs = new FileStream("./config.json", FileMode.Open)) { var skelFolderId = "45117847998"; var userId = "275111793"; var session = new BoxJWTAuth(BoxConfig.CreateFromJsonFile(fs)); var client = session.AdminClient(session.AdminToken()); var userClient = session.UserClient(session.UserToken(userId), userId); BoxCollaboration collabSkelFolder; try { collabSkelFolder = await client.CollaborationsManager.AddCollaborationAsync( new BoxCollaborationRequest { AccessibleBy = new BoxCollaborationUserRequest { Id = userId }, Item = new BoxRequestEntity { Id = skelFolderId, Type = BoxType.folder }, Role = BoxCollaborationRole.Editor.ToString() }); } catch(BoxException e) { var errorMessage = JObject.Parse(e.Message); if (errorMessage.GetValue("code").ToString() == "user_already_collaborator") { System.Console.WriteLine("Already a collaborator"); var collaborations = await client.FoldersManager.GetCollaborationsAsync(skelFolderId); var existingCollab = collaborations.Entries.Find((collaboration) = >{ return collaboration.AccessibleBy.Id == userId; }); if (existingCollab != null) { collabSkelFolder = existingCollab; } else { throw new Exception("Couldn't create new collaboration or find existing collaboration"); } } else { throw e; } } var items = await userClient.FoldersManager.GetFolderItemsAsync(skelFolderId, limit: 1000, autoPaginate: true); var copyTasks = new List < Task < BoxItem >> (); items.Entries.ForEach((item) = >{ if (item.Type == BoxType.folder.ToString()) { copyTasks.Add(userClient.FoldersManager.CopyAsync(new BoxFolderRequest { Id = item.Id, Parent = new BoxRequestEntity { Id = "0" } }).ContinueWith((folder) = >{ try { return (BoxItem) folder.Result; } catch(Exception e) { var errorMessage = JObject.Parse(e.InnerException.Message); if (errorMessage.GetValue("status").ToObject < int > () == 409) { System.Console.WriteLine("Conflict found"); System.Console.WriteLine(errorMessage.SelectToken("context_info.conflicts.id")); return (BoxItem) userClient.FoldersManager.GetInformationAsync(errorMessage.SelectToken("context_info.conflicts.id").ToString()).Result; } else { throw e; } } })); } else if (item.Type == BoxType.file.ToString()) { copyTasks.Add(userClient.FilesManager.CopyAsync(new BoxFileRequest { Id = item.Id, Parent = new BoxRequestEntity { Id = "0" } }).ContinueWith((file) = >{ try { return (BoxItem) file.Result; } catch(Exception e) { var errorMessage = JObject.Parse(e.InnerException.Message); if (errorMessage.GetValue("status").ToObject < int > () == 409) { System.Console.WriteLine("Conflict found"); System.Console.WriteLine(errorMessage.SelectToken("context_info.conflicts.id")); return (BoxItem) userClient.FilesManager.GetInformationAsync(errorMessage.SelectToken("context_info.conflicts.id").ToString()).Result; } else { throw e; } } })); } else { System.Console.WriteLine("Couldn't process this item..."); } }); var copiedItems = await Task.WhenAll(copyTasks); System.Console.WriteLine($ "Copied {copiedItems.Count()} items from the skel directory."); if (await client.CollaborationsManager.RemoveCollaborationAsync(collabSkelFolder.Id)){ System.Console.WriteLine("Removed temporary skel directory collaboration..."); System.Console.WriteLine("Complete!"); } else { System.Console.WriteLine("Something went wrong when removing skel directory collaboration."); } } } } } ``` **Reference:** https://developer.box.com/guides/users/provision/populate-content/ --- ## Untitled *Type: guide | Category: Webhooks * Delete Webhooks V1 webhooks cannot be fully deleted. Instead, the webhook can be set back to Developer Mode by support. Developers can also… # Delete Webhooks V1 webhooks cannot be fully deleted. Instead, the webhook can be set back to Developer Mode by [support](https://support.box.com/hc/en-us/requests/new). Developers can also remove the application from their account by revisiting the enablement URL and clicking **Remove**. **Reference:** https://developer.box.com/guides/webhooks/v1/delete-v1/ --- ## Untitled *Type: guide | Category: Webhooks * Create Webhooks V1 webhooks are created in the Developer Console by following the steps below. Navigate to your application in the Developer… # Create Webhooks V1 webhooks are created in the [Developer Console](https://app.box.com/developers/console) by following the steps below. 1. Navigate to your application in the [Developer Console](https://app.box.com/developers/console) 2. Select the **Webhooks** tab. 3. Click the **Create a new Webhook** button. 4. Fill in the form, including event triggers, an endpoint URL and one or more callback parameters. 5. Click **Save Webhook**. # Callback parameters Unlike the V2 Webhooks, these manual webhooks need to be configured with the data you'd like. This data will be sent as a query string either in the body or as a query parameter, for example `name=Contract.pdf&type=file`. ## Developer Mode By default V1 webhooks only work for users that are listed as application collaborators in the **General Settings** tab in the Developer Console. To enable a webhooks for all users, please [contact support](https://support.box.com). ## Enabling a webhook After creating a webhook, the application must be added to the user's account to begin use. To obtain the URL to add the app, follow the directions below for OAuth 2.0 authentication apps: 1. Navigate to the **Integrations** tab for the application in the [Developer Console](https://app.box.com/developers/console). 2. Click **Submit My App**. Do not worry, you will not be completing the submission process! 3. At the bottom of the page, click **Preview**. 4. Click **Add** For all other authentication types, you will need to contact support to obtain this URL. Webhooks will now trigger for any configured events that are occur in the user's account. **Reference:** https://developer.box.com/guides/webhooks/v1/create-v1/ --- ## Untitled *Type: guide | Category: Users * Setup Shared Folders As a final step to manage access to shared folders, we'll create the folder structures needed within the service… # Setup Shared Folders As a final step to manage access to shared folders, we'll create the folder structures needed within the service account. Then, groups will map to the needed permissions based on user types and level of access needed to those folders. We'll use a Market Department as an example. ``` { "name": "Marketing Department", "parent": { "id": "0" }, "children": [ { "name": "Projects", "children": [] }, { "name": "Newsletter", "children": [ { "name": "Drafts", "children": [] } ] } ] } ``` Working from this sample folder structure, we can use the folder tree creator code we used earlier to create the `etc/skel` structure. That code may be modified to make your own structure. Once created, we'll need the IDs of the folders that each group will need to access. For example, Marketing managers will likely have `editor` access to all folders within the Marketing Department. On the other hand, Marketing project managers will likely need `editor` access to only the `Projects` folder. We'll create two groups and give them these permissions. ``` "use strict"; const fs = require("fs"); const box = require("box-node-sdk"); let configFile = fs.readFileSync("config.json"); configFile = JSON.parse(configFile); let session = box.getPreconfiguredInstance(configFile); let serviceAccountClient = session.getAppAuthClient("enterprise"); const marketingDeptFolderID = "45765309069"; const marketingProjectsFolderID = "45765461670"; const marketingManagersGroupName = "Marketing Managers"; const marketingProjectManagersGroupName = "Marketing Project Managers"; (async () => { let marketingManagerGroup; try { marketingManagerGroup = await serviceAccountClient.groups.create( marketingManagersGroupName, { description: "For Marketing department leadership team.", invitability_level: "admins_only", member_viewability_level: "admins_only" } ); } catch (e) { marketingManagerGroup = await handleGroupConflictError( e, marketingManagersGroupName, serviceAccountClient ); } console.log(marketingManagerGroup); let marketingProjectManagerGroup; try { marketingProjectManagerGroup = await serviceAccountClient.groups.create( marketingProjectManagersGroupName, { description: "All team members who manage Marketing projects.", invitability_level: "admins_and_members", member_viewability_level: "admins_and_members" } ); } catch (e) { marketingProjectManagerGroup = await handleGroupConflictError( e, marketingProjectManagersGroupName, serviceAccountClient ); } console.log(marketingProjectManagerGroup); let collabMarketingManagers; try { collabMarketingManagers = await serviceAccountClient.collaborations.createWithGroupID( marketingManagerGroup.id, marketingDeptFolderID, serviceAccountClient.collaborationRoles.EDITOR ); } catch (e) { collabMarketingManagers = await handleFolderCollaborationConflictError( e, marketingDeptFolderID, marketingManagerGroup.id, serviceAccountClient ); } console.log(collabMarketingManagers); let collabMarketingProjectManagers; try { collabMarketingProjectManagers = await serviceAccountClient.collaborations.createWithGroupID( marketingProjectManagerGroup.id, marketingProjectsFolderID, serviceAccountClient.collaborationRoles.EDITOR ); } catch (e) { collabMarketingProjectManagers = await handleFolderCollaborationConflictError( e, marketingProjectsFolderID, marketingProjectManagerGroup.id, serviceAccountClient ); } console.log(collabMarketingProjectManagers); })(); async function autoPage(iterator, collection = []) { let moveToNextItem = async () => { let item = await iterator.next(); if (item.value) { collection.push(item.value); } if (item.done !== true) { return moveToNextItem(); } else { return collection; } }; return moveToNextItem(); } async function handleGroupConflictError(e, groupName, boxClient) { let storeIteratorSetting = boxClient._useIterators; if (e && e.response && e.response.body && e.response.body.status === 409) { boxClient._useIterators = true; let groupsIterator = await boxClient.groups.getAll({ name: groupName }); let groups = await autoPage(groupsIterator); let results = groups.filter(group => { return group.name === groupName; }); if (results.length > 0) { boxClient._useIterators = storeIteratorSetting; return results[0]; } else { throw new Error("Couldn't create group or find existing group."); } } else { throw e; } } async function handleFolderCollaborationConflictError( e, folderID, groupID, boxClient ) { let storeIteratorSetting = boxClient._useIterators; if (e && e.response && e.response.body && e.response.body.status === 409) { boxClient._useIterators = true; let collaborationsIterator = await boxClient.folders.getCollaborations( folderID ); let collaborations = await autoPage(collaborationsIterator); let results = collaborations.filter(collaboration => { return collaboration.accessible_by.id === groupID; }); console.log(results); if (results.length > 0) { boxClient._useIterators = storeIteratorSetting; return results[0]; } else { throw new Error( "Couldn't create new collaboration or located existing collaboration." ); } } else { throw e; } } ``` ``` package com.box; import java.io.BufferedReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.Optional; import com.box.sdk.BoxAPIException; import com.box.sdk.BoxCollaboration; import com.box.sdk.BoxConfig; import com.box.sdk.BoxDeveloperEditionAPIConnection; import com.box.sdk.BoxFolder; import com.box.sdk.BoxGroup; import com.eclipsesource.json.JsonObject; public class BoxPlayground { public static void main(String[] args) throws Exception { Path configPath = Paths.get("config.json"); try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) { String marketingDeptFolderID = "45765309069"; String marketingProjectsFolderID = "45765461670"; String marketingManagersGroupName = "Marketing Managers"; String marketingProjectManagersGroupName = "Marketing Project Managers"; BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection serviceAccountClient = BoxDeveloperEditionAPIConnection .getAppEnterpriseConnection(boxConfig); BoxGroup.Info marketingManagerGroup; try { marketingManagerGroup = BoxGroup.createGroup(serviceAccountClient, marketingManagersGroupName, null, null, "For Marketing department leadership team.", "admins_only", "admins_only"); } catch (BoxAPIException e) { JsonObject errorMessage = JsonObject.readFrom(e.getResponse()); int status = errorMessage.get("status").asInt(); if (status == 409) { marketingManagerGroup = handleGroupConflictError(marketingManagersGroupName, serviceAccountClient); } else { throw e; } } System.out.println(marketingManagerGroup.getID()); BoxGroup.Info marketingProjectManagerGroup; try { marketingProjectManagerGroup = BoxGroup.createGroup(serviceAccountClient, marketingProjectManagersGroupName, null, null, "All team members who manage Marketing projects.", "admins_and_members", "admins_and_members"); } catch (BoxAPIException e) { JsonObject errorMessage = JsonObject.readFrom(e.getResponse()); int status = errorMessage.get("status").asInt(); if (status == 409) { marketingProjectManagerGroup = handleGroupConflictError(marketingProjectManagersGroupName, serviceAccountClient); } else { throw e; } } System.out.println(marketingProjectManagerGroup.getID()); BoxFolder marketDeptFolder = new BoxFolder(serviceAccountClient, marketingDeptFolderID); BoxCollaboration.Info marketingDeptFolderCollaboration; try { marketingDeptFolderCollaboration = marketDeptFolder.collaborate( new BoxGroup(serviceAccountClient, marketingManagerGroup.getID()), BoxCollaboration.Role.EDITOR); } catch (BoxAPIException e) { System.out.println("Searching for existing collaborator."); JsonObject errorMessage = JsonObject.readFrom(e.getResponse()); int status = errorMessage.get("status").asInt(); if (status == 409) { marketingDeptFolderCollaboration = handleFolderCollaborationConflict(marketDeptFolder, marketingManagerGroup.getID()); } else { throw e; } } System.out.println(marketingDeptFolderCollaboration.getID()); BoxFolder marketingProjectsFolder = new BoxFolder(serviceAccountClient, marketingProjectsFolderID); BoxCollaboration.Info marketingProjectsFolderCollaboration; try { marketingProjectsFolderCollaboration = marketingProjectsFolder.collaborate( new BoxGroup(serviceAccountClient, marketingProjectManagerGroup.getID()), BoxCollaboration.Role.EDITOR); } catch (BoxAPIException e) { System.out.println("Searching for existing collaborator."); JsonObject errorMessage = JsonObject.readFrom(e.getResponse()); int status = errorMessage.get("status").asInt(); if (status == 409) { marketingProjectsFolderCollaboration = handleFolderCollaborationConflict(marketingProjectsFolder, marketingProjectManagerGroup.getID()); } else { throw e; } } System.out.println(marketingProjectsFolderCollaboration.getID()); } } private static BoxCollaboration.Info handleFolderCollaborationConflict(BoxFolder folder, String groupID) throws Exception { System.out.println("Already collaborated..."); Collection<BoxCollaboration.Info > collaborations = folder.getCollaborations(); Optional<BoxCollaboration.Info > results = collaborations.stream().filter(c -> { return c.getAccessibleBy().getID().intern() == groupID.intern(); }).findFirst(); if (results.isPresent()) { return results.get(); } else { throw new Exception("Couldn't create new collaboration or find existing collaboration."); } } private static BoxGroup.Info handleGroupConflictError(String groupName, BoxDeveloperEditionAPIConnection boxClient) throws Exception { Iterable<BoxGroup.Info > groups = BoxGroup.getAllGroupsByName(boxClient, groupName); BoxGroup.Info foundGroup = null; for (BoxGroup.Info group: groups) { if (group.getName().intern() == groupName) { foundGroup = group; break; } } if (foundGroup != null) { return foundGroup; } else { throw new Exception("Couldn't create group or find existing group."); } } } ``` ``` using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Box.V2; using Box.V2.Config; using Box.V2.Exceptions; using Box.V2.JWTAuth; using Box.V2.Models; using Box.V2.Models.Request; using Newtonsoft.Json.Linq; namespace BoxPlayground { public class Program { static void Main(string[] args) { ExecuteMainAsync().Wait(); } private static async Task ExecuteMainAsync() { using(FileStream fs = new FileStream("./config.json", FileMode.Open)) { var marketingDeptFolderId = "45765309069"; var marketingProjectsFolderId = "45765461670"; var marketingManagersGroupName = "Marketing Managers"; var marketingProjectManagersGroupName = "Marketing Project Managers"; var session = new BoxJWTAuth(BoxConfig.CreateFromJsonFile(fs)); var serviceAccountClient = session.AdminClient(session.AdminToken()); BoxGroup marketingManagerGroup; try { marketingManagerGroup = await serviceAccountClient.GroupsManager.CreateAsync(new BoxGroupRequest { Name = marketingManagersGroupName, InvitabilityLevel = "admins_only", MemberViewabilityLevel = "admins_only" }); } catch(BoxException e) { var errorMessage = JObject.Parse(e.Message); if (errorMessage.GetValue("status").ToObject < int > () == 409) { marketingManagerGroup = await HandleGroupConflictError(marketingManagersGroupName, serviceAccountClient); } else { throw e; } } System.Console.WriteLine(marketingManagerGroup.Id); BoxGroup marketingProjectsManagerGroup; try { marketingProjectsManagerGroup = await serviceAccountClient.GroupsManager.CreateAsync(new BoxGroupRequest { Name = marketingProjectManagersGroupName, InvitabilityLevel = "admins_and_members", MemberViewabilityLevel = "admins_and_members" }); } catch(BoxException e) { var errorMessage = JObject.Parse(e.Message); if (errorMessage.GetValue("status").ToObject < int > () == 409) { marketingProjectsManagerGroup = await HandleGroupConflictError(marketingProjectManagersGroupName, serviceAccountClient); } else { throw e; } } System.Console.WriteLine(marketingProjectsManagerGroup.Id); BoxCollaboration marketingManagerCollab; try { marketingManagerCollab = await serviceAccountClient.CollaborationsManager.AddCollaborationAsync( new BoxCollaborationRequest { AccessibleBy = new BoxCollaborationUserRequest { Id = marketingManagerGroup.Id, Type = BoxType.group }, Item = new BoxRequestEntity { Id = marketingDeptFolderId, Type = BoxType.folder }, Role = BoxCollaborationRole.Editor.ToString() }); } catch(BoxException e) { var errorMessage = JObject.Parse(e.Message); if (errorMessage.GetValue("status").ToObject < int > () == 409) { marketingManagerCollab = await HandleFolderCollaborationConflictError(marketingDeptFolderId, marketingManagerGroup.Id, serviceAccountClient); } else { throw e; } } System.Console.WriteLine(marketingManagerCollab.Id); BoxCollaboration marketingProjectsManagerCollab; try { marketingProjectsManagerCollab = await serviceAccountClient.CollaborationsManager.AddCollaborationAsync( new BoxCollaborationRequest { AccessibleBy = new BoxCollaborationUserRequest { Id = marketingProjectsManagerGroup.Id, Type = BoxType.group }, Item = new BoxRequestEntity { Id = marketingProjectsFolderId, Type = BoxType.folder }, Role = BoxCollaborationRole.Editor.ToString() }); } catch(BoxException e) { var errorMessage = JObject.Parse(e.Message); if (errorMessage.GetValue("status").ToObject < int > () == 409) { marketingProjectsManagerCollab = await HandleFolderCollaborationConflictError(marketingProjectsFolderId, marketingProjectsManagerGroup.Id, serviceAccountClient); } else { throw e; } } System.Console.WriteLine(marketingProjectsManagerCollab.Id); } } public async static Task < BoxGroup > HandleGroupConflictError(string groupName, BoxClient boxClient) { System.Console.WriteLine("Found conflict."); var groups = await boxClient.GroupsManager.GetAllGroupsAsync(autoPaginate: true); return groups.Entries.Find((group) = >{ return group.Name == groupName; }); } public async static Task < BoxCollaboration > HandleFolderCollaborationConflictError(string folderId, string groupId, BoxClient boxClient) { System.Console.WriteLine("Already a collaborator"); var collaborations = await boxClient.FoldersManager.GetCollaborationsAsync(folderId); var existingCollab = collaborations.Entries.Find((collaboration) = >{ return collaboration.AccessibleBy.Id == groupId; }); if (existingCollab != null) { return existingCollab; } else { throw new Exception("Couldn't create new collaboration or find existing collaboration"); } } } } ``` ``` box groups:create "Marketing Managers" --invite=admins_only --view-members=admins_only box groups:create "Marketing Project Managers" --invite=admins_and_members --view-members=admins_and_members ``` Once the groups are created, add the user to that group and they will have the prescribed access to the shared folders created within the service account. ``` 'use strict' const fs = require('fs'); const box = require('box-node-sdk'); let configFile = fs.readFileSync('config.json'); configFile = JSON.parse(configFile); let session = box.getPreconfiguredInstance(configFile); let serviceAccountClient = session.getAppAuthClient("enterprise"); const marketingManagerGroupID = "839790214"; const marketingManagerUserID = "275111793"; (async () => { let addedUser; try { addedUser = await serviceAccountClient.groups.addUser(marketingManagerGroupID, marketingManagerUserID, { role: serviceAccountClient.groups.userRoles.ADMIN }); } catch (e) { addedUser = await handleGroupMembershipConflictError(e, marketingManagerGroupID, marketingManagerUserID, serviceAccountClient); } console.log(addedUser); })(); async function autoPage(iterator, collection = []) { let moveToNextItem = async () => { let item = await iterator.next(); if (item.value) { collection.push(item.value); } if (item.done !== true) { return moveToNextItem(); } else { return collection; } } return moveToNextItem(); } async function handleGroupMembershipConflictError(e, groupID, userID, boxClient) { let storeIteratorSetting = boxClient._useIterators; if (e && e.response && e.response.body && e.response.body.status === 409) { boxClient._useIterators = true; let groupMembershipsIterator = await boxClient.groups.getMemberships(groupID); let groupMemberships = await autoPage(groupMembershipsIterator); let results = groupMemberships.filter((groupMembership) => { return groupMembership.user.id === userID; }); if (results.length > 0) { boxClient._useIterators = storeIteratorSetting; return results[0]; } else { throw new Error("Couldn't create group membership or find existing group membership."); } } else { throw e; } } ``` ``` package com.box; import java.io.BufferedReader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import com.box.sdk.BoxAPIException; import com.box.sdk.BoxConfig; import com.box.sdk.BoxDeveloperEditionAPIConnection; import com.box.sdk.BoxGroup; import com.box.sdk.BoxGroupMembership; import com.box.sdk.BoxUser; import com.box.sdk.BoxGroupMembership.Role; import com.eclipsesource.json.JsonObject; public class BoxPlayground { public static void main(String[] args) throws Exception { Path configPath = Paths.get("config.json"); try (BufferedReader reader = Files.newBufferedReader(configPath, Charset.forName("UTF-8"))) { String marketingManagerGroupID = "839982796"; String marketingManagerUserID = "275111793"; BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection serviceAccountClient = BoxDeveloperEditionAPIConnection .getAppEnterpriseConnection(boxConfig); BoxGroupMembership.Info marketingManagerMembership = null; BoxGroup marketingManagerGroup = new BoxGroup(serviceAccountClient, marketingManagerGroupID); try { marketingManagerMembership = marketingManagerGroup .addMembership(new BoxUser(serviceAccountClient, marketingManagerUserID), Role.ADMIN); } catch (BoxAPIException e) { JsonObject errorMessage = JsonObject.readFrom(e.getResponse()); int status = errorMessage.get("status").asInt(); if (status == 409) { System.out.println("Found existing membership"); Iterable<BoxGroupMembership.Info > memberships = marketingManagerGroup.getAllMemberships(); for (BoxGroupMembership.Info membership: memberships) { if (membership.getUser().getID().intern() == marketingManagerUserID) { marketingManagerMembership = membership; break; } } if (marketingManagerMembership == null) { throw new Exception("Couldn't add user to group or find existing membership"); } } else { throw e; } } System.out.println(marketingManagerMembership.getID()); System.out.println(marketingManagerMembership.getRole()); } } } ``` ``` using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Box.V2; using Box.V2.Config; using Box.V2.Exceptions; using Box.V2.JWTAuth; using Box.V2.Models; using Box.V2.Models.Request; using Newtonsoft.Json.Linq; namespace BoxPlayground { public class Program { static void Main(string[] args) { ExecuteMainAsync().Wait(); } private static async Task ExecuteMainAsync() { using(FileStream fs = new FileStream("./config.json", FileMode.Open)) { var marketingManagerGroupId = "839982796"; var marketingManagerUserId = "275111793"; var session = new BoxJWTAuth(BoxConfig.CreateFromJsonFile(fs)); var serviceAccountClient = session.AdminClient(session.AdminToken()); BoxGroupMembership marketingManagerMembership; try { marketingManagerMembership = await serviceAccountClient.GroupsManager.AddMemberToGroupAsync(new BoxGroupMembershipRequest { User = new BoxRequestEntity { Id = marketingManagerUserId }, Group = new BoxGroupRequest { Id = marketingManagerGroupId }, Role = "admin" }); } catch(BoxException e) { var errorMessage = JObject.Parse(e.Message); if (errorMessage.GetValue("status").ToObject < int > () == 409) { var groups = await serviceAccountClient.GroupsManager.GetAllGroupMembershipsForGroupAsync(marketingManagerGroupId, autoPaginate: true); marketingManagerMembership = groups.Entries.Find((group) = >{ return group.User.Id == marketingManagerUserId; }); if (marketingManagerMembership == null) { throw new Exception("Couldn't create new collaboration or find existing collaboration"); } } else { throw e; } } System.Console.WriteLine(marketingManagerMembership.Id); } } } } ``` ``` box groups:membership:add $user_id $group_id --role=admin ``` **Reference:** https://developer.box.com/guides/users/provision/shared-folders/ --- ## Untitled *Type: guide | Category: Webhooks * V1 Webhooks Webhooks created using the Developer Console monitor changes to all files and folders within a user's account. When creating one… # V1 Webhooks Webhooks created using the [Developer Console](https://app.box.com/developers/console) monitor changes to all files and folders within a user's account. When creating one of these webhooks it is not possible specify a specific object to bind the webhook to. To create a webhook for a specific file or folder, you will need to leverage [v2 webhooks](g://webhooks/v2). Webhooks created through this process will not show when listing all webhooks for a user via API call. All V1 webhooks are visible in the **Webhooks** tab in the [Developer Console](https://app.box.com/developers/console). **Reference:** https://developer.box.com/guides/webhooks/v1/ --- ## Untitled *Type: guide | Category: Webhooks * V2 Webhooks Flow When an event triggers a webhook for a file or a folder, it makes a HTTP call to the address specified when the webhook… # V2 Webhooks ## Flow When an event triggers a webhook for a file or a folder, it makes a HTTP call to the `address` specified when the webhook was created. The payload of this call contains some request headers, and a JSON body. ## Payload headers The payload sent by a webhook has the following Box-specific headers. | Header | Description | | --- | --- | | BOX-DELIVERY-ID | A unique ID assigned by Box that identifies the delivered webhook payload. When Box retries a webhook this ID will change, while the ID in the payload body remains the same. | | BOX-DELIVERY-TIMESTAMP | An RFC-3339 timestamp that identifies when the payload was sent. | | BOX-SIGNATURE-PRIMARY | A signature created using the primary signature key configured for this webhook. | | BOX-SIGNATURE-SECONDARY | A signature created using the secondary signature key configured for this webhook. | | BOX-SIGNATURE-VERSION | Value is always 1. | | BOX-SIGNATURE-ALGORITHM | Value is always HmacSHA256 . | For example: ``` BOX-DELIVERY-ID: 673a081b-bb4b-4d45-b4f1-4131a29c1d07 BOX-DELIVERY-TIMESTAMP: 2016-07-11T10:10:33-07:00 BOX-SIGNATURE-PRIMARY: isCeDp7mLR41/MjcSEFLag9bWmpJkgmN80Je4VIESdo= BOX-SIGNATURE-SECONDARY: 1UbiiKS7/2o5vNIlyMh7e5QGCHq8lflWFgEF+YWBugI= BOX-SIGNATURE-VERSION: 1 BOX-SIGNATURE-ALGORITHM: HmacSHA256 USER-AGENT: Box-WH-Client/0.1 ``` We recommend [setting up](g://webhooks/v2/signatures-v2) and [verifying signatures](g://webhooks/v2/signatures-v2) of the webhook payloads. HTTP header names are case insensitive. Your client should convert all header names to a standardized lowercase or uppercase format before trying to determine the value of a header. ## Payload body The body of a webhook payload is a JSON object that describes the file or folder (target) that triggered the webhook, as well as the event that has been triggered. | Field | Description | | --- | --- | | type | Value is always webhook_event. | | id | A unique ID assigned by Box that identifies an event. When Box retries a webhook this ID will not change, while the ID in the header changes between calls. | | created_at | The time/date when an event was triggered at. | | trigger | The name of the action that triggered an event, for example FILE.UPLOADED. | | webhook | The webhook ID for which an event triggered. | | created_by | The user that triggered an event. | | source | The item that triggered an event, for example the file that was uploaded to the target folder. | Example: ``` { "type": "webhook_event", "id": "eb0c4e06-751f-442c-86f8-fd5bb404dbec", "created_at": "2016-07-11T10:10:32-07:00", "trigger": "FILE.UPLOADED", "webhook": { "id": "53", "type": "webhook" }, "created_by": { "type": "user", "id": "226067247", "name": "John Q. Developer", "login": "johnq@dev.name" }, "source": { "id": "73835521473", "type": "file", "file_version": { "type": "file_version", "id": "78096737033", "sha1": "2c61623e86bee78e6ab444af456bccc7a1164095" }, "sequence_id": "0", "etag": "0", "sha1": "2c61623e86bee78e6ab444af456bccc7a1164095", "name": "Test-Image-3.png", "description": "", "size": 26458, "path_collection": { "total_count": 4, "entries": [ { "type": "folder", "id": "0", "sequence_id": null, "etag": null, "name": "All Files" }, { "type": "folder", "id": "2614853901", "sequence_id": "4", "etag": "4", "name": "Testing" }, { "type": "folder", "id": "8290186265", "sequence_id": "0", "etag": "0", "name": "Webhooks Base" }, { "type": "folder", "id": "8290188973", "sequence_id": "0", "etag": "0", "name": "Webhooks" } ] }, "created_at": "2016-07-11T10:10:32-07:00", "modified_at": "2016-07-11T10:10:32-07:00", "trashed_at": null, "purged_at": null, "content_created_at": "2016-06-08T11:14:04-07:00", "content_modified_at": "2016-06-08T11:14:04-07:00", "created_by": { "type": "user", "id": "226067247", "name": "John Q. Developer", "login": "johnq@dev.name" }, "modified_by": { "type": "user", "id": "226067247", "name": "John Q. Developer", "login": "johnq@dev.name" }, "owned_by": { "type": "user", "id": "226067247", "name": "John Q. Developer", "login": "johnq@dev.name" }, "shared_link": null, "parent": { "type": "folder", "id": "8290188973", "sequence_id": "0", "etag": "0", "name": "Webhooks" }, "item_status": "active" }, "additional_info": [] } ``` ## Retries Delivery of a webhook payload fails when Box does not receive a response with a HTTP status code in the `200` to `299` range within 30 seconds of sending the payload. Box will retry webhook deliveries up to 12 times over a period of 2 hours. These numbers could be subject to change. **Reference:** https://developer.box.com/guides/webhooks/v2/ --- ## Untitled *Type: guide | Category: Webhooks * Delete Webhooks You can delete a webhook using the Developer Console or API. Developer Console To delete a webhook follow the steps below… # Delete Webhooks You can delete a webhook using the [Developer Console](https://app.box.com/developers/console) or API. ## Developer Console To delete a webhook follow the steps below. 1. Navigate to the **Webhooks** tab in the [Developer Console](https://app.box.com/developers/console). 2. Select the webhook you want to delete by clicking on its ID. 3. Click the **Delete** button. 4. Confirm the action by clicking **Delete** under the warning message. ## API To remove a webhook from a file or folder, you need to use the [remove webhook endpoint](e://delete-webhooks-id) with the ID of the webhook. You can get this value using the [list all webhooks endpoint](e://get-webhooks). ## Automatic webhook deletion Using [this](e://delete-webhooks-id) endpoint is not the only way a webhook can be deleted. The following reasons can cause webhooks to be deleted. Deleting a Box application automatically deletes all webhooks associated with it. Deleting all active Access Tokens associated with a webhook automatically deletes the webhook. This includes Developer Tokens and password. The last successful notification was delivered 30 days ago to the set URL and the period between the last successful notification delivery and the last user trigger event date exceeds 14 days. Let's go through a scenario in which the user downloads a file. This action triggers the webhook to use the set URL to delete a shared link. The diagram illustrates this scenario, showing when the webhook will be deleted. - **User event trigger**: when the user initiated the event, for example downloaded a file. - **Notification trigger**: when the notification was sent to the webhook, saying that the file was downloaded. - **Last notification delivery**: when the webhook sent a message to a specific URL, for example to delete a shared link. In all of these cases Box sends a webhook payload with the `WEBHOOK.DELETED` event name to the notification URL. The body of the payload includes the following additional information. ``` "additional_info": { "reason": "auto_cleanup" } ``` **Reference:** https://developer.box.com/guides/webhooks/v2/delete-v2/ --- ## Untitled *Type: guide | Category: Webhooks * Limitations One webhook per item There's a limit of one webhook for each item (file or folder), each application and each authenticated user… # Limitations ## One webhook per item There's a limit of one webhook for each item (file or folder), each application and each authenticated user. Once a webhook is attached to an item, no second webhook can be attached, even if the second webhook would respond to a different trigger event. Example: a webhook is set up by `John Doe` to watch `FILE.UPLOADED` events in a folder with the name `Junk`, for an application named `CleanupApp`. At that point, no second webhook can be added to the `Junk` folder by the `CleanupApp` by `John Doe`, even if it is to trigger for an `FILE.DOWNLOADED` event. To listen to another event, [update](g://webhooks/v2/update-v2) the existing webhook or create a new application. ## 1000 webhooks limit There is a limit of 1000 webhooks for each application and each user. To create more webhooks for a user, create another application or [update existing webhooks](g://webhooks/v2/update-v2) to apply to higher levels in the folder tree. ## Notification URL restrictions The notification URL or `address` for a webhook must be a valid HTTPS URL that resolves to a valid IP address. It needs to have a certificate signed by a reputable certificate authority. Box does not support self-signed SSL certificates. The IP address of the server must be publicly accessible from the internet and cannot be a `(*.)box.com` address. The port used in the URL must be the standard HTTPS port (`443`). Notifications will not be delivered to other ports. The supported TLS protocol versions are `TLS 1.2` and `TLS 1.3` with FIPS-compliant cipher suites. ## No webhooks on root folder V2 webhooks cannot be created on the root folder, which is the folder with ID `0`. Instead, you will need to use a [v1 webhook](g://webhooks/v1). When the permissions on an item prevent an action from occurring, no notification is sent for the attempted action. ## NO_ACTIVE_SESSION is set in the webhook payload If the auth session (access token) for the app you used to create a webhook expires, that webhook no longer sends events with a full payload. In that case, the event trigger is `NO_ACTIVE_SESSION`. ### JWT Auth For webhooks created with the JWT Auth app, the session expires when you delete the app authorization for this app in the Admin Console. For more information, see [application authorization guide](https://support.box.com/hc/en-us/articles/360043697014-Authorizing-Apps-in-the-Box-App-Approval-Process). ### OAuth 2.0 For webhooks created with OAuth 2.0 Auth app, the session expires when both the access token and the refresh token for the user and app used for creating that webhook expire. ### Developer token As the developer token cannot be refreshed and expires after 1 hour, the event trigger `NO_ACTIVE_SESSION` is set in the webhook payload after 1 hour. ## Reasons for webhook deletion The following reasons can cause webhooks to be deleted. 1. Deleting a Box application automatically deletes all webhooks associated with it. 2. Deleting all active Access Tokens associated with a webhook automatically deletes the webhook. This includes Developer Tokens and password. 3. A webhook is automatically deleted if the last successful delivery was 30 days ago and the period between the last successful delivery and the last trigger date is more than 14 days. In all of these cases Box sends a webhook payload with the `WEBHOOK.DELETED` event name to the notification URL. The body of the payload includes the following additional information. ``` "additional_info": { "reason": "auto_cleanup" } ``` **Reference:** https://developer.box.com/guides/webhooks/v2/limitations-v2/ --- ## Untitled *Type: guide | Category: Webhooks * Create Webhooks V2 webhooks can monitor specific files or folders. They can be created in the Developer Console and with API. Developer… # Create Webhooks V2 webhooks can monitor specific files or folders. They can be created in the [Developer Console](https://app.box.com/developers/console) and with API. ## Developer console V2 webhooks can be created only when the scope **Manage Webhooks** is selected and the application is authorized. See more about [Required Access Scopes](g://applications) and [authorization](g://authorization). To create a webhook follow the steps below. 1. Navigate to your application in the [Developer Console](https://app.box.com/developers/console). 2. Select the **Webhooks** tab. 3. Click the **Create webhook** button. 4. Select **V2** from the drop-down list. 5. Fill in the form. 6. Click **Create webhook** button to save your changes. ### Required fields | Field name | Description | Required | | --- | --- | --- | | URL Address | URL address to be notified by the webhook. | Yes | | Content type | Type of content (file/folder) the webhook is configured for. | Yes | | Triggers | Different triggers that activate the webhook. | Yes | ## API This API requires the application to have the **Manage Webhooks** scope enabled. To attach a webhook to a file, call the [create webhook](e://post_webhooks) endpoint with the type of `file`, the ID of the file, a URL to send webhook notifications to, and a list of [triggers](g://webhooks/triggers). To attach a webhook to a folder, call the [create webhook](e://post_webhooks) endpoint with the type of `folder`, the ID of the folder, a URL to send webhook notifications to, and a list of [triggers](g://webhooks/triggers). Webhooks do cascade, so if a webhook is set on a parent folder, it will also monitor sub-folders for the selected triggers. ## Ownership It is best practice and strongly recommended to create webhooks with a [Service Account](page://platform/user-types/#service-account), or user that will not be deleted, to avoid potential issues with webhook delivery due to loss of access to content. Similar to files and folders, webhooks are owned by a user. If a user who owns a webhook is deleted, they will lose access to all files and folders that they previously had access to. Their webhooks will begin to fail validation, but the webhook service will continue to send events and require retries. ## Webhook address The notification URL specified in the `address` parameter must be a valid URL that you specify when you create a webhook. Every time one of the triggers is activated, this URL is called. The notification URL must use standard port `443` and should return an HTTP status in the range of `200` to `299` within 30 seconds of receiving the webhook payload. ## Webhook triggers The triggers are a list of strings that specify the events which cause the webhook to fire. For example, if you want the webhook to be triggered when a user uploads a file, use `FILE.UPLOADED`. You can find a list of available triggers [in this guide](g://webhooks/triggers). **Reference:** https://developer.box.com/guides/webhooks/v2/create-v2/ --- ## Untitled *Type: guide | Category: Webhooks * List Webhooks for a User To fetch all webhooks for the authenticated user, use the list all webhooks endpoint. This endpoint requires the… # List Webhooks for a User To fetch all webhooks for the authenticated user, use the [list all webhooks](endpoint://get_webhooks) endpoint. This endpoint requires the application to have the **Manage Webhooks** scope enabled. This API call will only list the webhooks for the authenticated user, not for any other users in the enterprise. **Reference:** https://developer.box.com/guides/webhooks/v2/list-v2/ --- ## Untitled *Type: guide | Category: Webhooks * Signature Verification Webhook signatures help ensure that a webhook payload was sent by Box and was not tampered with. Signatures greatly… # Signature Verification Webhook signatures help ensure that a webhook payload was sent by Box and was not tampered with. Signatures greatly reduce the likelihood of a successful man-in-the-middle or replay attacks. When signatures are configured, Box generates a cryptographic digest of the notification's body and attaches it to the header of the webhook payload. When your application receives the payload, verify the signatures by calculating the same digest and comparing it to the one received. If the digests do not match, the payload should not be trusted. You can achieve an extra level of protection by frequently changing the signature keys. To enable a smooth transition between the old and new keys, Box supports two simultaneous signature keys. ## Signature configuration In order to attach signatures to an application's notifications, you must first generate signature keys for the application. To configure your application's keys follow the steps below. 1. Navigate to the application in the developer console. 2. Click on the **Webhooks** tab. 3. Click the **Manage signature keys** button. 4. Click the **Generate Key** button to configure your keys. Once generating the primary or secondary key, copy the value. You will need it to verify the webhook payloads. Every webhook will now include a `BOX-SIGNATURE-PRIMARY` and `BOX-SIGNATURE-SECONDARY` header payload. ## Signature verification with SDKs Although it is possible to verify signatures manually, methods are provided for your convenience in the [official Box SDKs](g://tooling/sdks). ## Manual signature verification The following steps describe the basics of how to verify a signature. ### Timestamp validation Check if the timestamp in the `BOX-DELIVERY-TIMESTAMP` header of the payload is not older than ten minutes. ``` var timestamp = headers['BOX-DELIVERY-TIMESTAMP']; var date = Date.parse(timestamp); var expired = Date.now() - date > 10*60*1000; ``` ``` import dateutil.parser import pytz import datetime timestamp = headers["BOX-DELIVERY-TIMESTAMP"] date = dateutil.parser.parse(timestamp).astimezone(pytz.utc) now = datetime.datetime.now(pytz.utc) delta = datetime.timedelta(minutes=10) expiry_date = now - deltaMinutes expired = date >= expiry_date ``` ### Calculate HMAC signature Calculate the HMAC of the payload using either one of the two configured signatures for the application in the [Developer Console](https://app.box.com/developers/console). Ensure you append the bytes of the payload body first, and then the bytes of the timestamp found in the `BOX-DELIVERY-TIMESTAMP` header. ``` var crypto = require('crypto'); var primaryKey = '...'; var secondaryKey = '...'; var payload = '{"type":"webhook_event"...}'; var hmac1 = crypto.createHmac('sha256', primaryKey); hmac1.update(payload); hmac1.update(timestamp); var hmac2 = crypto.createHmac('sha256', secondaryKey); hmac2.update(payload); hmac2.update(timestamp); ``` ``` import hmac import hashlib primary_key = '...' secondary_key = '...' payload = "{\"type\":\"webhook_event\"...}" bytes = bytes(payload, 'utf-8') + bytes(timestamp, 'utf-8') hmac1 = hmac.new(primary_key, bytes, hashlib.sha256).digest() hmac2 = hmac.new(secondary_key, bytes, hashlib.sha256).digest() ``` ### Base64 Conversion Convert the HMAC to a `Base64` encoded digest. ``` var digest1 = hmac1.digest('base64'); var digest2 = hmac2.digest('base64'); ``` ``` import base64 digest1 = base64.b64encode(hmac1) digest2 = base64.b64encode(hmac2) ``` ### Signature comparison Compare the encoded digest with the value of the `BOX-SIGNATURE-PRIMARY` or `BOX-SIGNATURE-SECONDARY` headers. Compare the value of the `BOX-SIGNATURE-PRIMARY` header to the digest created with the primary key, and the value of the `BOX-SIGNATURE-SECONDARY` header to the digest created with the secondary key. Make sure to use a timing-safe comparison between signatures to prevent timing attacks. ``` const crypto = require('crypto'); function compareSignatures(expectedSignature, receivedSignature) { const expectedBuffer = Buffer.from(expectedSignature, 'base64'); const receivedBuffer = Buffer.from(receivedSignature, 'base64'); if (expectedBuffer.length !== receivedBuffer.length) { return false; } return crypto.timingSafeEqual(expectedBuffer, receivedBuffer); } const signature1 = headers['BOX-SIGNATURE-SECONDARY']; const signature2 = headers['BOX-SIGNATURE-PRIMARY']; const primarySignatureValid = compareSignatures(digest1, signature1) const secondarySignatureValid = compareSignatures(digest2, signature2) const valid = !expired && (primarySignatureValid || secondarySignatureValid) ``` ``` import hmac def compare_signatures(expected_signature: Optional[str], received_signature: Optional[str]) -> bool: if not expected_signature or not received_signature: return False if len(expected_signature) != len(received_signature): return False return hmac.compare_digest(expected_signature, received_signature) signature1 = headers["BOX-SIGNATURE-SECONDARY"] signature2 = headers["BOX-SIGNATURE-PRIMARY"] primary_sig_valid = compare_signatures(digest1, signature1) secondary_sig_valid = compare_signatures(digest2, signature2) valid = not expired and (primary_sig_valid or secondary_sig_valid) ``` HTTP header names are case insensitive. Your client should convert all header names to a standardized lowercase or uppercase format before trying to determine the value of a header. ## Rotate signatures When enabled, Box sends two signatures with every webhook payload. Your application can trust a payload as long as at least one of its signatures is valid. When updating one signature key at a time your application will always receive a payload with at least one valid signature. ### Rotation steps These instructions assume that you have already created a primary and secondary key in the [Developer Console](https://app.box.com/developers/console) and you are ready to replace either of them. By following these steps you can configure your application with two new keys without any conflicts. 1. Go to the **Webhooks** tab in the [Developer Console](https://app.box.com/developers/console). 2. Click the **Manage signatures keys**. 3. Click the **Reset** button to change the primary key. 4. Update your application with the new primary key. Your application can still receive notifications with the old primary key, but your webhooks should be processed correctly since the secondary key is still valid. 5. Once you are confident that no webhooks with the old primary key are in-flight, you can update the secondary key using the same process. **Reference:** https://developer.box.com/guides/webhooks/v2/signatures-v2/ --- ## Untitled *Type: guide | Category: Webhooks * Update Webhooks You can update a webhook using the Developer Console or API. Developer Console To update a webhook in the Developer Console… # Update Webhooks You can update a webhook using the [Developer Console](https://app.box.com/developers/console) or API. ## Developer Console To update a webhook in the [Developer Console](https://app.box.com/developers/console), follow the steps below. 1. Go to the **Webhooks** tab in the [Developer Console](https://app.box.com/developers/console) to display all webhooks. 2. Select the webhook you want to update by clicking on its ID. 3. Click the **Edit webhook** button. 4. Fill in the data you want to update. 5. Click the **Update** button to save your changes. The list of webhooks contains the following fields: **ID**, **Address**, **Content**, **Created by**, and **Created date**. ## API To update a webhook, use the [update webhook](e://put-webhooks-id) endpoint, which requires the webhook ID. To find the ID of the webhook, use the [list all webhooks](g://webhooks/v2/list-v2) endpoint. **Reference:** https://developer.box.com/guides/webhooks/v2/update-v2/ --- ## Untitled *Type: guide | Category: Metadata * Delete a metadata template Deleting a metadata template can be achieved by calling the DELETE /metadata_templates/enterprise/:templateKey… # Delete a metadata template Deleting a metadata template can be achieved by calling the [`DELETE /metadata_templates/enterprise/:templateKey/schema`](e://delete_metadata_templates_id_id_schema) API. This API returns a `204 No Content` API response with no response body when the template has been successfully deleted. This API also removes all the template instances from any files and folders. Only templates created within the `enterprise` scope can be deleted. # Admin permissions required Deleting metadata templates is restricted to users with admin permission. This means that only admins, or co-admins who have been granted rights to Create and edit metadata templates for your company by the admin can use the web app or the API to manage templates. **Reference:** https://developer.box.com/guides/metadata/templates/delete/ --- ## Untitled *Type: quick-start | Category: Mobile * Configure a Box Platform App To start making authenticated API calls to the Box API with the Box iOS SDK, an Access Token will be needed… # Configure a Box Platform App To start making authenticated API calls to the Box API with the **Box iOS SDK**, an **Access Token** will be needed. The simplest way to generate a valid token is to generate a new **Box Platform App** and manually generate a short lived developer token. The developer token is generated through the developer console UI and will be valid for one hour before having to be manually refreshed. ## Set up a Box app # Create a new Box app Create and configure a new Box JWT application from which a developer token may be generated. # Use an existing app Use one of your existing Box JWT applications from the Box developer console. # Create a new Box app To create a new Box application that may be used to generate a developer token, use the following steps. 1. Go to the [Developer Console](https://cloud.app.box.com/developers/console) > **My Platform Apps**. 2. Select **Create Platform App**. 3. Select **Platform App** as the type of application to create, and click **Next**. 4. Enter the **App Name**, an optional **Description** and **Purpose** of the App. Confirm with **Next**. 5. Select **User Authentication (OAuth 2.0)** as the authentication method, and click **Create App** 6. Optionally, scroll to the **Application Scopes** section of the same screen and select any additional permissions you want to enable for this application. 7. At the top of the page click the button to **Save Changes**. # Use an Existing JWT Box application If you have an existing JWT based Box application in your [developer console](https://cloud.app.box.com/developers/console) that you would like to use, skip to the next step. ## Generate a developer token Now that an application is available, we need to create a developer token that may be used to authenticate the Box iOS SDK to start making calls to the Box APIs. 1. Go to the [Developer Console](https://cloud.app.box.com/developers/console) 2. Load the application that you would like to use 3. In the left navigation menu, click on **Configuration** 4. Under **Developer Token**, click the **Generate Developer Token** button 5. Copy the token for the next step to make an API call ## Summary - You created a new, or are using an existing, Box app - You have generated and copied the developer token I have a developer token **Reference:** https://developer.box.com/guides/mobile/ios/quick-start/configure-box-app/ --- ## Untitled *Type: quick-start | Category: Mobile * Create an iOS App Before installing the Box iOS SDK you'll need to have an iOS application available to add the dependencies into. We'll… # Create an iOS App Before installing the Box iOS SDK you'll need to have an iOS application available to add the dependencies into. We'll create a new blank application now. ## Setup an iOS App Xcode will be the tool that we use to create and edit our iOS application during this quick-start guide. If you don't have Xcode, download it now from the [Apple developer site](https://developer.apple.com/xcode/). If this is the first application you're creating in Xcode or you already have application development experience in it, we'll start our integration of the Box iOS SDK with a new blank application. 1. Start Xcode 2. From the top menu, select **File** -> **New** -> **Project...** Select the option for **Single View App** Enter your application configuration information, including the `Product Name`, `Organization Identifier`, and `Organization Name`. 1. Select a local storage location for the application and click **Create** ## Summary - You created a new blank iOS application in Xcode I created a blank iOS application **Reference:** https://developer.box.com/guides/mobile/ios/quick-start/create-ios-app/ --- ## Untitled *Type: quick-start | Category: Mobile * Install the iOS SDK With an iOS application in place, you will need to import the required Box iOS SDK dependencies into your project using… # Install the iOS SDK With an iOS application in place, you will need to import the required Box iOS SDK dependencies into your project using one of the available package manager options. ## Select a package manager to use # Carthage Carthage is a decentralized dependency manager for Swift and Objective-C Cocoa projects. It is open-source and built with Swift. # CocoaPods CocoaPods is a centralized dependency manager for Swift and Objective-C Cocoa projects. It is open-source and was built with Ruby. # Swift Package Manager The Swift Package Manager is a tool for managing the distribution of source code, making it easy to share your code and reuse others’ code. # Install the iOS SDK using Carthage 1. From a terminal window, install Carthage: `brew install carthage`. Visit the [Carthage documentation](https://github.com/Carthage/Carthage#installing-carthage) for other installation methods. 2. At the root of your iOS application folder, where the `{APPNAME}.xcodeproj` is located, create a new file named `Cartfile`, without an extension. 3. Open the `Cartfile` and add the **Box iOS SDK** dependency with `git "https://github.com/box/box-ios-sdk.git" ~> 3.0`, then save and close the file. 4. From the terminal, in the folder where the `Cartfile` is present, update all dependencies: `carthage update --platform iOS`. A `Cartfile.resolved` file and a `Carthage` directory will be created in the directory. 5. Within a Finder or File Explorer window load the **Carthage** -> **Build** -> **iOS** directory. This should have a framework file named `BoxSDK.framework`. Keep this window open as we'll use it to add the framework to our project in the next step. 6. In your Xcode project, click on the name of your application at the top of the project navigator on the left. In the content that displays, click on the name of your project under the **TARGETS** option. Scroll down to **Frameworks, Libraries, and Embedded Content**. 7. Drag `BoxSDK.framework` from our Finder window over to the frameworks section. # Install the iOS SDK using CocoaPods 1. From a terminal window, install CocoaPods: `sudo gem install cocoapods`. 2. At the root of your iOS application folder, where the `APPNAME.xcodeproj` is located, run `pod init` to create a new `Podfile` with smart defaults. 3. Load `Podfile`, add the **Box iOS SDK** dependency under `# Pods for {APPNAME}` with `pod 'BoxSDK', '~> 3.0'`, then save and close. 4. From the terminal, in the folder where the `Podfile` is present, download all dependencies: `pod install`. 5. Open `.xcworkspace` in Xcode: `open {APPNAME}.xcworkspace` and build the project. # Install the iOS SDK using the Swift Package Manager 1. In your Xcode project, click on the name of your application at the top of the project navigator on the left. In the content that displays, click on the name of your project under the **PROJECT** option. 2. Click on **Swift Packages** and click on the `+` to add a package. 3. Enter the following repository URL `https://github.com/box/box-ios-sdk.git` and click next. 4. Leave the default settings and click next to finish importing. ## Summary You either selected to install the iOS dependencies using Carthage - You installed Carthage - You create a `Cartfile` with the Box iOS SDK dependency - You installed the iOS SDK dependencies - You manually imported the built dependencies into the Xcode project framework list. Or selected to use **CocoaPods** and - You installed CocoaPods - You created a new `Podfile` with the Box iOS SDK dependency - You installed the iOS SDK dependencies - You built the project in Xcode Or selected to use the **Swift Package Manager** and - You imported the iOS SDK `.git` repository into the Swift packages I've installed the Box iOS SDK dependencies **Reference:** https://developer.box.com/guides/mobile/ios/quick-start/install-ios-sdk/ --- ## Untitled *Type: quick-start | Category: Mobile * Learn to use the iOS SDK The Box iOS SDK is a Swift language wrapper for adding the Box API into your iOS project. Requirements To begin… # Learn to use the iOS SDK The Box iOS SDK is a [Swift language](https://developer.apple.com/swift/) wrapper for adding the Box API into your iOS project. ## Requirements To begin working with the Box iOS SDK and this quick start, the following are required: - iOS 11.0+ / Mac OS X 10.13+ - Xcode 10.0+ ## Overview This guide will take you through the following steps. 1. [Create a new iOS app](g://mobile/ios/quick-start/create-ios-app) in Xcode. 2. [Install the iOS SDK](g://mobile/ios/quick-start/install-ios-sdk) into your project. 3. [Configure a Box App](g://mobile/ios/quick-start/configure-box-app) so that the iOS SDK can access the Box API. 4. [Make an API call](g://mobile/ios/quick-start/make-api-call) to the Box API with the iOS SDK. I am ready to get started **Reference:** https://developer.box.com/guides/mobile/ios/quick-start/ --- ## Untitled *Type: quick-start | Category: Mobile * Make an API call With our Box and iOS applications created and configured with the Box iOS SDK we can now make our first call to Box APIs… # Make an API call With our Box and iOS applications created and configured with the Box iOS SDK we can now make our first call to Box APIs. Using our blank iOS application, we will create a button to trigger a request to Box to fetch the name of the currently authenticated user. Using a blocking actions as we use in these examples is slow. In a production app these blocking actions would need to be replaced with proper task delegation and non-blocking actions. ## Create a button Within your Swift application in Xcode, load `ContentView.swift`. At the top of the file you will see a `struct` for `ContentView`, within which is a basic string that will be output to your iOS application if you run the app in an emulator. ``` import SwiftUI struct ContentView: View { var body: some View { Text("Hello, World!") } } ``` We'll first replace the `Text` output line with a button to be able to trigger off the call to get the current user. Replace that line with the below button. ``` Button(action: { // Perform some action }) { Text("Click to get current user") } .padding(10) .cornerRadius(20) .foregroundColor(.white) .background(Color.blue) ``` Our next step is to add an an action for the button which will fetch a user's details from Box. ## Add an API call button action When a user clicks the button, we want to fetch the user's details. To achieve this we need to do two things, add the import for the **Box iOS SDK** and add the button action to make the call. At the top of the `ContentView.swift` file, add `import BoxSDK` with the other import statement. Next, within the button action, where we currently have a comment placeholder, add a call to the iOS SDK to fetch the current user. When the API call completes it will print an authentication message to the developer console. For ease of implementation, we have a blocking `sleep(5)` call in place in order to test that the iOS SDK can make calls from our iOS SDK by providing enough time for the request to complete. Replace `{{YOUR DEVELOPER TOKEN}}` with your developer token. ``` let client = BoxSDK.getClient(token: "{{YOUR DEVELOPER TOKEN}}") client.users.getCurrent(fields:["name", "login"]) { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error getting user information") return } print("Authenticated as \(user.name)") } sleep(5) ``` Build and run your sample application in the iOS emulator. If you run this code an hour or more after you created the developer token in the last step, you will need to revoke and generate a new developer token using the same method in the [previous step](g://mobile/ios/quick-start/configure-box-app) as the developer token will only persist for 60 minutes. Once the application loads in the emulator you should see the button we created. Click it to start the API request. Within the Xcode developer console you should see the API request and response, with the last line showing the user print statement that we specified. ``` ◁ Status code: 200: no error ◁ Headers: ◁ Cache-Control, Value: no-cache, no-store ◁ BOX-REQUEST-ID, Value: 1c55151238444132eca16b4c2346d005 ◁ Transfer-Encoding, Value: Identity ◁ content-type, Value: application/json ◁ Connection, Value: keep-alive ◁ Strict-Transport-Security, Value: max-age=31536000 ◁ Body: {"type":"user","id":"123456789","name":"Test User","login":"testuser@test.com"} Authenticated as Optional("Test User") ``` If you don't see the Xcode developer console, from the menu click **View** -> **Debug Area** -> **Activate Console** Congratulations, you've now configured the **Box iOS SDK** and have made your first call to the Box API. ## Summary - You added a button to your blank iOS application - You added a request to fetch the current user using the iOS SDK I made an API call **Reference:** https://developer.box.com/guides/mobile/ios/quick-start/make-api-call/ --- ## Untitled *Type: quick-start | Category: Mobile * Next steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. Created a new iOS app in… # Next steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. 1. [Created a new iOS app](g://mobile/ios/quick-start/create-ios-app) in Xcode. 2. [Installed the iOS SDK](g://mobile/ios/quick-start/install-ios-sdk) into your project. 3. [Configured a Box App](g://mobile/ios/quick-start/configure-box-app) so that the iOS SDK can access the Box API. 4. [Made your first API call](g://mobile/ios/quick-start/make-api-call) to the Box API with the iOS SDK. ## Next things to do To take the next step with your application, the following resources are recommended. - [Token Downscoping](g://authentication/tokens/downscope): In this quick start guide you used a developer token to make your first call. To implement a scalable solution you should have a server-side solution to generate downscoped tokens to replace that implementation. - [Official JWT sample application](https://github.com/box/box-ios-sdk/tree/master/SampleApps/JWTSampleApp): Bundled with the iOS SDK, this sample application will get you started quickly with a properly structured Box JWT application, which doesn't require user login. - [Official OAuth 2 sample application](https://github.com/box/box-ios-sdk/tree/master/SampleApps/OAuth2SampleApp): Bundled with the iOS SDK, this sample application will get you started quickly with a properly structured Box OAuth 2 application, which requires user login. **Reference:** https://developer.box.com/guides/mobile/ios/quick-start/next-steps/ --- ## Untitled *Type: quick-start | Category: Tooling * Configure a Box App To use the Postman Collection the Postman application needs to authenticate to the Box API using an Access Token. The… # Configure a Box App To use the **Postman Collection** the Postman application needs to authenticate to the Box API using an **Access Token**. The simplest way to get an Access Token is by logging into Box using a **Box App**. A **Box App** is an application that can be used for making API calls. When using the **Postman Collection** you can choose to either set up your own Box App or use our preconfigured one. The key benefit of setting up your own Box App is that you won't need to go through login every hour, but it does require a few extra steps to set up. ## Select a Box App to use # Create new Box App We can set up a Box App for you right here from the documentation. With a few clicks you will be ready to go. # Use existing Box app If you've already created a Box App before that you want to use, then we can use the credentials for that application. # Create a Box app To use your own **Box App** you will need to create a new Box App in the **Box Developer Console**. Click the button below and we will set it up for you. At the end you will have a **Client ID** and **Client Secret**. Create an app We will use these credentials to authenticate your application in the next step. # Use existing Box app If you have already created a Box App before you can use that as well. We require a few settings to be set for this to work. 1. Go to the [Developer Console](https://cloud.app.box.com/developers/console) 2. Select your application 3. Go to the app's configuration section 4. Make sure your application uses **Standard OAuth 2.0** as the authentication method 5. Scroll down to the **OAuth 2.0 redirect URI** configuration and set the **Redirect URI** to the value `https://developer.box.com/auth/callback`. It is important to note, if you visited this tutorial at `box.dev` your **Redirect URI** should be `https://box.dev/auth/callback`. 6. Scroll down to the **Application Scopes** section to select your desired [permissions](g://api-calls/permissions-and-errors/scopes). **Your application must have at least one or more** **of the following scopes:** manage users, read all files and folders stored in Box, read and write all files and folders in Box. 7. At the top of the page click the button to **Save Changes** Next, copy the values for the Client ID and Client Secret into these 2 fields. Client ID Client Secret We will use these credentials to authenticate your application in the next step. # Security notice Your API credentials are now stored in the browser cache. We highly recommend clearing out this storage by clicking the **Reset** button later in this guide. ## Summary You either selected to create a new **Box App** - Signed up for a developer account (Optional) - Had us create **Platform App** for you that uses **OAuth 2.0** authentication - Had us set up the **redirect URL** for the application Or you selected to use an **existing Box App** I have configured a Box app **Reference:** https://developer.box.com/guides/tooling/postman/quick-start/configure-box-app/ --- ## Untitled *Type: quick-start | Category: Tooling * Use Postman to make API calls Postman is a tool that lets you build and test HTTP requests in an easy-to-use interface without configuring a… # Use Postman to make API calls [Postman](https://getpostman.com) is a tool that lets you build and test HTTP requests in an easy-to-use interface without configuring a full development environment. The Box Postman Collection is a set of preconfigured requests that make it possible to get started with the Box API from Postman without having to manually configure the requests. ## Overview This guide will take you through the following steps. 1. [Install Postman](g://tooling/postman/quick-start/install-postman) on your device. 2. [Configure a Box App](g://tooling/postman/quick-start/configure-box-app) so that Postman can access the Box API. 3. [Log in](g://tooling/postman/quick-start/log-in-to-box) to the Box App to get the right API credentials. 4. [Fork Box's Postman collection](g://tooling/postman/quick-start/load-postman-collection) into Postman. 5. [Make a first API call](g://tooling/postman/quick-start/make-api-call) to the Box API with Postman. I am ready to get started **Reference:** https://developer.box.com/guides/tooling/postman/quick-start/ --- ## Untitled *Type: quick-start | Category: Tooling * Install Postman To use the Box Postman Collection you will need to have the Postman app installed on your device. Postman is available for… # Install Postman To use the **Box Postman Collection** you will need to have the [Postman](https://getpostman.com) app installed on your device. Postman is available for Windows, Mac, and Linux environments. [Download the appropriate version for you operating system](https://www.postman.com/downloads/) Next, install Postman on your machine and (optionally) [register for a Postman account and log in](https://identity.getpostman.com/signup). ## Summary - You installed Postman - You created a Postman account (optional) - You logged into the Postman application with your Postman account I have installed Postman **Reference:** https://developer.box.com/guides/tooling/postman/quick-start/install-postman/ --- ## Untitled *Type: quick-start | Category: Tooling * Fork a collection Now that you are logged in we can fork the Box Postman Collection into the Postman App that we installed previously. When… # Fork a collection Now that you are logged in we can fork the **Box Postman Collection** into the **Postman App** that we installed previously. When we fork the Postman Collection we will also automatically load your API credentials as a Postman environment. ## Forking a collection and environment By clicking the button below you will fork the Box Postman Collection into your Postman application. In the same click it will also load your **Access Token**, **Refresh Token**, **Client ID** and Client Secret into a Postman environment. We recommend to fork the Box Postman Collection - you will be asked if you want to update the collection any time Box makes changes to it. You can also copy the collection, but you might miss important updates. ## Exploring the collection When you clicked the button above it would have asked you to fork the collection into the Postman application. Once imported, the collection should appear within the app in the left-hand sidebar. You can click on the collection to open it up and explore our over 170 API endpoints. ## Summary - You forked the Postman collection into Postman - You additionally loaded your Box Postman environment into Postman # Incomplete previous step Complete the previous steps to select and log in to a **Box App**. # Incomplete previous step Complete the previous steps to select and log in to a **Box App**. I have forked the collection **Reference:** https://developer.box.com/guides/tooling/postman/quick-start/load-postman-collection/ --- ## Untitled *Type: quick-start | Category: Tooling * Log in to Box In this step, we will use the Client ID and Client Secret from the previous step to log you in and create an Access Token for… # Log in to Box In this step, we will use the **Client ID** and **Client Secret** from the previous step to log you in and create an **Access Token** for your user. ## The reason to log in Currently you have provided us with the following information. Client ID Client Secret These **credentials** allow any program or piece of code to authenticate itself to the **Box API**. It represents the **Box App** you created but it doesn't tell the API who you, the **User**, are. To authenticate yourself you will need to send your browser to the Box login screen to authorize your **Box App** to access to your **User** account. Setting this flow up can be hard, which is why we have made this straightforward for you with the button below. ## Log into your Box app ## You are now logged in We just sent your browser to the [Box Authorization](e://get-authorize) screen where you granted your application access to your user account. After you granted it access the browser redirected back to this site with a `code`. We then [exchanged](e://post-oauth2-token) this short-lived `code` for a longer lived **Access Token** and **Refresh Token**. These tokens represent you, the **User**. Your name Access Token Refresh Token # Security notice Your API credentials are now stored in the browser cache. We highly recommend clearing out this storage by clicking the **Reset** button later in this guide. # Incomplete previous step Please complete the previous step to set up the **Box App** you want to use. ## Summary - You logged into your **Box account** using your own **Box App** or our preconfigured app - You granted the **Box App** access to your account - You are able to see your account's **Access Token** and **Refresh Token** on this page I have logged in to Box **Reference:** https://developer.box.com/guides/tooling/postman/quick-start/log-in-to-box/ --- ## Untitled *Type: quick-start | Category: Tooling * Next steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. Installed Postman on your… # Next steps You've reached the end of this Quick Start guide. By now you should have taken the following steps. 1. [Installed Postman](g://tooling/postman/quick-start/install-postman) on your device. 2. [Configured a Box App](g://tooling/postman/quick-start/configure-box-app) in order to be able to authenticate a Postman App for accessing Box. 3. [Logged in](g://tooling/postman/quick-start/log-in-to-box) to the Box App to get the right API credentials. 4. [Loaded Box's Postman collection](g://tooling/postman/quick-start/load-postman-collection) into Postman, and with it all the credentials needed to make API calls. 5. [Made your first API call](g://tooling/postman/quick-start/make-api-call) to the Box API with Postman. ## Next things to do We recommend the following resource for anyone who wants to learn more about using Postman with the Box API. - [The official Postman Get Started guide](https://learning.getpostman.com/getting-started/) from the Postman team. - [Learn how to refresh your access token](g://tooling/postman/refresh) within Postman. **Reference:** https://developer.box.com/guides/tooling/postman/quick-start/next-steps/ --- ## Untitled *Type: quick-start | Category: Tooling * Make an API call With the Box Postman Collection forked into the Postman App it is now possible to make API calls to the Box API on behalf… # Make an API call With the **Box Postman Collection** forked into the **Postman App** it is now possible to make API calls to the **Box API** on behalf of the user you logged in as. ## First: Reset browser storage Now that you've imported the Box API credentials into Postman you should take a moment to remove these credentials from your browser's storage. Clear credentials Removing your API credentials from the browser storage ensures that no other script can read your **Client ID**, **Client Secret**, **Access Token** or **Refresh Token**. ## Select an environment Before an API call can be made it is important to select the right Postman environment to use when making API calls. When you imported the **Box Postman collection** it automatically imported a `Box` Postman environment for you to use. The collection will automatically recognize and use the variables in this environment for making API calls. To select the Box Postman environment, select **Box** from the dropdown in the top-right of Postman. You can inspect the environment by clicking the **eye** icon to the right of the dropdown. ## Make an API request To make an API request, select a **Request** from the Box Postman Collection. In this example, we will use the **List items in folder** API which can be found in the **Folders** folder. By default the `folder_id` for this API endpoint is set to `0` which represents every user's root folder. You can leave this value as is or set it to the folder ID of a folder you want to inspect. Next, click the **Send** button in the top right to make the API request. The API call should return quickly and show you a list of items in your folder in the response **Body** tab in the bottom half of the screen. # Authentication error At this point Postman might return an error instead of a list. Often, this means your **Access Token** has expired. Check our guide on refreshing an access token in Postman for more details. ## Summary - You selected the Postman environment to use for making API calls to Box - You made your first API call to Box, requesting the folder items for your user's root folder. I made an API call **Reference:** https://developer.box.com/guides/tooling/postman/quick-start/make-api-call/ --- --- # API Reference This section contains 552 documentation items covering resource, endpoint. Includes 313 API endpoints and 239 resource definitions. ## Access token *Type: resource | Category: api-resource* A token that can be used to make authenticated API calls. # Access token A token that can be used to make authenticated API calls. --- ## Add changed status of shield information barrier with specified ID *Type: endpoint | Category: api-endpoint* # undefined /reference/post-shield-information-barriers-change-status/ **Reference:** https://developer.box.com/reference/post-shield-information-barriers-change-status/ --- ## Add classification *Type: endpoint | Category: api-endpoint* # undefined /reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--add/ **Reference:** https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--add/ --- ## Add classification to file *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/ **Reference:** https://developer.box.com/reference/post-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/ --- ## Add classification to folder *Type: endpoint | Category: api-endpoint* # undefined /reference/post-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/ **Reference:** https://developer.box.com/reference/post-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/ --- ## Add domain to list of allowed collaboration domains *Type: endpoint | Category: api-endpoint* # undefined /reference/post-collaboration-whitelist-entries/ **Reference:** https://developer.box.com/reference/post-collaboration-whitelist-entries/ --- ## Add initial classifications *Type: endpoint | Category: api-endpoint* # undefined /reference/post-metadata-templates-schema--classifications/ **Reference:** https://developer.box.com/reference/post-metadata-templates-schema--classifications/ --- ## Add or update user avatar *Type: endpoint | Category: api-endpoint* # undefined /reference/post-users-id-avatar/ **Reference:** https://developer.box.com/reference/post-users-id-avatar/ --- ## Add shared link to file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id--add-shared-link/ **Reference:** https://developer.box.com/reference/put-files-id--add-shared-link/ --- ## Add shared link to folder *Type: endpoint | Category: api-endpoint* # undefined /reference/put-folders-id--add-shared-link/ **Reference:** https://developer.box.com/reference/put-folders-id--add-shared-link/ --- ## Add shared link to web link *Type: endpoint | Category: api-endpoint* # undefined /reference/put-web-links-id--add-shared-link/ **Reference:** https://developer.box.com/reference/put-web-links-id--add-shared-link/ --- ## Add user to group *Type: endpoint | Category: api-endpoint* # undefined /reference/post-group-memberships/ **Reference:** https://developer.box.com/reference/post-group-memberships/ --- ## AI agent *Type: resource | Category: api-resource* Standard representation of an AI Agent instance. # AI agent Standard representation of an AI Agent instance. --- ## AI agent (Full) *Type: resource | Category: api-resource* Full representation of an AI Agent instance. # AI agent (Full) Full representation of an AI Agent instance. --- ## AI agent capability ask *Type: resource | Category: api-resource* The AI agent to be used to ask questions. # AI agent capability ask The AI agent to be used to ask questions. --- ## AI agent capability ask request *Type: resource | Category: api-resource* The AI agent to be used to handle queries. # AI agent capability ask request The AI agent to be used to handle queries. --- ## AI agent capability extract *Type: resource | Category: api-resource* The AI agent to be used for metadata extraction. # AI agent capability extract The AI agent to be used for metadata extraction. --- ## AI agent capability extract request *Type: resource | Category: api-resource* The AI agent to be used for metadata extraction. # AI agent capability extract request The AI agent to be used for metadata extraction. --- ## AI agent capability text generation *Type: resource | Category: api-resource* The AI agent to be used to generate text. # AI agent capability text generation The AI agent to be used to generate text. --- ## AI agent capability text generation request *Type: resource | Category: api-resource* The AI agent to be used to generate text. # AI agent capability text generation request The AI agent to be used to generate text. --- ## AI agent for extract requests *Type: resource | Category: api-resource* The AI agent to be used for extraction. # AI agent for extract requests The AI agent to be used for extraction. --- ## AI agent for question requests *Type: resource | Category: api-resource* The AI agent used to handle queries. # AI agent for question requests The AI agent used to handle queries. --- ## AI agent for structured extract request *Type: resource | Category: api-resource* The AI agent to be used for structured extraction. # AI agent for structured extract request The AI agent to be used for structured extraction. --- ## AI agent for text generation requests *Type: resource | Category: api-resource* The AI agent used for generating text. # AI agent for text generation requests The AI agent used for generating text. --- ## AI agent reference *Type: resource | Category: api-resource* The AI agent used to handle queries. # AI agent reference The AI agent used to handle queries. --- ## AI agents list *Type: resource | Category: api-resource* List of AI Agents with pagination. # AI agents list List of AI Agents with pagination. --- ## AI extract response *Type: resource | Category: api-resource* AI extract response. The content of this response may vary depending on the requested configuration. # AI extract response AI extract response. The content of this response may vary depending on the requested configuration. --- ## AI extract structured response *Type: resource | Category: api-resource* AI extract structured response. # AI extract structured response AI extract structured response. --- ## AI LLM endpoint params AWS *Type: resource | Category: api-resource* AI LLM endpoint params AWS object. # AI LLM endpoint params AWS AI LLM endpoint params AWS object. --- ## AI LLM endpoint params Google *Type: resource | Category: api-resource* AI LLM endpoint params Google object. # AI LLM endpoint params Google AI LLM endpoint params Google object. --- ## AI LLM endpoint params IBM *Type: resource | Category: api-resource* AI LLM endpoint params IBM object. # AI LLM endpoint params IBM AI LLM endpoint params IBM object. --- ## AI LLM endpoint params OpenAI *Type: resource | Category: api-resource* AI LLM endpoint params OpenAI object. # AI LLM endpoint params OpenAI AI LLM endpoint params OpenAI object. --- ## AI response *Type: resource | Category: api-resource* AI response. # AI response AI response. --- ## AI response (Full) *Type: resource | Category: api-resource* AI ask response. # AI response (Full) AI ask response. --- ## Allowed collaboration domain *Type: resource | Category: api-resource* An entry that describes an approved domain for which users can collaborate with files and folders in your enterprise or vice versa. # Allowed collaboration domain An entry that describes an approved domain for which users can collaborate with files and folders in your enterprise or vice versa. --- ## Allowed collaboration domains *Type: resource | Category: api-resource* A list of allowed domains for collaboration. # Allowed collaboration domains A list of allowed domains for collaboration. --- ## Allowed collaboration domains user exemption *Type: resource | Category: api-resource* The user that is exempt from any of the restrictions imposed by the list of allowed collaboration domains for this enterprise. # Allowed collaboration domains user exemption The user that is exempt from any of the restrictions imposed by the list of allowed collaboration domains for this enterprise. --- ## Allowed collaboration domains user exemptions *Type: resource | Category: api-resource* A list of users exempt from any of the restrictions imposed by the list of allowed collaboration domains for this enterprise. # Allowed collaboration domains user exemptions A list of users exempt from any of the restrictions imposed by the list of allowed collaboration domains for this enterprise. --- ## App item *Type: resource | Category: api-resource* An app item represents an content object owned by an application. It can group files and folders together from different paths. That set can be shared via a collaboration. # App item An app item represents an content object owned by an application. It can group files and folders together from different paths. That set can be shared via a collaboration. --- ## App item association *Type: resource | Category: api-resource* An app item association represents an association between a file or folder and an app item. Associations between a folder and an app item cascade down to all descendants of the folder. # App item association An app item association represents an association between a file or folder and an app item. Associations between a folder and an app item cascade down to all descendants of the folder. --- ## App item associations *Type: resource | Category: api-resource* A list of app item associations. # App item associations A list of app item associations. --- ## AppItem event source *Type: resource | Category: api-resource* The AppItem that triggered an event in the event stream. # AppItem event source The AppItem that triggered an event in the event stream. --- ## Apply watermark to file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id-watermark/ **Reference:** https://developer.box.com/reference/put-files-id-watermark/ --- ## Apply watermark to folder *Type: endpoint | Category: api-endpoint* # undefined /reference/put-folders-id-watermark/ **Reference:** https://developer.box.com/reference/put-folders-id-watermark/ --- ## Archive *Type: resource | Category: api-resource* An archive is a folder dedicated to storing content that is redundant, outdated, or trivial. Content in an archive is not accessible to its owner and collaborators. To use this feature, you must request GCM scope for your Box application. # Archive An archive is a folder dedicated to storing content that is redundant, outdated, or trivial. Content in an archive is not accessible to its owner and collaborators. To use this feature, you must request GCM scope for your Box application. --- ## Archives *Type: resource | Category: api-resource* A list of archives. # Archives A list of archives. --- ## Ask question *Type: endpoint | Category: api-endpoint* # undefined /reference/post-ai-ask/ **Reference:** https://developer.box.com/reference/post-ai-ask/ --- ## Assign legal hold policy *Type: endpoint | Category: api-endpoint* # undefined /reference/post-legal-hold-policy-assignments/ **Reference:** https://developer.box.com/reference/post-legal-hold-policy-assignments/ --- ## Assign retention policy *Type: endpoint | Category: api-endpoint* # undefined /reference/post-retention-policy-assignments/ **Reference:** https://developer.box.com/reference/post-retention-policy-assignments/ --- ## Assign storage policy *Type: endpoint | Category: api-endpoint* # undefined /reference/post-storage-policy-assignments/ **Reference:** https://developer.box.com/reference/post-storage-policy-assignments/ --- ## Assign task *Type: endpoint | Category: api-endpoint* # undefined /reference/post-task-assignments/ **Reference:** https://developer.box.com/reference/post-task-assignments/ --- ## Authorize user *Type: endpoint | Category: api-endpoint* # undefined /reference/get-authorize/ **Reference:** https://developer.box.com/reference/get-authorize/ --- ## Box Doc Gen batch (Base) *Type: resource | Category: api-resource* The basic representation of a Box Doc Gen batch object. A Box Doc Gen batch contains one or more Box Doc Gen jobs. # Box Doc Gen batch (Base) The basic representation of a Box Doc Gen batch object. A Box Doc Gen batch contains one or more Box Doc Gen jobs. --- ## Box Doc Gen job *Type: resource | Category: api-resource* A standard representation of a Box Doc Gen job. # Box Doc Gen job A standard representation of a Box Doc Gen job. --- ## Box Doc Gen job (Base) *Type: resource | Category: api-resource* The basic representation of a Box Doc Gen job. # Box Doc Gen job (Base) The basic representation of a Box Doc Gen job. --- ## Box Doc Gen job (Full) *Type: resource | Category: api-resource* A full representation of a Box Doc Gen job. # Box Doc Gen job (Full) A full representation of a Box Doc Gen job. --- ## Box Doc Gen jobs *Type: resource | Category: api-resource* A list of Box Doc Gen jobs with a standard set of parameters. # Box Doc Gen jobs A list of Box Doc Gen jobs with a standard set of parameters. --- ## Box Doc Gen jobs (Full) *Type: resource | Category: api-resource* A list of Box Doc Gen jobs with a full set of parameters. # Box Doc Gen jobs (Full) A list of Box Doc Gen jobs with a full set of parameters. --- ## Box Doc Gen tags *Type: resource | Category: api-resource* A list of Box Doc Gen tags. # Box Doc Gen tags A list of Box Doc Gen tags. --- ## Box Doc Gen tags processing message *Type: resource | Category: api-resource* A message informing the user that document tags are still being processed. # Box Doc Gen tags processing message A message informing the user that document tags are still being processed. --- ## Box Doc Gen template *Type: resource | Category: api-resource* A Box Doc Gen template object. # Box Doc Gen template A Box Doc Gen template object. --- ## Box Doc Gen template (Base) *Type: resource | Category: api-resource* A base representation of a Box Doc Gen template, used when nested within another resource. # Box Doc Gen template (Base) A base representation of a Box Doc Gen template, used when nested within another resource. --- ## Box Doc Gen template tag *Type: resource | Category: api-resource* A Box Doc Gen template tag object. # Box Doc Gen template tag A Box Doc Gen template tag object. --- ## Box Doc Gen templates *Type: resource | Category: api-resource* List of Box Doc Gen templates. # Box Doc Gen templates List of Box Doc Gen templates. --- ## Box Sign request *Type: resource | Category: api-resource* A Box Sign request object. # Box Sign request A Box Sign request object. --- ## Box Sign requests *Type: resource | Category: api-resource* A standard representation of a signature request, as returned from any Box Sign API endpoints by default. # Box Sign requests A standard representation of a signature request, as returned from any Box Sign API endpoints by default. --- ## Box Sign template *Type: resource | Category: api-resource* A Box Sign template object. # Box Sign template A Box Sign template object. --- ## Box Sign templates *Type: resource | Category: api-resource* A list of templates, as returned from any Box Sign API endpoints by default. # Box Sign templates A list of templates, as returned from any Box Sign API endpoints by default. --- ## Cancel Box Sign request *Type: endpoint | Category: api-endpoint* # undefined /reference/post-sign-requests-id-cancel/ **Reference:** https://developer.box.com/reference/post-sign-requests-id-cancel/ --- ## Classification *Type: resource | Category: api-resource* An instance of the classification metadata template, containing the classification applied to the file or folder. To get more details about the classification applied to an item, request the classification metadata template. # Classification An instance of the classification metadata template, containing the classification applied to the file or folder. To get more details about the classification applied to an item, request the classification metadata template. --- ## Classification Template *Type: resource | Category: api-resource* A metadata template that holds the security classifications defined by an enterprise. # Classification Template A metadata template that holds the security classifications defined by an enterprise. --- ## Client error *Type: resource | Category: api-resource* A generic error. # Client error A generic error. --- ## Client error *Type: resource | Category: api-resource* A generic error. # Client error A generic error. --- ## Collaboration *Type: resource | Category: api-resource* Collaborations define access permissions for users and groups to files and folders, similar to access control lists. A collaboration object grants a user or group access to a file or folder with permissions defined by a specific role. # Collaboration Collaborations define access permissions for users and groups to files and folders, similar to access control lists. A collaboration object grants a user or group access to a file or folder with permissions defined by a specific role. --- ## Collaborations *Type: resource | Category: api-resource* A list of collaborations. # Collaborations A list of collaborations. --- ## Collaborations *Type: resource | Category: api-resource* A list of collaborations. # Collaborations A list of collaborations. --- ## Collection *Type: resource | Category: api-resource* A collection of items, including files and folders. Currently, the only collection available is the `favorites` collection. The contents of a collection can be explored in a similar way to which the contents of a folder is explored. # Collection A collection of items, including files and folders. Currently, the only collection available is the `favorites` collection. The contents of a collection can be explored in a similar way to which the contents of a folder is explored. --- ## Collections *Type: resource | Category: api-resource* A list of collections. # Collections A list of collections. --- ## Comment *Type: resource | Category: api-resource* Standard representation of a comment. # Comment Standard representation of a comment. --- ## Comment (Base) *Type: resource | Category: api-resource* Base representation of a comment. # Comment (Base) Base representation of a comment. --- ## Comment (Full) *Type: resource | Category: api-resource* Comments are messages created on files. Comments can be made independently or created as responses to other comments. # Comment (Full) Comments are messages created on files. Comments can be made independently or created as responses to other comments. --- ## Comments *Type: resource | Category: api-resource* A list of comments. # Comments A list of comments. --- ## Commit upload session *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-upload-sessions-id-commit/ **Reference:** https://developer.box.com/reference/post-files-upload-sessions-id-commit/ --- ## Conflict error *Type: resource | Category: api-resource* The error that occurs when a file can not be created due to a conflict. # Conflict error The error that occurs when a file can not be created due to a conflict. --- ## Copy file *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-id-copy/ **Reference:** https://developer.box.com/reference/post-files-id-copy/ --- ## Copy file request *Type: endpoint | Category: api-endpoint* # undefined /reference/post-file-requests-id-copy/ **Reference:** https://developer.box.com/reference/post-file-requests-id-copy/ --- ## Copy folder *Type: endpoint | Category: api-endpoint* # undefined /reference/post-folders-id-copy/ **Reference:** https://developer.box.com/reference/post-folders-id-copy/ --- ## Copy hub *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/post-hubs-id-copy/ **Reference:** https://developer.box.com/reference/v2025.0/post-hubs-id-copy/ --- ## Create a Box Sign request *Type: resource | Category: api-resource* Creates a Box Sign request object. # Create a Box Sign request Creates a Box Sign request object. --- ## Create AI agent *Type: endpoint | Category: api-endpoint* # undefined /reference/post-ai-agents/ **Reference:** https://developer.box.com/reference/post-ai-agents/ --- ## Create archive *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/post-archives/ **Reference:** https://developer.box.com/reference/v2025.0/post-archives/ --- ## Create Box Doc Gen template *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/post-docgen-templates/ **Reference:** https://developer.box.com/reference/v2025.0/post-docgen-templates/ --- ## Create Box Sign request *Type: endpoint | Category: api-endpoint* # undefined /reference/post-sign-requests/ **Reference:** https://developer.box.com/reference/post-sign-requests/ --- ## Create Box Skill cards on file *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-id-metadata-global-boxSkillsCards/ **Reference:** https://developer.box.com/reference/post-files-id-metadata-global-boxSkillsCards/ --- ## Create collaboration *Type: endpoint | Category: api-endpoint* # undefined /reference/post-collaborations/ **Reference:** https://developer.box.com/reference/post-collaborations/ --- ## Create comment *Type: endpoint | Category: api-endpoint* # undefined /reference/post-comments/ **Reference:** https://developer.box.com/reference/post-comments/ --- ## Create email alias *Type: endpoint | Category: api-endpoint* # undefined /reference/post-users-id-email-aliases/ **Reference:** https://developer.box.com/reference/post-users-id-email-aliases/ --- ## Create folder *Type: endpoint | Category: api-endpoint* # undefined /reference/post-folders/ **Reference:** https://developer.box.com/reference/post-folders/ --- ## Create folder lock *Type: endpoint | Category: api-endpoint* # undefined /reference/post-folder-locks/ **Reference:** https://developer.box.com/reference/post-folder-locks/ --- ## Create group *Type: endpoint | Category: api-endpoint* # undefined /reference/post-groups/ **Reference:** https://developer.box.com/reference/post-groups/ --- ## Create hub *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/post-hubs/ **Reference:** https://developer.box.com/reference/v2025.0/post-hubs/ --- ## Create hub collaboration *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/post-hub-collaborations/ **Reference:** https://developer.box.com/reference/v2025.0/post-hub-collaborations/ --- ## Create jobs to terminate user group session *Type: endpoint | Category: api-endpoint* # undefined /reference/post-groups-terminate-sessions/ **Reference:** https://developer.box.com/reference/post-groups-terminate-sessions/ --- ## Create jobs to terminate users session *Type: endpoint | Category: api-endpoint* # undefined /reference/post-users-terminate-sessions/ **Reference:** https://developer.box.com/reference/post-users-terminate-sessions/ --- ## Create legal hold policy *Type: endpoint | Category: api-endpoint* # undefined /reference/post-legal-hold-policies/ **Reference:** https://developer.box.com/reference/post-legal-hold-policies/ --- ## Create metadata cascade policy *Type: endpoint | Category: api-endpoint* # undefined /reference/post-metadata-cascade-policies/ **Reference:** https://developer.box.com/reference/post-metadata-cascade-policies/ --- ## Create metadata instance on file *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-id-metadata-id-id/ **Reference:** https://developer.box.com/reference/post-files-id-metadata-id-id/ --- ## Create metadata instance on folder *Type: endpoint | Category: api-endpoint* # undefined /reference/post-folders-id-metadata-id-id/ **Reference:** https://developer.box.com/reference/post-folders-id-metadata-id-id/ --- ## Create metadata template *Type: endpoint | Category: api-endpoint* # undefined /reference/post-metadata-templates-schema/ **Reference:** https://developer.box.com/reference/post-metadata-templates-schema/ --- ## Create retention policy *Type: endpoint | Category: api-endpoint* # undefined /reference/post-retention-policies/ **Reference:** https://developer.box.com/reference/post-retention-policies/ --- ## Create shield information barrier *Type: endpoint | Category: api-endpoint* # undefined /reference/post-shield-information-barriers/ **Reference:** https://developer.box.com/reference/post-shield-information-barriers/ --- ## Create shield information barrier report *Type: endpoint | Category: api-endpoint* # undefined /reference/post-shield-information-barrier-reports/ **Reference:** https://developer.box.com/reference/post-shield-information-barrier-reports/ --- ## Create shield information barrier segment *Type: endpoint | Category: api-endpoint* # undefined /reference/post-shield-information-barrier-segments/ **Reference:** https://developer.box.com/reference/post-shield-information-barrier-segments/ --- ## Create shield information barrier segment member *Type: endpoint | Category: api-endpoint* # undefined /reference/post-shield-information-barrier-segment-members/ **Reference:** https://developer.box.com/reference/post-shield-information-barrier-segment-members/ --- ## Create shield information barrier segment restriction *Type: endpoint | Category: api-endpoint* # undefined /reference/post-shield-information-barrier-segment-restrictions/ **Reference:** https://developer.box.com/reference/post-shield-information-barrier-segment-restrictions/ --- ## Create shield list *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/post-shield-lists/ **Reference:** https://developer.box.com/reference/v2025.0/post-shield-lists/ --- ## Create Slack integration mapping *Type: endpoint | Category: api-endpoint* # undefined /reference/post-integration-mappings-slack/ **Reference:** https://developer.box.com/reference/post-integration-mappings-slack/ --- ## Create Slack integration mapping request *Type: resource | Category: api-resource* A request to create a Slack Integration Mapping object. # Create Slack integration mapping request A request to create a Slack Integration Mapping object. --- ## Create task *Type: endpoint | Category: api-endpoint* # undefined /reference/post-tasks/ **Reference:** https://developer.box.com/reference/post-tasks/ --- ## Create Teams integration mapping *Type: endpoint | Category: api-endpoint* # undefined /reference/post-integration-mappings-teams/ **Reference:** https://developer.box.com/reference/post-integration-mappings-teams/ --- ## Create teams integration mapping request *Type: resource | Category: api-resource* A request to create a Teams Integration Mapping object. # Create teams integration mapping request A request to create a Teams Integration Mapping object. --- ## Create terms of service *Type: endpoint | Category: api-endpoint* # undefined /reference/post-terms-of-services/ **Reference:** https://developer.box.com/reference/post-terms-of-services/ --- ## Create terms of service status for new user *Type: endpoint | Category: api-endpoint* # undefined /reference/post-terms-of-service-user-statuses/ **Reference:** https://developer.box.com/reference/post-terms-of-service-user-statuses/ --- ## Create upload session *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-upload-sessions/ **Reference:** https://developer.box.com/reference/post-files-upload-sessions/ --- ## Create upload session for existing file *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-id-upload-sessions/ **Reference:** https://developer.box.com/reference/post-files-id-upload-sessions/ --- ## Create user *Type: endpoint | Category: api-endpoint* # undefined /reference/post-users/ **Reference:** https://developer.box.com/reference/post-users/ --- ## Create user exemption from collaboration domain restrictions *Type: endpoint | Category: api-endpoint* # undefined /reference/post-collaboration-whitelist-exempt-targets/ **Reference:** https://developer.box.com/reference/post-collaboration-whitelist-exempt-targets/ --- ## Create user invite *Type: endpoint | Category: api-endpoint* # undefined /reference/post-invites/ **Reference:** https://developer.box.com/reference/post-invites/ --- ## Create web link *Type: endpoint | Category: api-endpoint* # undefined /reference/post-web-links/ **Reference:** https://developer.box.com/reference/post-web-links/ --- ## Create webhook *Type: endpoint | Category: api-endpoint* # undefined /reference/post-webhooks/ **Reference:** https://developer.box.com/reference/post-webhooks/ --- ## Create zip download *Type: endpoint | Category: api-endpoint* # undefined /reference/post-zip-downloads/ **Reference:** https://developer.box.com/reference/post-zip-downloads/ --- ## Delete AI agent *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-ai-agents-id/ **Reference:** https://developer.box.com/reference/delete-ai-agents-id/ --- ## Delete archive *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/delete-archives-id/ **Reference:** https://developer.box.com/reference/v2025.0/delete-archives-id/ --- ## Delete Box Doc Gen template *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/delete-docgen-templates-id/ **Reference:** https://developer.box.com/reference/v2025.0/delete-docgen-templates-id/ --- ## Delete file *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-files-id/ **Reference:** https://developer.box.com/reference/delete-files-id/ --- ## Delete file request *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-file-requests-id/ **Reference:** https://developer.box.com/reference/delete-file-requests-id/ --- ## Delete folder *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-folders-id/ **Reference:** https://developer.box.com/reference/delete-folders-id/ --- ## Delete folder lock *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-folder-locks-id/ **Reference:** https://developer.box.com/reference/delete-folder-locks-id/ --- ## Delete hub *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/delete-hubs-id/ **Reference:** https://developer.box.com/reference/v2025.0/delete-hubs-id/ --- ## Delete retention policy *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-retention-policies-id/ **Reference:** https://developer.box.com/reference/delete-retention-policies-id/ --- ## Delete shield information barrier segment *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-shield-information-barrier-segments-id/ **Reference:** https://developer.box.com/reference/delete-shield-information-barrier-segments-id/ --- ## Delete shield information barrier segment member by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-shield-information-barrier-segment-members-id/ **Reference:** https://developer.box.com/reference/delete-shield-information-barrier-segment-members-id/ --- ## Delete shield information barrier segment restriction by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-shield-information-barrier-segment-restrictions-id/ **Reference:** https://developer.box.com/reference/delete-shield-information-barrier-segment-restrictions-id/ --- ## Delete single shield list by shield list id *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/delete-shield-lists-id/ **Reference:** https://developer.box.com/reference/v2025.0/delete-shield-lists-id/ --- ## Delete Slack integration mapping *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-integration-mappings-slack-id/ **Reference:** https://developer.box.com/reference/delete-integration-mappings-slack-id/ --- ## Delete Teams integration mapping *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-integration-mappings-teams-id/ **Reference:** https://developer.box.com/reference/delete-integration-mappings-teams-id/ --- ## Delete user *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-users-id/ **Reference:** https://developer.box.com/reference/delete-users-id/ --- ## Delete user avatar *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-users-id-avatar/ **Reference:** https://developer.box.com/reference/delete-users-id-avatar/ --- ## Device pinner *Type: resource | Category: api-resource* Device pins allow enterprises to control what devices can use native Box applications. # Device pinner Device pins allow enterprises to control what devices can use native Box applications. --- ## Device pinners *Type: resource | Category: api-resource* A list of device pins. # Device pinners A list of device pins. --- ## Download file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-content/ **Reference:** https://developer.box.com/reference/get-files-id-content/ --- ## Download zip archive *Type: endpoint | Category: api-endpoint* # undefined /reference/get-zip-downloads-id-content/ **Reference:** https://developer.box.com/reference/get-zip-downloads-id-content/ --- ## Email alias *Type: resource | Category: api-resource* An email alias for a user. # Email alias An email alias for a user. --- ## Email aliases *Type: resource | Category: api-resource* A list of email aliases. # Email aliases A list of email aliases. --- ## Enterprise (Base) *Type: resource | Category: api-resource* A mini representation of a enterprise, used when nested within another resource. # Enterprise (Base) A mini representation of a enterprise, used when nested within another resource. --- ## Event *Type: resource | Category: api-resource* The description of an event that happened within Box. # Event The description of an event that happened within Box. --- ## Event source *Type: resource | Category: api-resource* The source file or folder that triggered an event in the event stream. # Event source The source file or folder that triggered an event in the event stream. --- ## Events *Type: resource | Category: api-resource* A list of event objects. # Events A list of event objects. --- ## Extract metadata (freeform) *Type: endpoint | Category: api-endpoint* # undefined /reference/post-ai-extract/ **Reference:** https://developer.box.com/reference/post-ai-extract/ --- ## Extract metadata (structured) *Type: endpoint | Category: api-endpoint* # undefined /reference/post-ai-extract-structured/ **Reference:** https://developer.box.com/reference/post-ai-extract-structured/ --- ## File *Type: resource | Category: api-resource* A standard representation of a file, as returned from any file API endpoints by default. # File A standard representation of a file, as returned from any file API endpoints by default. --- ## File (Base) *Type: resource | Category: api-resource* The bare basic representation of a file, the minimal amount of fields returned when using the `fields` query parameter. # File (Base) The bare basic representation of a file, the minimal amount of fields returned when using the `fields` query parameter. --- ## File (Conflict) *Type: resource | Category: api-resource* A representation of a file that is used to show. # File (Conflict) A representation of a file that is used to show. --- ## File (Full) *Type: resource | Category: api-resource* A full representation of a file, as can be returned from any file API endpoints by default. # File (Full) A full representation of a file, as can be returned from any file API endpoints by default. --- ## File (Mini) *Type: resource | Category: api-resource* A mini representation of a file, used when nested under another resource. # File (Mini) A mini representation of a file, used when nested under another resource. --- ## File Request *Type: resource | Category: api-resource* A standard representation of a file request, as returned from any file request API endpoints by default. # File Request A standard representation of a file request, as returned from any file request API endpoints by default. --- ## File version *Type: resource | Category: api-resource* A standard representation of a file version. # File version A standard representation of a file version. --- ## File version (Base) *Type: resource | Category: api-resource* The bare basic representation of a file version, the minimal amount of fields returned when using the `fields` query parameter. # File version (Base) The bare basic representation of a file version, the minimal amount of fields returned when using the `fields` query parameter. --- ## File version (Full) *Type: resource | Category: api-resource* A full representation of a file version, as can be returned from any file version API endpoints by default. # File version (Full) A full representation of a file version, as can be returned from any file version API endpoints by default. --- ## File version (Mini) *Type: resource | Category: api-resource* A mini representation of a file version, used when nested within another resource. # File version (Mini) A mini representation of a file version, used when nested within another resource. --- ## File version legal hold *Type: resource | Category: api-resource* File version legal hold is an entity representing all holds on a File Version. # File version legal hold File version legal hold is an entity representing all holds on a File Version. --- ## File version legal holds *Type: resource | Category: api-resource* A list of file versions with legal holds. # File version legal holds A list of file versions with legal holds. --- ## File version retention *Type: resource | Category: api-resource* A retention policy blocks permanent deletion of content for a specified amount of time. Admins can apply policies to specified folders, or an entire enterprise. A file version retention is a record for a retained file version. To use this feature, you must have the manage retention policies scope enabled for your API key in your application management console. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. # File version retention A retention policy blocks permanent deletion of content for a specified amount of time. Admins can apply policies to specified folders, or an entire enterprise. A file version retention is a record for a retained file version. To use this feature, you must have the manage retention policies scope enabled for your API key in your application management console. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. --- ## File version retentions *Type: resource | Category: api-resource* A list of file version retentions. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. # File version retentions A list of file version retentions. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. --- ## File versions *Type: resource | Category: api-resource* A list of file versions. # File versions A list of file versions. --- ## File versions on hold *Type: resource | Category: api-resource* A list of files on hold for legal policy assignment. # File versions on hold A list of files on hold for legal policy assignment. --- ## Files *Type: resource | Category: api-resource* A list of files. # Files A list of files. --- ## Files on hold *Type: resource | Category: api-resource* A list of files on hold for legal policy assignment. # Files on hold A list of files on hold for legal policy assignment. --- ## Files under retention *Type: resource | Category: api-resource* A list of files under retention. # Files under retention A list of files under retention. --- ## Find app item for shared link *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shared-items--app-items/ **Reference:** https://developer.box.com/reference/get-shared-items--app-items/ --- ## Find file for shared link *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shared-items/ **Reference:** https://developer.box.com/reference/get-shared-items/ --- ## Find folder for shared link *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shared-items--folders/ **Reference:** https://developer.box.com/reference/get-shared-items--folders/ --- ## Find metadata template by instance ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-metadata-templates/ **Reference:** https://developer.box.com/reference/get-metadata-templates/ --- ## Find web link for shared link *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shared-items--web-links/ **Reference:** https://developer.box.com/reference/get-shared-items--web-links/ --- ## Folder *Type: resource | Category: api-resource* A standard representation of a folder, as returned from any folder API endpoints by default. # Folder A standard representation of a folder, as returned from any folder API endpoints by default. --- ## Folder (Base) *Type: resource | Category: api-resource* The bare basic representation of a folder, the minimal amount of fields returned when using the `fields` query parameter. # Folder (Base) The bare basic representation of a folder, the minimal amount of fields returned when using the `fields` query parameter. --- ## Folder (Full) *Type: resource | Category: api-resource* A full representation of a folder, as can be returned from any folder API endpoints by default. # Folder (Full) A full representation of a folder, as can be returned from any folder API endpoints by default. --- ## Folder (Mini) *Type: resource | Category: api-resource* A mini representation of a file version, used when nested under another resource. # Folder (Mini) A mini representation of a file version, used when nested under another resource. --- ## Folder Lock *Type: resource | Category: api-resource* Folder locks define access restrictions placed by folder owners to prevent specific folders from being moved or deleted. # Folder Lock Folder locks define access restrictions placed by folder owners to prevent specific folders from being moved or deleted. --- ## Folder Locks *Type: resource | Category: api-resource* A list of folder locks. # Folder Locks A list of folder locks. --- ## Force-apply metadata cascade policy to folder *Type: endpoint | Category: api-endpoint* # undefined /reference/post-metadata-cascade-policies-id-apply/ **Reference:** https://developer.box.com/reference/post-metadata-cascade-policies-id-apply/ --- ## Generate document using Box Doc Gen template *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/post-docgen-batches/ **Reference:** https://developer.box.com/reference/v2025.0/post-docgen-batches/ --- ## Generate text *Type: endpoint | Category: api-endpoint* # undefined /reference/post-ai-text-gen/ **Reference:** https://developer.box.com/reference/post-ai-text-gen/ --- ## Generic source *Type: resource | Category: api-resource* A generic event source type. # Generic source A generic event source type. --- ## Get AI agent by agent ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-ai-agents-id/ **Reference:** https://developer.box.com/reference/get-ai-agents-id/ --- ## Get AI agent default configuration *Type: endpoint | Category: api-endpoint* # undefined /reference/get-ai-agent-default/ **Reference:** https://developer.box.com/reference/get-ai-agent-default/ --- ## Get all shield lists in enterprise *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-shield-lists/ **Reference:** https://developer.box.com/reference/v2025.0/get-shield-lists/ --- ## Get allowed collaboration domain *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collaboration-whitelist-entries-id/ **Reference:** https://developer.box.com/reference/get-collaboration-whitelist-entries-id/ --- ## Get Box Doc Gen job by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-docgen-jobs-id/ **Reference:** https://developer.box.com/reference/v2025.0/get-docgen-jobs-id/ --- ## Get Box Doc Gen jobs by batch ID *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-docgen-batch-jobs-id/ **Reference:** https://developer.box.com/reference/v2025.0/get-docgen-batch-jobs-id/ --- ## Get Box Doc Gen template by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-docgen-templates-id/ **Reference:** https://developer.box.com/reference/v2025.0/get-docgen-templates-id/ --- ## Get Box Sign request by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-sign-requests-id/ **Reference:** https://developer.box.com/reference/get-sign-requests-id/ --- ## Get Box Sign template by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-sign-templates-id/ **Reference:** https://developer.box.com/reference/get-sign-templates-id/ --- ## Get classification on file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/ **Reference:** https://developer.box.com/reference/get-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/ --- ## Get classification on folder *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/ **Reference:** https://developer.box.com/reference/get-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/ --- ## Get collaboration *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collaborations-id/ **Reference:** https://developer.box.com/reference/get-collaborations-id/ --- ## Get collection by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collections-id/ **Reference:** https://developer.box.com/reference/get-collections-id/ --- ## Get comment *Type: endpoint | Category: api-endpoint* # undefined /reference/get-comments-id/ **Reference:** https://developer.box.com/reference/get-comments-id/ --- ## Get current user *Type: endpoint | Category: api-endpoint* # undefined /reference/get-users-me/ **Reference:** https://developer.box.com/reference/get-users-me/ --- ## Get device pin *Type: endpoint | Category: api-endpoint* # undefined /reference/get-device-pinners-id/ **Reference:** https://developer.box.com/reference/get-device-pinners-id/ --- ## Get events long poll endpoint *Type: endpoint | Category: api-endpoint* # undefined /reference/options-events/ **Reference:** https://developer.box.com/reference/options-events/ --- ## Get file information *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id/ **Reference:** https://developer.box.com/reference/get-files-id/ --- ## Get file request *Type: endpoint | Category: api-endpoint* # undefined /reference/get-file-requests-id/ **Reference:** https://developer.box.com/reference/get-file-requests-id/ --- ## Get file thumbnail *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-thumbnail-id/ **Reference:** https://developer.box.com/reference/get-files-id-thumbnail-id/ --- ## Get file version *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-versions-id/ **Reference:** https://developer.box.com/reference/get-files-id-versions-id/ --- ## Get file version legal hold *Type: endpoint | Category: api-endpoint* # undefined /reference/get-file-version-legal-holds-id/ **Reference:** https://developer.box.com/reference/get-file-version-legal-holds-id/ --- ## Get file versions under retention *Type: endpoint | Category: api-endpoint* # undefined /reference/get-retention-policy-assignments-id-file-versions-under-retention/ **Reference:** https://developer.box.com/reference/get-retention-policy-assignments-id-file-versions-under-retention/ --- ## Get files under retention *Type: endpoint | Category: api-endpoint* # undefined /reference/get-retention-policy-assignments-id-files-under-retention/ **Reference:** https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention/ --- ## Get folder information *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id/ **Reference:** https://developer.box.com/reference/get-folders-id/ --- ## Get group *Type: endpoint | Category: api-endpoint* # undefined /reference/get-groups-id/ **Reference:** https://developer.box.com/reference/get-groups-id/ --- ## Get group membership *Type: endpoint | Category: api-endpoint* # undefined /reference/get-group-memberships-id/ **Reference:** https://developer.box.com/reference/get-group-memberships-id/ --- ## Get hub collaboration by collaboration ID *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-hub-collaborations-id/ **Reference:** https://developer.box.com/reference/v2025.0/get-hub-collaborations-id/ --- ## Get hub collaborations *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-hub-collaborations/ **Reference:** https://developer.box.com/reference/v2025.0/get-hub-collaborations/ --- ## Get hub information by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-hubs-id/ **Reference:** https://developer.box.com/reference/v2025.0/get-hubs-id/ --- ## Get hub items *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-hub-items/ **Reference:** https://developer.box.com/reference/v2025.0/get-hub-items/ --- ## Get legal hold policy *Type: endpoint | Category: api-endpoint* # undefined /reference/get-legal-hold-policies-id/ **Reference:** https://developer.box.com/reference/get-legal-hold-policies-id/ --- ## Get legal hold policy assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/get-legal-hold-policy-assignments-id/ **Reference:** https://developer.box.com/reference/get-legal-hold-policy-assignments-id/ --- ## Get list of all Box Doc Gen jobs for template *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-docgen-template-jobs-id/ **Reference:** https://developer.box.com/reference/v2025.0/get-docgen-template-jobs-id/ --- ## Get metadata cascade policy *Type: endpoint | Category: api-endpoint* # undefined /reference/get-metadata-cascade-policies-id/ **Reference:** https://developer.box.com/reference/get-metadata-cascade-policies-id/ --- ## Get metadata instance on file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-metadata-id-id/ **Reference:** https://developer.box.com/reference/get-files-id-metadata-id-id/ --- ## Get metadata instance on folder *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id-metadata-id-id/ **Reference:** https://developer.box.com/reference/get-folders-id-metadata-id-id/ --- ## Get metadata template by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-metadata-templates-id/ **Reference:** https://developer.box.com/reference/get-metadata-templates-id/ --- ## Get metadata template by name *Type: endpoint | Category: api-endpoint* # undefined /reference/get-metadata-templates-id-id-schema/ **Reference:** https://developer.box.com/reference/get-metadata-templates-id-id-schema/ --- ## Get retention on file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-file-version-retentions-id/ **Reference:** https://developer.box.com/reference/get-file-version-retentions-id/ --- ## Get retention policy *Type: endpoint | Category: api-endpoint* # undefined /reference/get-retention-policies-id/ **Reference:** https://developer.box.com/reference/get-retention-policies-id/ --- ## Get retention policy assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/get-retention-policy-assignments-id/ **Reference:** https://developer.box.com/reference/get-retention-policy-assignments-id/ --- ## Get shared link for file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id--get-shared-link/ **Reference:** https://developer.box.com/reference/get-files-id--get-shared-link/ --- ## Get shared link for folder *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id--get-shared-link/ **Reference:** https://developer.box.com/reference/get-folders-id--get-shared-link/ --- ## Get shared link for web link *Type: endpoint | Category: api-endpoint* # undefined /reference/get-web-links-id--get-shared-link/ **Reference:** https://developer.box.com/reference/get-web-links-id--get-shared-link/ --- ## Get shield information barrier report by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barrier-reports-id/ **Reference:** https://developer.box.com/reference/get-shield-information-barrier-reports-id/ --- ## Get shield information barrier segment member by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barrier-segment-members-id/ **Reference:** https://developer.box.com/reference/get-shield-information-barrier-segment-members-id/ --- ## Get shield information barrier segment restriction by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barrier-segment-restrictions-id/ **Reference:** https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions-id/ --- ## Get shield information barrier segment with specified ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barrier-segments-id/ **Reference:** https://developer.box.com/reference/get-shield-information-barrier-segments-id/ --- ## Get shield information barrier with specified ID *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barriers-id/ **Reference:** https://developer.box.com/reference/get-shield-information-barriers-id/ --- ## Get single shield list by shield list id *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-shield-lists-id/ **Reference:** https://developer.box.com/reference/v2025.0/get-shield-lists-id/ --- ## Get storage policy *Type: endpoint | Category: api-endpoint* # undefined /reference/get-storage-policies-id/ **Reference:** https://developer.box.com/reference/get-storage-policies-id/ --- ## Get storage policy assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/get-storage-policy-assignments-id/ **Reference:** https://developer.box.com/reference/get-storage-policy-assignments-id/ --- ## Get task *Type: endpoint | Category: api-endpoint* # undefined /reference/get-tasks-id/ **Reference:** https://developer.box.com/reference/get-tasks-id/ --- ## Get task assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/get-task-assignments-id/ **Reference:** https://developer.box.com/reference/get-task-assignments-id/ --- ## Get terms of service *Type: endpoint | Category: api-endpoint* # undefined /reference/get-terms-of-services-id/ **Reference:** https://developer.box.com/reference/get-terms-of-services-id/ --- ## Get trashed file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-trash/ **Reference:** https://developer.box.com/reference/get-files-id-trash/ --- ## Get trashed folder *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id-trash/ **Reference:** https://developer.box.com/reference/get-folders-id-trash/ --- ## Get trashed web link *Type: endpoint | Category: api-endpoint* # undefined /reference/get-web-links-id-trash/ **Reference:** https://developer.box.com/reference/get-web-links-id-trash/ --- ## Get upload session *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-upload-sessions-id/ **Reference:** https://developer.box.com/reference/get-files-upload-sessions-id/ --- ## Get user *Type: endpoint | Category: api-endpoint* # undefined /reference/get-users-id/ **Reference:** https://developer.box.com/reference/get-users-id/ --- ## Get user avatar *Type: endpoint | Category: api-endpoint* # undefined /reference/get-users-id-avatar/ **Reference:** https://developer.box.com/reference/get-users-id-avatar/ --- ## Get user exempt from collaboration domain restrictions *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collaboration-whitelist-exempt-targets-id/ **Reference:** https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets-id/ --- ## Get user invite status *Type: endpoint | Category: api-endpoint* # undefined /reference/get-invites-id/ **Reference:** https://developer.box.com/reference/get-invites-id/ --- ## Get watermark for folder *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id-watermark/ **Reference:** https://developer.box.com/reference/get-folders-id-watermark/ --- ## Get watermark on file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-watermark/ **Reference:** https://developer.box.com/reference/get-files-id-watermark/ --- ## Get web link *Type: endpoint | Category: api-endpoint* # undefined /reference/get-web-links-id/ **Reference:** https://developer.box.com/reference/get-web-links-id/ --- ## Get webhook *Type: endpoint | Category: api-endpoint* # undefined /reference/get-webhooks-id/ **Reference:** https://developer.box.com/reference/get-webhooks-id/ --- ## Get zip download status *Type: endpoint | Category: api-endpoint* # undefined /reference/get-zip-downloads-id-status/ **Reference:** https://developer.box.com/reference/get-zip-downloads-id-status/ --- ## Group *Type: resource | Category: api-resource* A standard representation of a group, as returned from any group API endpoints by default. # Group A standard representation of a group, as returned from any group API endpoints by default. --- ## Group (Base) *Type: resource | Category: api-resource* A base representation of a group. # Group (Base) A base representation of a group. --- ## Group (Full) *Type: resource | Category: api-resource* Groups contain a set of users, and can be used in place of users in some operations, such as collaborations. # Group (Full) Groups contain a set of users, and can be used in place of users in some operations, such as collaborations. --- ## Group (Mini) *Type: resource | Category: api-resource* Mini representation of a group, including id and name of group. # Group (Mini) Mini representation of a group, including id and name of group. --- ## Group membership *Type: resource | Category: api-resource* Membership is used to signify that a user is part of a group. # Group membership Membership is used to signify that a user is part of a group. --- ## Group memberships *Type: resource | Category: api-resource* A list of group memberships. # Group memberships A list of group memberships. --- ## Groups *Type: resource | Category: api-resource* A list of groups. # Groups A list of groups. --- ## Hub *Type: resource | Category: api-resource* A standard representation of a hub, as returned from any hubs API endpoints by default. # Hub A standard representation of a hub, as returned from any hubs API endpoints by default. --- ## Hub (Base) *Type: resource | Category: api-resource* The bare basic representation of a hub. # Hub (Base) The bare basic representation of a hub. --- ## Hub Collaboration *Type: resource | Category: api-resource* A hub collaboration object grants a user or group access to a hub with permissions defined by a specific role. # Hub Collaboration A hub collaboration object grants a user or group access to a hub with permissions defined by a specific role. --- ## Hub Collaborations *Type: resource | Category: api-resource* A list of hub collaborations. # Hub Collaborations A list of hub collaborations. --- ## Hub Item *Type: resource | Category: api-resource* A Hub Item is a Box Item that is referenced in a Hub. # Hub Item A Hub Item is a Box Item that is referenced in a Hub. --- ## Hub Items *Type: resource | Category: api-resource* A list of Hub items. # Hub Items A list of Hub items. --- ## Hub Items Manage Response *Type: resource | Category: api-resource* Response schema for the status of Hub items management operations. # Hub Items Manage Response Response schema for the status of Hub items management operations. --- ## Hubs *Type: resource | Category: api-resource* A paginated list of hubs. # Hubs A paginated list of hubs. --- ## Integration mapping Slack *Type: resource | Category: api-resource* A Slack specific representation of an integration mapping object. # Integration mapping Slack A Slack specific representation of an integration mapping object. --- ## Integration mapping Teams *Type: resource | Category: api-resource* A Microsoft Teams specific representation of an integration mapping object. # Integration mapping Teams A Microsoft Teams specific representation of an integration mapping object. --- ## Integration mappings Slack *Type: resource | Category: api-resource* A list of integration mapping objects. # Integration mappings Slack A list of integration mapping objects. --- ## Integration mappings Teams *Type: resource | Category: api-resource* A list of integration mapping objects. # Integration mappings Teams A list of integration mapping objects. --- ## Invite *Type: resource | Category: api-resource* An invite for a user to an enterprise. # Invite An invite for a user to an enterprise. --- ## Items *Type: resource | Category: api-resource* A list of files, folders, and web links in their mini representation. # Items A list of files, folders, and web links in their mini representation. --- ## Items *Type: resource | Category: api-resource* A list of files, folders, and web links in their mini representation. # Items A list of files, folders, and web links in their mini representation. --- ## Keyword Skill Card *Type: resource | Category: api-resource* A skill card that contains a set of keywords. # Keyword Skill Card A skill card that contains a set of keywords. --- ## Legal hold policies *Type: resource | Category: api-resource* A list of legal hold policies. # Legal hold policies A list of legal hold policies. --- ## Legal hold policy *Type: resource | Category: api-resource* Legal Hold Policy information describes the basic characteristics of the Policy, such as name, description, and filter dates. # Legal hold policy Legal Hold Policy information describes the basic characteristics of the Policy, such as name, description, and filter dates. --- ## Legal hold policy (Mini) *Type: resource | Category: api-resource* A mini legal hold policy. # Legal hold policy (Mini) A mini legal hold policy. --- ## Legal hold policy assignment *Type: resource | Category: api-resource* Legal Hold Assignments are used to assign Legal Hold Policies to Users, Folders, Files, or File Versions. Creating a Legal Hold Assignment puts a hold on the File-Versions that belong to the Assignment's 'apply-to' entity. # Legal hold policy assignment Legal Hold Assignments are used to assign Legal Hold Policies to Users, Folders, Files, or File Versions. Creating a Legal Hold Assignment puts a hold on the File-Versions that belong to the Assignment's 'apply-to' entity. --- ## Legal hold policy assignment (Base) *Type: resource | Category: api-resource* Legal Hold Assignments are used to assign Legal Hold Policies to Users, Folders, Files, or File Versions. Creating a Legal Hold Assignment puts a hold on the File-Versions that belong to the Assignment's 'apply-to' entity. # Legal hold policy assignment (Base) Legal Hold Assignments are used to assign Legal Hold Policies to Users, Folders, Files, or File Versions. Creating a Legal Hold Assignment puts a hold on the File-Versions that belong to the Assignment's 'apply-to' entity. --- ## Legal hold policy assignments *Type: resource | Category: api-resource* A list of legal hold policies assignments. # Legal hold policy assignments A list of legal hold policies assignments. --- ## List AI agents *Type: endpoint | Category: api-endpoint* # undefined /reference/get-ai-agents/ **Reference:** https://developer.box.com/reference/get-ai-agents/ --- ## List all Box Doc Gen jobs *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-docgen-jobs/ **Reference:** https://developer.box.com/reference/v2025.0/get-docgen-jobs/ --- ## List all Box Doc Gen template tags in template *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-docgen-templates-id-tags/ **Reference:** https://developer.box.com/reference/v2025.0/get-docgen-templates-id-tags/ --- ## List all classifications *Type: endpoint | Category: api-endpoint* # undefined /reference/get-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema/ **Reference:** https://developer.box.com/reference/get-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema/ --- ## List all collections *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collections/ **Reference:** https://developer.box.com/reference/get-collections/ --- ## List all file versions *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-versions/ **Reference:** https://developer.box.com/reference/get-files-id-versions/ --- ## List all global metadata templates *Type: endpoint | Category: api-endpoint* # undefined /reference/get-metadata-templates-global/ **Reference:** https://developer.box.com/reference/get-metadata-templates-global/ --- ## List all hubs *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-hubs/ **Reference:** https://developer.box.com/reference/v2025.0/get-hubs/ --- ## List all hubs for requesting enterprise *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-enterprise-hubs/ **Reference:** https://developer.box.com/reference/v2025.0/get-enterprise-hubs/ --- ## List all legal hold policies *Type: endpoint | Category: api-endpoint* # undefined /reference/get-legal-hold-policies/ **Reference:** https://developer.box.com/reference/get-legal-hold-policies/ --- ## List all metadata templates for enterprise *Type: endpoint | Category: api-endpoint* # undefined /reference/get-metadata-templates-enterprise/ **Reference:** https://developer.box.com/reference/get-metadata-templates-enterprise/ --- ## List all webhooks *Type: endpoint | Category: api-endpoint* # undefined /reference/get-webhooks/ **Reference:** https://developer.box.com/reference/get-webhooks/ --- ## List allowed collaboration domains *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collaboration-whitelist-entries/ **Reference:** https://developer.box.com/reference/get-collaboration-whitelist-entries/ --- ## List archives *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-archives/ **Reference:** https://developer.box.com/reference/v2025.0/get-archives/ --- ## List Box Doc Gen templates *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/get-docgen-templates/ **Reference:** https://developer.box.com/reference/v2025.0/get-docgen-templates/ --- ## List Box Sign requests *Type: endpoint | Category: api-endpoint* # undefined /reference/get-sign-requests/ **Reference:** https://developer.box.com/reference/get-sign-requests/ --- ## List Box Sign templates *Type: endpoint | Category: api-endpoint* # undefined /reference/get-sign-templates/ **Reference:** https://developer.box.com/reference/get-sign-templates/ --- ## List Box Skill cards on file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-metadata-global-boxSkillsCards/ **Reference:** https://developer.box.com/reference/get-files-id-metadata-global-boxSkillsCards/ --- ## List collection items *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collections-id-items/ **Reference:** https://developer.box.com/reference/get-collections-id-items/ --- ## List enterprise device pins *Type: endpoint | Category: api-endpoint* # undefined /reference/get-enterprises-id-device-pinners/ **Reference:** https://developer.box.com/reference/get-enterprises-id-device-pinners/ --- ## List enterprise users *Type: endpoint | Category: api-endpoint* # undefined /reference/get-users/ **Reference:** https://developer.box.com/reference/get-users/ --- ## List file app item associations *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-app-item-associations/ **Reference:** https://developer.box.com/reference/get-files-id-app-item-associations/ --- ## List file collaborations *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-collaborations/ **Reference:** https://developer.box.com/reference/get-files-id-collaborations/ --- ## List file comments *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-comments/ **Reference:** https://developer.box.com/reference/get-files-id-comments/ --- ## List file version legal holds *Type: endpoint | Category: api-endpoint* # undefined /reference/get-file-version-legal-holds/ **Reference:** https://developer.box.com/reference/get-file-version-legal-holds/ --- ## List file version retentions *Type: endpoint | Category: api-endpoint* # undefined /reference/get-file-version-retentions/ **Reference:** https://developer.box.com/reference/get-file-version-retentions/ --- ## List files with current file versions for legal hold policy assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/get-legal-hold-policy-assignments-id-files-on-hold/ **Reference:** https://developer.box.com/reference/get-legal-hold-policy-assignments-id-files-on-hold/ --- ## List folder app item associations *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id-app-item-associations/ **Reference:** https://developer.box.com/reference/get-folders-id-app-item-associations/ --- ## List folder collaborations *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id-collaborations/ **Reference:** https://developer.box.com/reference/get-folders-id-collaborations/ --- ## List folder locks *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folder-locks/ **Reference:** https://developer.box.com/reference/get-folder-locks/ --- ## List group collaborations *Type: endpoint | Category: api-endpoint* # undefined /reference/get-groups-id-collaborations/ **Reference:** https://developer.box.com/reference/get-groups-id-collaborations/ --- ## List groups for enterprise *Type: endpoint | Category: api-endpoint* # undefined /reference/get-groups/ **Reference:** https://developer.box.com/reference/get-groups/ --- ## List items in folder *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id-items/ **Reference:** https://developer.box.com/reference/get-folders-id-items/ --- ## List legal hold policy assignments *Type: endpoint | Category: api-endpoint* # undefined /reference/get-legal-hold-policy-assignments/ **Reference:** https://developer.box.com/reference/get-legal-hold-policy-assignments/ --- ## List members of group *Type: endpoint | Category: api-endpoint* # undefined /reference/get-groups-id-memberships/ **Reference:** https://developer.box.com/reference/get-groups-id-memberships/ --- ## List metadata cascade policies *Type: endpoint | Category: api-endpoint* # undefined /reference/get-metadata-cascade-policies/ **Reference:** https://developer.box.com/reference/get-metadata-cascade-policies/ --- ## List metadata instances on file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-metadata/ **Reference:** https://developer.box.com/reference/get-files-id-metadata/ --- ## List metadata instances on folder *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-id-metadata/ **Reference:** https://developer.box.com/reference/get-folders-id-metadata/ --- ## List of Shield Information Barrier Reports *Type: resource | Category: api-resource* A list of shield barrier reports. # List of Shield Information Barrier Reports A list of shield barrier reports. --- ## List of Shield Information Barrier Segment Members *Type: resource | Category: api-resource* List of Shield Information Barrier Member objects. # List of Shield Information Barrier Segment Members List of Shield Information Barrier Member objects. --- ## List of Shield Information Barrier Segment Restrictions *Type: resource | Category: api-resource* List of shield information barrier segment restriction objects. # List of Shield Information Barrier Segment Restrictions List of shield information barrier segment restriction objects. --- ## List of Shield Information Barrier Segments *Type: resource | Category: api-resource* List of Shield Information Barrier Segment objects. # List of Shield Information Barrier Segments List of Shield Information Barrier Segment objects. --- ## List of Shield Information Barriers *Type: resource | Category: api-resource* List of Shield Information Barrier objects. # List of Shield Information Barriers List of Shield Information Barrier objects. --- ## List of Shield Lists *Type: resource | Category: api-resource* List of Shield List objects. # List of Shield Lists List of Shield List objects. --- ## List parts *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-upload-sessions-id-parts/ **Reference:** https://developer.box.com/reference/get-files-upload-sessions-id-parts/ --- ## List pending collaborations *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collaborations/ **Reference:** https://developer.box.com/reference/get-collaborations/ --- ## List previous file versions for legal hold policy assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/get-legal-hold-policy-assignments-id-file-versions-on-hold/ **Reference:** https://developer.box.com/reference/get-legal-hold-policy-assignments-id-file-versions-on-hold/ --- ## List recently accessed items *Type: endpoint | Category: api-endpoint* # undefined /reference/get-recent-items/ **Reference:** https://developer.box.com/reference/get-recent-items/ --- ## List retention policies *Type: endpoint | Category: api-endpoint* # undefined /reference/get-retention-policies/ **Reference:** https://developer.box.com/reference/get-retention-policies/ --- ## List retention policy assignments *Type: endpoint | Category: api-endpoint* # undefined /reference/get-retention-policies-id-assignments/ **Reference:** https://developer.box.com/reference/get-retention-policies-id-assignments/ --- ## List shield information barrier reports *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barrier-reports/ **Reference:** https://developer.box.com/reference/get-shield-information-barrier-reports/ --- ## List shield information barrier segment members *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barrier-segment-members/ **Reference:** https://developer.box.com/reference/get-shield-information-barrier-segment-members/ --- ## List shield information barrier segment restrictions *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barrier-segment-restrictions/ **Reference:** https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions/ --- ## List shield information barrier segments *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barrier-segments/ **Reference:** https://developer.box.com/reference/get-shield-information-barrier-segments/ --- ## List shield information barriers *Type: endpoint | Category: api-endpoint* # undefined /reference/get-shield-information-barriers/ **Reference:** https://developer.box.com/reference/get-shield-information-barriers/ --- ## List Slack integration mappings *Type: endpoint | Category: api-endpoint* # undefined /reference/get-integration-mappings-slack/ **Reference:** https://developer.box.com/reference/get-integration-mappings-slack/ --- ## List storage policies *Type: endpoint | Category: api-endpoint* # undefined /reference/get-storage-policies/ **Reference:** https://developer.box.com/reference/get-storage-policies/ --- ## List storage policy assignments *Type: endpoint | Category: api-endpoint* # undefined /reference/get-storage-policy-assignments/ **Reference:** https://developer.box.com/reference/get-storage-policy-assignments/ --- ## List task assignments *Type: endpoint | Category: api-endpoint* # undefined /reference/get-tasks-id-assignments/ **Reference:** https://developer.box.com/reference/get-tasks-id-assignments/ --- ## List tasks on file *Type: endpoint | Category: api-endpoint* # undefined /reference/get-files-id-tasks/ **Reference:** https://developer.box.com/reference/get-files-id-tasks/ --- ## List Teams integration mappings *Type: endpoint | Category: api-endpoint* # undefined /reference/get-integration-mappings-teams/ **Reference:** https://developer.box.com/reference/get-integration-mappings-teams/ --- ## List terms of service user statuses *Type: endpoint | Category: api-endpoint* # undefined /reference/get-terms-of-service-user-statuses/ **Reference:** https://developer.box.com/reference/get-terms-of-service-user-statuses/ --- ## List terms of services *Type: endpoint | Category: api-endpoint* # undefined /reference/get-terms-of-services/ **Reference:** https://developer.box.com/reference/get-terms-of-services/ --- ## List trashed items *Type: endpoint | Category: api-endpoint* # undefined /reference/get-folders-trash-items/ **Reference:** https://developer.box.com/reference/get-folders-trash-items/ --- ## List user and enterprise events *Type: endpoint | Category: api-endpoint* # undefined /reference/get-events/ **Reference:** https://developer.box.com/reference/get-events/ --- ## List user's email aliases *Type: endpoint | Category: api-endpoint* # undefined /reference/get-users-id-email-aliases/ **Reference:** https://developer.box.com/reference/get-users-id-email-aliases/ --- ## List user's groups *Type: endpoint | Category: api-endpoint* # undefined /reference/get-users-id-memberships/ **Reference:** https://developer.box.com/reference/get-users-id-memberships/ --- ## List users exempt from collaboration domain restrictions *Type: endpoint | Category: api-endpoint* # undefined /reference/get-collaboration-whitelist-exempt-targets/ **Reference:** https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets/ --- ## List workflows *Type: endpoint | Category: api-endpoint* # undefined /reference/get-workflows/ **Reference:** https://developer.box.com/reference/get-workflows/ --- ## Manage hub items *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/post-hubs-id-manage-items/ **Reference:** https://developer.box.com/reference/v2025.0/post-hubs-id-manage-items/ --- ## Metadata cascade policies *Type: resource | Category: api-resource* A list of metadata cascade policies. # Metadata cascade policies A list of metadata cascade policies. --- ## Metadata cascade policy *Type: resource | Category: api-resource* A metadata cascade policy automatically applies a metadata template instance to all the files and folders within the targeted folder. # Metadata cascade policy A metadata cascade policy automatically applies a metadata template instance to all the files and folders within the targeted folder. --- ## Metadata Error *Type: resource | Category: api-resource* A generic metadata operation error. # Metadata Error A generic metadata operation error. --- ## Metadata field filter (date range) *Type: resource | Category: api-resource* Specifies which `date` field on the template to filter the search results by, specifying a range of dates that can match. # Metadata field filter (date range) Specifies which `date` field on the template to filter the search results by, specifying a range of dates that can match. --- ## Metadata field filter (float range) *Type: resource | Category: api-resource* Specifies which `float` field on the template to filter the search results by, specifying a range of values that can match. # Metadata field filter (float range) Specifies which `float` field on the template to filter the search results by, specifying a range of values that can match. --- ## Metadata filter *Type: resource | Category: api-resource* A metadata template used to filter the search results. # Metadata filter A metadata template used to filter the search results. --- ## Metadata instance *Type: resource | Category: api-resource* An instance of a metadata template, which has been applied to a file or folder. # Metadata instance An instance of a metadata template, which has been applied to a file or folder. --- ## Metadata instance (Base) *Type: resource | Category: api-resource* The base representation of a metadata instance. # Metadata instance (Base) The base representation of a metadata instance. --- ## Metadata instance (Full) *Type: resource | Category: api-resource* An instance of a metadata template, which has been applied to a file or folder. # Metadata instance (Full) An instance of a metadata template, which has been applied to a file or folder. --- ## Metadata instances *Type: resource | Category: api-resource* A list of metadata instances that have been applied to a file or folder. # Metadata instances A list of metadata instances that have been applied to a file or folder. --- ## Metadata query index *Type: resource | Category: api-resource* A metadata query index. # Metadata query index A metadata query index. --- ## Metadata query search results *Type: resource | Category: api-resource* A page of files and folders that matched the metadata query. # Metadata query search results A page of files and folders that matched the metadata query. --- ## Metadata template *Type: resource | Category: api-resource* A template for metadata that can be applied to files and folders. # Metadata template A template for metadata that can be applied to files and folders. --- ## Metadata templates *Type: resource | Category: api-resource* A list of metadata templates. # Metadata templates A list of metadata templates. --- ## OAuth 2.0 error *Type: resource | Category: api-resource* An OAuth 2.0 error. # OAuth 2.0 error An OAuth 2.0 error. --- ## Permanently remove file *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-files-id-trash/ **Reference:** https://developer.box.com/reference/delete-files-id-trash/ --- ## Permanently remove folder *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-folders-id-trash/ **Reference:** https://developer.box.com/reference/delete-folders-id-trash/ --- ## Permanently remove web link *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-web-links-id-trash/ **Reference:** https://developer.box.com/reference/delete-web-links-id-trash/ --- ## Preflight check before upload *Type: endpoint | Category: api-endpoint* # undefined /reference/options-files-content/ **Reference:** https://developer.box.com/reference/options-files-content/ --- ## Promote file version *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-id-versions-current/ **Reference:** https://developer.box.com/reference/post-files-id-versions-current/ --- ## Query files/folders by metadata *Type: endpoint | Category: api-endpoint* # undefined /reference/post-metadata-queries-execute-read/ **Reference:** https://developer.box.com/reference/post-metadata-queries-execute-read/ --- ## Real-time server *Type: resource | Category: api-resource* A real-time server that can be used for long polling user events. # Real-time server A real-time server that can be used for long polling user events. --- ## Real-time servers *Type: resource | Category: api-resource* A list of real-time servers that can be used for long-polling. # Real-time servers A list of real-time servers that can be used for long-polling. --- ## Recent item *Type: resource | Category: api-resource* A recent item accessed by a user. # Recent item A recent item accessed by a user. --- ## Recent items *Type: resource | Category: api-resource* A list of recent items. # Recent items A list of recent items. --- ## Refresh access token *Type: endpoint | Category: api-endpoint* # undefined /reference/post-oauth2-token--refresh/ **Reference:** https://developer.box.com/reference/post-oauth2-token--refresh/ --- ## Remove Box Skill cards from file *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-files-id-metadata-global-boxSkillsCards/ **Reference:** https://developer.box.com/reference/delete-files-id-metadata-global-boxSkillsCards/ --- ## Remove classification from file *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/ **Reference:** https://developer.box.com/reference/delete-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/ --- ## Remove classification from folder *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/ **Reference:** https://developer.box.com/reference/delete-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/ --- ## Remove collaboration *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-collaborations-id/ **Reference:** https://developer.box.com/reference/delete-collaborations-id/ --- ## Remove comment *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-comments-id/ **Reference:** https://developer.box.com/reference/delete-comments-id/ --- ## Remove device pin *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-device-pinners-id/ **Reference:** https://developer.box.com/reference/delete-device-pinners-id/ --- ## Remove domain from list of allowed collaboration domains *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-collaboration-whitelist-entries-id/ **Reference:** https://developer.box.com/reference/delete-collaboration-whitelist-entries-id/ --- ## Remove email alias *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-users-id-email-aliases-id/ **Reference:** https://developer.box.com/reference/delete-users-id-email-aliases-id/ --- ## Remove file version *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-files-id-versions-id/ **Reference:** https://developer.box.com/reference/delete-files-id-versions-id/ --- ## Remove group *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-groups-id/ **Reference:** https://developer.box.com/reference/delete-groups-id/ --- ## Remove hub collaboration *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/delete-hub-collaborations-id/ **Reference:** https://developer.box.com/reference/v2025.0/delete-hub-collaborations-id/ --- ## Remove legal hold policy *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-legal-hold-policies-id/ **Reference:** https://developer.box.com/reference/delete-legal-hold-policies-id/ --- ## Remove metadata cascade policy *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-metadata-cascade-policies-id/ **Reference:** https://developer.box.com/reference/delete-metadata-cascade-policies-id/ --- ## Remove metadata instance from file *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-files-id-metadata-id-id/ **Reference:** https://developer.box.com/reference/delete-files-id-metadata-id-id/ --- ## Remove metadata instance from folder *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-folders-id-metadata-id-id/ **Reference:** https://developer.box.com/reference/delete-folders-id-metadata-id-id/ --- ## Remove metadata template *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-metadata-templates-id-id-schema/ **Reference:** https://developer.box.com/reference/delete-metadata-templates-id-id-schema/ --- ## Remove retention policy assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-retention-policy-assignments-id/ **Reference:** https://developer.box.com/reference/delete-retention-policy-assignments-id/ --- ## Remove shared link from file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id--remove-shared-link/ **Reference:** https://developer.box.com/reference/put-files-id--remove-shared-link/ --- ## Remove shared link from folder *Type: endpoint | Category: api-endpoint* # undefined /reference/put-folders-id--remove-shared-link/ **Reference:** https://developer.box.com/reference/put-folders-id--remove-shared-link/ --- ## Remove shared link from web link *Type: endpoint | Category: api-endpoint* # undefined /reference/put-web-links-id--remove-shared-link/ **Reference:** https://developer.box.com/reference/put-web-links-id--remove-shared-link/ --- ## Remove task *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-tasks-id/ **Reference:** https://developer.box.com/reference/delete-tasks-id/ --- ## Remove upload session *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-files-upload-sessions-id/ **Reference:** https://developer.box.com/reference/delete-files-upload-sessions-id/ --- ## Remove user from group *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-group-memberships-id/ **Reference:** https://developer.box.com/reference/delete-group-memberships-id/ --- ## Remove user from list of users exempt from domain restrictions *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-collaboration-whitelist-exempt-targets-id/ **Reference:** https://developer.box.com/reference/delete-collaboration-whitelist-exempt-targets-id/ --- ## Remove watermark from file *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-files-id-watermark/ **Reference:** https://developer.box.com/reference/delete-files-id-watermark/ --- ## Remove watermark from folder *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-folders-id-watermark/ **Reference:** https://developer.box.com/reference/delete-folders-id-watermark/ --- ## Remove web link *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-web-links-id/ **Reference:** https://developer.box.com/reference/delete-web-links-id/ --- ## Remove webhook *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-webhooks-id/ **Reference:** https://developer.box.com/reference/delete-webhooks-id/ --- ## Request access token *Type: endpoint | Category: api-endpoint* # undefined /reference/post-oauth2-token/ **Reference:** https://developer.box.com/reference/post-oauth2-token/ --- ## Resend Box Sign request *Type: endpoint | Category: api-endpoint* # undefined /reference/post-sign-requests-id-resend/ **Reference:** https://developer.box.com/reference/post-sign-requests-id-resend/ --- ## Restore file *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-id/ **Reference:** https://developer.box.com/reference/post-files-id/ --- ## Restore file version *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id-versions-id/ **Reference:** https://developer.box.com/reference/put-files-id-versions-id/ --- ## Restore folder *Type: endpoint | Category: api-endpoint* # undefined /reference/post-folders-id/ **Reference:** https://developer.box.com/reference/post-folders-id/ --- ## Restore web link *Type: endpoint | Category: api-endpoint* # undefined /reference/post-web-links-id/ **Reference:** https://developer.box.com/reference/post-web-links-id/ --- ## Retention policies *Type: resource | Category: api-resource* A list of retention policies. # Retention policies A list of retention policies. --- ## Retention policy *Type: resource | Category: api-resource* A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders, metadata templates, or their entire enterprise. To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console. # Retention policy A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders, metadata templates, or their entire enterprise. To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console. --- ## Retention policy (Base) *Type: resource | Category: api-resource* A base representation of a retention policy. # Retention policy (Base) A base representation of a retention policy. --- ## Retention policy (Mini) *Type: resource | Category: api-resource* A mini representation of a retention policy, used when nested within another resource. # Retention policy (Mini) A mini representation of a retention policy, used when nested within another resource. --- ## Retention policy assignment *Type: resource | Category: api-resource* A retention assignment represents a rule specifying the files a retention policy retains. Assignments can retain files based on their folder or metadata, or hold all files in the enterprise. # Retention policy assignment A retention assignment represents a rule specifying the files a retention policy retains. Assignments can retain files based on their folder or metadata, or hold all files in the enterprise. --- ## Retention policy assignment (Base) *Type: resource | Category: api-resource* A base representation of a retention policy assignment. # Retention policy assignment (Base) A base representation of a retention policy assignment. --- ## Retention policy assignments *Type: resource | Category: api-resource* A list of retention policy assignments. # Retention policy assignments A list of retention policy assignments. --- ## Revoke access token *Type: endpoint | Category: api-endpoint* # undefined /reference/post-oauth2-revoke/ **Reference:** https://developer.box.com/reference/post-oauth2-revoke/ --- ## Search for content *Type: endpoint | Category: api-endpoint* # undefined /reference/get-search/ **Reference:** https://developer.box.com/reference/get-search/ --- ## Search Result (including Shared Link) *Type: resource | Category: api-resource* A single of files, folder or web link that matched the search query, including the additional information about the shared link through which the item has been shared with the user. This response format is only returned when the `include_recent_shared_links` query parameter has been set to `true`. # Search Result (including Shared Link) A single of files, folder or web link that matched the search query, including the additional information about the shared link through which the item has been shared with the user. This response format is only returned when the `include_recent_shared_links` query parameter has been set to `true`. --- ## Search Results *Type: resource | Category: api-resource* A list of files, folders and web links that matched the search query. # Search Results A list of files, folders and web links that matched the search query. --- ## Search Results (including Shared Links) *Type: resource | Category: api-resource* A list of files, folders and web links that matched the search query, including the additional information about any shared links through which the item has been shared with the user. This response format is only returned when the `include_recent_shared_links` query parameter has been set to `true`. # Search Results (including Shared Links) A list of files, folders and web links that matched the search query, including the additional information about any shared links through which the item has been shared with the user. This response format is only returned when the `include_recent_shared_links` query parameter has been set to `true`. --- ## Session termination message *Type: resource | Category: api-resource* A message informing about the termination job status. # Session termination message A message informing about the termination job status. --- ## Shield information barrier *Type: resource | Category: api-resource* A standard representation of a shield information barrier object. # Shield information barrier A standard representation of a shield information barrier object. --- ## Shield information barrier (Base) *Type: resource | Category: api-resource* A base representation of a shield information barrier object. # Shield information barrier (Base) A base representation of a shield information barrier object. --- ## Shield information barrier reference *Type: resource | Category: api-resource* A shield information barrier reference for requests and responses. # Shield information barrier reference A shield information barrier reference for requests and responses. --- ## Shield information barrier report *Type: resource | Category: api-resource* A standard representation of a shield information barrier report object. # Shield information barrier report A standard representation of a shield information barrier report object. --- ## Shield information barrier report (Base) *Type: resource | Category: api-resource* A base representation of a shield information barrier report object. # Shield information barrier report (Base) A base representation of a shield information barrier report object. --- ## Shield information barrier report details *Type: resource | Category: api-resource* Indicates which folder the report file is located and any errors when generating the report. # Shield information barrier report details Indicates which folder the report file is located and any errors when generating the report. --- ## Shield information barrier segment *Type: resource | Category: api-resource* A shield information barrier segment object. # Shield information barrier segment A shield information barrier segment object. --- ## Shield information barrier segment member *Type: resource | Category: api-resource* A standard representation of a shield information barrier segment member object. # Shield information barrier segment member A standard representation of a shield information barrier segment member object. --- ## Shield information barrier segment member (Base) *Type: resource | Category: api-resource* A base representation of a shield information barrier segment member object. # Shield information barrier segment member (Base) A base representation of a shield information barrier segment member object. --- ## Shield information barrier segment member (Mini) *Type: resource | Category: api-resource* A mini representation of a shield information barrier segment member object. # Shield information barrier segment member (Mini) A mini representation of a shield information barrier segment member object. --- ## Shield information barrier segment restriction *Type: resource | Category: api-resource* A standard representation of a segment restriction of a shield information barrier object. # Shield information barrier segment restriction A standard representation of a segment restriction of a shield information barrier object. --- ## Shield information barrier segment restriction (Base) *Type: resource | Category: api-resource* A base representation of a segment restriction object for the shield information barrier. # Shield information barrier segment restriction (Base) A base representation of a segment restriction object for the shield information barrier. --- ## Shield information barrier segment restriction (Mini) *Type: resource | Category: api-resource* A mini representation of a segment restriction object for the shield information barrier. # Shield information barrier segment restriction (Mini) A mini representation of a segment restriction object for the shield information barrier. --- ## Shield List *Type: resource | Category: api-resource* A standard representation of a Shield List. # Shield List A standard representation of a Shield List. --- ## Shield List (Mini) *Type: resource | Category: api-resource* A mini representation of a Shield List. # Shield List (Mini) A mini representation of a Shield List. --- ## Shield List Content (Country) *Type: resource | Category: api-resource* Representation of content of a Shield List that contains countries data. # Shield List Content (Country) Representation of content of a Shield List that contains countries data. --- ## Shield List Content (Domain) *Type: resource | Category: api-resource* Representation of content of a Shield List that contains domains data. # Shield List Content (Domain) Representation of content of a Shield List that contains domains data. --- ## Shield List Content (Email) *Type: resource | Category: api-resource* Representation of content of a Shield List that contains email addresses data. # Shield List Content (Email) Representation of content of a Shield List that contains email addresses data. --- ## Shield List Content (Integration) *Type: resource | Category: api-resource* Representation of content of a Shield List that contains integrations data. # Shield List Content (Integration) Representation of content of a Shield List that contains integrations data. --- ## Shield List Content (IP) *Type: resource | Category: api-resource* Representation of content of a Shield List that contains ip addresses data. # Shield List Content (IP) Representation of content of a Shield List that contains ip addresses data. --- ## Skill webhook payload *Type: resource | Category: api-resource* The payload of a Box skill as sent to a skill's `invocation_url`. # Skill webhook payload The payload of a Box skill as sent to a skill's `invocation_url`. --- ## Skills metadata instance *Type: resource | Category: api-resource* The metadata assigned to a using for Box skills. # Skills metadata instance The metadata assigned to a using for Box skills. --- ## Starts workflow based on request body *Type: endpoint | Category: api-endpoint* # undefined /reference/post-workflows-id-start/ **Reference:** https://developer.box.com/reference/post-workflows-id-start/ --- ## Status Skill Card *Type: resource | Category: api-resource* A Box Skill metadata card that puts a status message in the metadata sidebar. # Status Skill Card A Box Skill metadata card that puts a status message in the metadata sidebar. --- ## Storage policies *Type: resource | Category: api-resource* A list of storage policies. # Storage policies A list of storage policies. --- ## Storage policy *Type: resource | Category: api-resource* The Storage Policy object describes the storage zone. # Storage policy The Storage Policy object describes the storage zone. --- ## Storage policy (Mini) *Type: resource | Category: api-resource* A mini description of a Storage Policy object. # Storage policy (Mini) A mini description of a Storage Policy object. --- ## Storage policy assignment *Type: resource | Category: api-resource* The assignment of a storage policy to a user or enterprise. # Storage policy assignment The assignment of a storage policy to a user or enterprise. --- ## Storage policy assignments *Type: resource | Category: api-resource* A list of storage policy assignments. # Storage policy assignments A list of storage policy assignments. --- ## Task *Type: resource | Category: api-resource* A task allows for file-centric workflows within Box. Users can create tasks on files and assign them to other users for them to complete the tasks. # Task A task allows for file-centric workflows within Box. Users can create tasks on files and assign them to other users for them to complete the tasks. --- ## Task assignment *Type: resource | Category: api-resource* A task assignment defines which task is assigned to which user to complete. # Task assignment A task assignment defines which task is assigned to which user to complete. --- ## Task assignments *Type: resource | Category: api-resource* A list of task assignments. # Task assignments A list of task assignments. --- ## Tasks *Type: resource | Category: api-resource* A list of tasks. # Tasks A list of tasks. --- ## Terms of service *Type: resource | Category: api-resource* The root-level record that is supposed to represent a single Terms of Service. # Terms of service The root-level record that is supposed to represent a single Terms of Service. --- ## Terms of service (Base) *Type: resource | Category: api-resource* The root-level record that is supposed to represent a single Terms of Service. # Terms of service (Base) The root-level record that is supposed to represent a single Terms of Service. --- ## Terms of service user status *Type: resource | Category: api-resource* The association between a Terms of Service and a user. # Terms of service user status The association between a Terms of Service and a user. --- ## Terms of service user statuses *Type: resource | Category: api-resource* A list of terms of service user statuses. # Terms of service user statuses A list of terms of service user statuses. --- ## Terms of services *Type: resource | Category: api-resource* A list of terms of services. # Terms of services A list of terms of services. --- ## The entity with type and ID *Type: resource | Category: api-resource* The entity with type and ID. # The entity with type and ID The entity with type and ID. --- ## Timeline Skill Card *Type: resource | Category: api-resource* A Box Skill metadata card that places a list of images on a timeline. # Timeline Skill Card A Box Skill metadata card that places a list of images on a timeline. --- ## Transcript Skill Card. *Type: resource | Category: api-resource* A Box Skill metadata card that adds a transcript to a file. # Transcript Skill Card. A Box Skill metadata card that adds a transcript to a file. --- ## Transfer owned folders *Type: endpoint | Category: api-endpoint* # undefined /reference/put-users-id-folders-0/ **Reference:** https://developer.box.com/reference/put-users-id-folders-0/ --- ## Trashed File *Type: resource | Category: api-resource* Represents a trashed file. # Trashed File Represents a trashed file. --- ## Trashed File (Restored) *Type: resource | Category: api-resource* Represents a file restored from the trash. # Trashed File (Restored) Represents a file restored from the trash. --- ## Trashed Folder *Type: resource | Category: api-resource* Represents a trashed folder. # Trashed Folder Represents a trashed folder. --- ## Trashed Folder (Restored) *Type: resource | Category: api-resource* Represents a folder restored from the trash. # Trashed Folder (Restored) Represents a folder restored from the trash. --- ## Trashed Web Link *Type: resource | Category: api-resource* Represents a trashed web link. # Trashed Web Link Represents a trashed web link. --- ## Trashed Web Link (Restored) *Type: resource | Category: api-resource* Represents a web link restored from the trash. # Trashed Web Link (Restored) Represents a web link restored from the trash. --- ## Unassign legal hold policy *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-legal-hold-policy-assignments-id/ **Reference:** https://developer.box.com/reference/delete-legal-hold-policy-assignments-id/ --- ## Unassign storage policy *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-storage-policy-assignments-id/ **Reference:** https://developer.box.com/reference/delete-storage-policy-assignments-id/ --- ## Unassign task *Type: endpoint | Category: api-endpoint* # undefined /reference/delete-task-assignments-id/ **Reference:** https://developer.box.com/reference/delete-task-assignments-id/ --- ## Update AI agent *Type: endpoint | Category: api-endpoint* # undefined /reference/put-ai-agents-id/ **Reference:** https://developer.box.com/reference/put-ai-agents-id/ --- ## Update all Box Skill cards on file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-skill-invocations-id/ **Reference:** https://developer.box.com/reference/put-skill-invocations-id/ --- ## Update Box Skill cards on file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id-metadata-global-boxSkillsCards/ **Reference:** https://developer.box.com/reference/put-files-id-metadata-global-boxSkillsCards/ --- ## Update classification *Type: endpoint | Category: api-endpoint* # undefined /reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--update/ **Reference:** https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--update/ --- ## Update classification on file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/ **Reference:** https://developer.box.com/reference/put-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/ --- ## Update classification on folder *Type: endpoint | Category: api-endpoint* # undefined /reference/put-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/ **Reference:** https://developer.box.com/reference/put-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/ --- ## Update collaboration *Type: endpoint | Category: api-endpoint* # undefined /reference/put-collaborations-id/ **Reference:** https://developer.box.com/reference/put-collaborations-id/ --- ## Update comment *Type: endpoint | Category: api-endpoint* # undefined /reference/put-comments-id/ **Reference:** https://developer.box.com/reference/put-comments-id/ --- ## Update file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id/ **Reference:** https://developer.box.com/reference/put-files-id/ --- ## Update file request *Type: endpoint | Category: api-endpoint* # undefined /reference/put-file-requests-id/ **Reference:** https://developer.box.com/reference/put-file-requests-id/ --- ## Update folder *Type: endpoint | Category: api-endpoint* # undefined /reference/put-folders-id/ **Reference:** https://developer.box.com/reference/put-folders-id/ --- ## Update group *Type: endpoint | Category: api-endpoint* # undefined /reference/put-groups-id/ **Reference:** https://developer.box.com/reference/put-groups-id/ --- ## Update group membership *Type: endpoint | Category: api-endpoint* # undefined /reference/put-group-memberships-id/ **Reference:** https://developer.box.com/reference/put-group-memberships-id/ --- ## Update hub collaboration *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/put-hub-collaborations-id/ **Reference:** https://developer.box.com/reference/v2025.0/put-hub-collaborations-id/ --- ## Update hub information by ID *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/put-hubs-id/ **Reference:** https://developer.box.com/reference/v2025.0/put-hubs-id/ --- ## Update legal hold policy *Type: endpoint | Category: api-endpoint* # undefined /reference/put-legal-hold-policies-id/ **Reference:** https://developer.box.com/reference/put-legal-hold-policies-id/ --- ## Update metadata instance on file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id-metadata-id-id/ **Reference:** https://developer.box.com/reference/put-files-id-metadata-id-id/ --- ## Update metadata instance on folder *Type: endpoint | Category: api-endpoint* # undefined /reference/put-folders-id-metadata-id-id/ **Reference:** https://developer.box.com/reference/put-folders-id-metadata-id-id/ --- ## Update metadata template *Type: endpoint | Category: api-endpoint* # undefined /reference/put-metadata-templates-id-id-schema/ **Reference:** https://developer.box.com/reference/put-metadata-templates-id-id-schema/ --- ## Update retention policy *Type: endpoint | Category: api-endpoint* # undefined /reference/put-retention-policies-id/ **Reference:** https://developer.box.com/reference/put-retention-policies-id/ --- ## Update shared link on file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-id--update-shared-link/ **Reference:** https://developer.box.com/reference/put-files-id--update-shared-link/ --- ## Update shared link on folder *Type: endpoint | Category: api-endpoint* # undefined /reference/put-folders-id--update-shared-link/ **Reference:** https://developer.box.com/reference/put-folders-id--update-shared-link/ --- ## Update shared link on web link *Type: endpoint | Category: api-endpoint* # undefined /reference/put-web-links-id--update-shared-link/ **Reference:** https://developer.box.com/reference/put-web-links-id--update-shared-link/ --- ## Update shield information barrier segment with specified ID *Type: endpoint | Category: api-endpoint* # undefined /reference/put-shield-information-barrier-segments-id/ **Reference:** https://developer.box.com/reference/put-shield-information-barrier-segments-id/ --- ## Update shield list *Type: endpoint | Category: api-endpoint* # undefined /reference/v2025.0/put-shield-lists-id/ **Reference:** https://developer.box.com/reference/v2025.0/put-shield-lists-id/ --- ## Update Slack integration mapping *Type: endpoint | Category: api-endpoint* # undefined /reference/put-integration-mappings-slack-id/ **Reference:** https://developer.box.com/reference/put-integration-mappings-slack-id/ --- ## Update storage policy assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/put-storage-policy-assignments-id/ **Reference:** https://developer.box.com/reference/put-storage-policy-assignments-id/ --- ## Update task *Type: endpoint | Category: api-endpoint* # undefined /reference/put-tasks-id/ **Reference:** https://developer.box.com/reference/put-tasks-id/ --- ## Update task assignment *Type: endpoint | Category: api-endpoint* # undefined /reference/put-task-assignments-id/ **Reference:** https://developer.box.com/reference/put-task-assignments-id/ --- ## Update Teams integration mapping *Type: endpoint | Category: api-endpoint* # undefined /reference/put-integration-mappings-teams-id/ **Reference:** https://developer.box.com/reference/put-integration-mappings-teams-id/ --- ## Update terms of service *Type: endpoint | Category: api-endpoint* # undefined /reference/put-terms-of-services-id/ **Reference:** https://developer.box.com/reference/put-terms-of-services-id/ --- ## Update terms of service status for existing user *Type: endpoint | Category: api-endpoint* # undefined /reference/put-terms-of-service-user-statuses-id/ **Reference:** https://developer.box.com/reference/put-terms-of-service-user-statuses-id/ --- ## Update user *Type: endpoint | Category: api-endpoint* # undefined /reference/put-users-id/ **Reference:** https://developer.box.com/reference/put-users-id/ --- ## Update web link *Type: endpoint | Category: api-endpoint* # undefined /reference/put-web-links-id/ **Reference:** https://developer.box.com/reference/put-web-links-id/ --- ## Update webhook *Type: endpoint | Category: api-endpoint* # undefined /reference/put-webhooks-id/ **Reference:** https://developer.box.com/reference/put-webhooks-id/ --- ## Upload file *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-content/ **Reference:** https://developer.box.com/reference/post-files-content/ --- ## Upload file version *Type: endpoint | Category: api-endpoint* # undefined /reference/post-files-id-content/ **Reference:** https://developer.box.com/reference/post-files-id-content/ --- ## Upload part *Type: resource | Category: api-resource* The representation of an upload session chunk. # Upload part The representation of an upload session chunk. --- ## Upload part (Mini) *Type: resource | Category: api-resource* The basic representation of an upload session chunk. # Upload part (Mini) The basic representation of an upload session chunk. --- ## Upload part of file *Type: endpoint | Category: api-endpoint* # undefined /reference/put-files-upload-sessions-id/ **Reference:** https://developer.box.com/reference/put-files-upload-sessions-id/ --- ## Upload parts *Type: resource | Category: api-resource* A list of uploaded chunks for an upload session. # Upload parts A list of uploaded chunks for an upload session. --- ## Upload session *Type: resource | Category: api-resource* An upload session for chunk uploading a file. # Upload session An upload session for chunk uploading a file. --- ## Upload URL *Type: resource | Category: api-resource* The details for the upload session for the file. # Upload URL The details for the upload session for the file. --- ## Uploaded part *Type: resource | Category: api-resource* A chunk of a file uploaded as part of an upload session, as returned by some endpoints. # Uploaded part A chunk of a file uploaded as part of an upload session, as returned by some endpoints. --- ## User *Type: resource | Category: api-resource* A standard representation of a user, as returned from any user API endpoints by default. # User A standard representation of a user, as returned from any user API endpoints by default. --- ## User (Base) *Type: resource | Category: api-resource* A mini representation of a user, used when nested within another resource. # User (Base) A mini representation of a user, used when nested within another resource. --- ## User (Collaborations) *Type: resource | Category: api-resource* A mini representation of a user, can be returned only when the status is `pending`. # User (Collaborations) A mini representation of a user, can be returned only when the status is `pending`. --- ## User (Full) *Type: resource | Category: api-resource* A full representation of a user, as can be returned from any user API endpoint. # User (Full) A full representation of a user, as can be returned from any user API endpoint. --- ## User (Integration Mappings) *Type: resource | Category: api-resource* A user representation for integration mappings API purposes. Fields name and login are not required. # User (Integration Mappings) A user representation for integration mappings API purposes. Fields name and login are not required. --- ## User (Mini) *Type: resource | Category: api-resource* A mini representation of a user, as can be returned when nested within other resources. # User (Mini) A mini representation of a user, as can be returned when nested within other resources. --- ## User avatar *Type: resource | Category: api-resource* A resource holding URLs to the avatar uploaded to a Box application. # User avatar A resource holding URLs to the avatar uploaded to a Box application. --- ## Users *Type: resource | Category: api-resource* A list of users. # Users A list of users. --- ## Watermark *Type: resource | Category: api-resource* A watermark is a semi-transparent overlay on an embedded file preview that displays a viewer's email address or user ID and the time of access over a file's content. # Watermark A watermark is a semi-transparent overlay on an embedded file preview that displays a viewer's email address or user ID and the time of access over a file's content. --- ## Web link *Type: resource | Category: api-resource* Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files. # Web link Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files. --- ## Web link (Base) *Type: resource | Category: api-resource* Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files. # Web link (Base) Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files. --- ## Web link (Mini) *Type: resource | Category: api-resource* Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files. # Web link (Mini) Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, they will also support most actions that apply to regular files. --- ## Webhook *Type: resource | Category: api-resource* Represents a configured webhook. # Webhook Represents a configured webhook. --- ## Webhook (Mini) *Type: resource | Category: api-resource* Represents a configured webhook. # Webhook (Mini) Represents a configured webhook. --- ## Webhook (V2) payload *Type: resource | Category: api-resource* The event that is sent to a webhook address when an event happens. # Webhook (V2) payload The event that is sent to a webhook address when an event happens. --- ## Webhooks *Type: resource | Category: api-resource* A list of webhooks. # Webhooks A list of webhooks. --- ## Workflow *Type: resource | Category: api-resource* Box Relay Workflows are objects that represent a named collection of flows. Your application must be authorized to use the `Manage Box Relay` application scope within the developer console in order to use this resource. # Workflow Box Relay Workflows are objects that represent a named collection of flows. Your application must be authorized to use the `Manage Box Relay` application scope within the developer console in order to use this resource. --- ## Workflow (Full) *Type: resource | Category: api-resource* Box Relay Workflows are objects that represent a named collection of flows. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in order to use this resource. # Workflow (Full) Box Relay Workflows are objects that represent a named collection of flows. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in order to use this resource. --- ## Workflow (Mini) *Type: resource | Category: api-resource* Box Relay Workflows are objects that represent a named collection of flows. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in order to use this resource. # Workflow (Mini) Box Relay Workflows are objects that represent a named collection of flows. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in order to use this resource. --- ## Workflows *Type: resource | Category: api-resource* A list of workflows. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in order to use this resource. # Workflows A list of workflows. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in order to use this resource. --- ## Zip download *Type: resource | Category: api-resource* Represents a successful request to create a `zip` archive of a list of files and folders. # Zip download Represents a successful request to create a `zip` archive of a list of files and folders. --- ## Zip download status *Type: resource | Category: api-resource* The status of a `zip` archive being downloaded. # Zip download status The status of a `zip` archive being downloaded. --- --- # Box AI Developer Zone This section contains 1 documentation items covering page. ## Untitled *Type: page | Category: Box AI Developer Zone * Box AI Developer Zone Box AI Developer Zone Box AI Developer Zone features interactive demos, sample code, and tools for building AI agents… # Box AI Developer Zone Box AI Developer Zone Box AI Developer Zone features interactive demos, sample code, and tools for building AI agents and intelligent workflows. Explore use cases, get hands-on experience with Box AI API, and build agents with Box AI Studio! Try out interactive demos Box AI API is available to all Enterprise Plus and Enterprise Advanced customers. Summarize a document in a selected tone of voice. Demo Use natural langage, or pass a stringified data structure to extract metadata with Box AI API. Demo Extract document metadata suggestions. Pass a Box metadata template ID or a predefined data structure. Demo Extract document metadata suggestions with the new Enhanced Extract Agent. Get the best answers thanks to chain-of-thought processing. New Tutorial Documentation These resources will get you up and running with Box AI API. Check the API reference for specification details. Documentation Browse the guides to learn how to use Box AI API. Documentation Box supports a variety of AI models, categorized along two dimensions: access level and capability tier. Check table list of the supported AI models. Documentation Override the default AI model configuration and fine tune LLMs with Box AI API. Documentation MCP Servers These resources will get you up and running with Box MCP Server. The remote Box MCP Server allows third party AI systems to securely connect and interact with your content in Box. New MCP A Python Developer Community open source project. It integrates with the Box API to perform various operations such as file search, text extraction, AI-based querying, and data extraction. MCP Use Box Doc Gen through the Box MCP server for AI-Powered Document Generation Tutorial Turn Box MCP Server into a LangChain-compatible agent using the LangChain MCP Adapters. Tutorial AI agents Learn how to create advanced AI agents with Box. Create and manage custom AI agents with Box AI Studio API. New Box AI Studio Get started with reusable Agentforce actions that help automate workflows and enhance intelligent agent—based processes within Salesforce. New Salesforce Use OpenAI Responses API and a Box Agent to add unstructured data from your Box instance into your agentic workflows. OpenAI Get started with a Python library for building AI agents for Box. Beta Box for AI Integrations Use Box for AI Integrations to extend LLM models' existing knowledge bases. Seamlessly connect unstructured content in Box with the powerful analytics capabilities of Snowflake, unlocking new insights and automating data-driven workflows. New Integration Transform unstructured documents into structured, queryable data by using the “Box data extract”, an Airbyte source connector. Integration Build RAG workflows by embedding Box content into a Weaviate vector database and leveraging Weaviate's new Query Agent. Integration Connect Box and Pinecone to customize vector embeddings and get more relevant answers from LLM. Integration Enable access to Box content within LLM workflows with Box reader suite for LlamaIndex. Integration Include Box content in your LLM workflows with Box loader for LangChain. Integration Use the Box MCP server to augment Pydantic AI agents with secure content in Box. Demo Videos Watch the latest Box AI API tutorials and demos. Check out the high-level features of the Box AI API in one minute. See a demo of the Box AI API text generation endpoint. See a demo of the Box AI API document Q&A endpoint. Extract metadata with various prompt formats with Box AI API. Extract metadata with predefined structure with Box AI API. Learn why Box chose to expose Box AI through our public API. View more videos **Reference:** https://developer.box.com/ai-dev-zone/ --- --- # Recent Updates This section contains 10 documentation items covering changelog. ## Untitled *Type: changelog* Windows .NET SDK v3.4.1 released Added support for Allowed Collaboration Domains Added Event Type enum Fixed deserialization issue with… # Windows .NET SDK v3.4.1 released Added support for [Allowed Collaboration Domains](https://developer.box.com/reference/resources/collaboration-allowlist-entry/) Added Event Type enum Fixed deserialization issue with `BoxRepresentationStatus` [`nuget.org/packages/Box.V2/3.4.1`](https://www.nuget.org/packages/Box.V2/3.4.1) [`nuget.org/packages/Box.V2.Core/3.4.1`](https://www.nuget.org/packages/Box.V2.Core/3.4.1) **Reference:** https://developer.box.com/changelog/#2018-01-10-windows-net-sdk-v341-release --- ## Untitled *Type: changelog* Java SDK v2.10.0 released Add optional is_confirmed parameter for adding user email alias (#499) Add support for token revocation (#51… # Java SDK v2.10.0 released - Add optional `is_confirmed` parameter for adding user email alias ([#499](https://github.com/box/box-java-sdk/pull/499)) - Add support for token revocation ([#510](https://github.com/box/box-java-sdk/pull/510)) - Metadata template delete ([#512](https://github.com/box/box-java-sdk/pull/512)) **Reference:** https://developer.box.com/changelog/#2018-01-12-java-sdk-v2100-release --- ## Untitled *Type: changelog* Java SDK v2.12.0 released Fix collaboration notify parameter (#545) Add OAuth 2.0 token creation event type (#533) Implement invite user to… # Java SDK v2.12.0 released 1. Fix collaboration notify parameter ([#545](https://github.com/box/box-java-sdk/pull/545)) 2. Add OAuth 2.0 token creation event type ([#533](https://github.com/box/box-java-sdk/pull/533)) 3. Implement invite user to enterprise ([#504](https://github.com/box/box-java-sdk/pull/504)) 4. Switch to `X-Box-UA` header for analytics ([#536](https://github.com/box/box-java-sdk/pull/536)) 5. Reduce Large File Upload memory usage ([#543](https://github.com/box/box-java-sdk/pull/543)) **Reference:** https://developer.box.com/changelog/#2018-02-01-java-sdk-v2120-release --- ## Untitled *Type: changelog* Java SDK v2.9.0 released Search readme update (#506) Add option to pass file SHA-1 hash for upload integrity (#502) Events log limit (#50… # Java SDK v2.9.0 released 1. Search `readme` update ([#506](https://github.com/box/box-java-sdk/pull/506)) 2. Add option to pass file `SHA-1` hash for upload integrity ([#502](https://github.com/box/box-java-sdk/pull/502)) 3. Events log limit ([#507](https://github.com/box/box-java-sdk/pull/507)) 4. Terms of Service ([#484](https://github.com/box/box-java-sdk/pull/484)) 5. Change `wiremock` port ([#505](https://github.com/box/box-java-sdk/pull/505)) 6. Delete redundant `response.disconnect()` from `moveFolderToUser()` ([#485](https://github.com/box/box-java-sdk/pull/485)) 7. Events `readme` patch ([#503](https://github.com/box/box-java-sdk/pull/503)) 8. Add missing webhook triggers to enum ([#497](https://github.com/box/box-java-sdk/pull/497)) 9. Fix `MetadataTemplate.updateMetadataTemplate()` type error ([#498](https://github.com/box/box-java-sdk/pull/498)) 10. Add missing event types to enum ([#500](https://github.com/box/box-java-sdk/pull/500)) 11. Add `modified_at` timestamp to `BoxComment.Info`([#501](https://github.com/box/box-java-sdk/pull/501)) 12. Collaboration whitelists ([#492](https://github.com/box/box-java-sdk/pull/492)) 13. Trash empty body patch ([#495](https://github.com/box/box-java-sdk/pull/495)) 14. Adding support for indefinite Box file locking by allowing null expiration ([#494](https://github.com/box/box-java-sdk/pull/494)) 15. Additional test in response for Batch API ([#474](https://github.com/box/box-java-sdk/pull/474)) 16. Fixing `BoxDeveloperEditionAPIConnection - decryptPrivateKey() - PEMParser returns PrivateKeyInfo already - Invalid cast` [#470](https://github.com/box/box-java-sdk/pull/470) ([#471](https://github.com/box/box-java-sdk/pull/471)) **Reference:** https://developer.box.com/changelog/#2018-01-04-java-sdk-v290-release --- ## Untitled *Type: changelog* Java SDK v2.11.0 released Fix chunked upload for files > 2GB (#531) Add updated file version upload endpoint and deprecate old method (#52… # Java SDK v2.11.0 released 1. Fix chunked upload for files > 2GB ([#531](https://github.com/box/box-java-sdk/pull/531)) 2. Add updated file version upload endpoint and deprecate old method ([#524](https://github.com/box/box-java-sdk/pull/524)) 3. Perform modified retry on JWT auth to avoid common JWT errors **Reference:** https://developer.box.com/changelog/#2018-01-25-java-sdk-v2110-release --- ## Untitled *Type: changelog* Java SDK v2.13.0 released Handle metadata values better (#553) # Java SDK v2.13.0 released 1. Handle metadata values better ([#553](https://github.com/box/box-java-sdk/pull/553)) **Reference:** https://developer.box.com/changelog/#2018-02-08-java-sdk-v2130-release --- ## Untitled *Type: changelog* Windows .NET SDK v3.4.2 released Updated Box SDK Version in NuSpec file to fix dependency issues for Box V2 and Box V2.Core. nuget.org… # Windows .NET SDK v3.4.2 released Updated Box SDK Version in `NuSpec` file to fix dependency issues for `Box V2` and `Box V2.Core`. [`nuget.org/packages/Box.V2/3.4.2`](https://www.nuget.org/packages/Box.V2/3.4.2) [`nuget.org/packages/Box.V2.Core/3.4.2`](https://www.nuget.org/packages/Box.V2.Core/3.4.2) **Reference:** https://developer.box.com/changelog/#2018-01-31-windows-net-sdk-v342-release --- ## Untitled *Type: changelog* Java SDK v2.14.1 released Add randomization to exponential backoff (#565) Force TLS version 1.1 or greater when supported (#548) Delay… # Java SDK v2.14.1 released 1. Add randomization to exponential backoff ([#565](https://github.com/box/box-java-sdk/pull/565)) 2. Force TLS version 1.1 or greater when supported ([#548](https://github.com/box/box-java-sdk/pull/548)) 3. Delay successive API calls by `EventStream` ([#564](https://github.com/box/box-java-sdk/pull/564)) **Reference:** https://developer.box.com/changelog/#2018-03-01-java-sdk-v2141-release --- ## Untitled *Type: changelog* Update to Box Annotations We will be introducing two enhancements to the annotations features available via the Box API that your customer… # Update to Box Annotations We will be introducing two enhancements to the annotations features available via the Box API that your customer uses in their custom application. The updates are as follows: - **Point Annotations mode**: We are enhancing point annotations by introducing Point Annotations mode. This allows users to expediently add annotations on a document without having to re-select the point annotation icon after each annotation. [here](guide://embed/ui-elements). - **Drawing Annotations via Expiring Embed**: We launched Drawing Annotations in November of 2017. This provided end users the ability to free-form draw on their touch-enabled devices using touch or a stylus. We are excited to share that we're making Drawing Annotations Full release announcement is available via the Expiring Embed. Users using annotations via the Get Embed Link API will now have a whole new way to express themselves via Box Preview. **Reference:** https://developer.box.com/changelog/#2018-03-05-update-to-box-annotations --- ## Untitled *Type: changelog* Breaking change to Metadata APIs On March 29, 2018, we will introduce a new data type (array of strings) in the response body of the Metadata API endpoints. We are making this change because we are adding a new field type to metadata templates in Box called multiSelect. This new field type represents a checkbox type multiple selection of values when creating template instances on files or folders. The selected options for this field type are stored in an array of strings, where each string in the array corresponds to the key of the chosen multiSelect option. # Breaking change to Metadata APIs On March 29, 2018, we will introduce a new data type (array of strings) in the response body of the Metadata API endpoints. We are making this change because we are adding a new field type to metadata templates in Box called `multiSelect`. This new field type represents a checkbox type multiple selection of values when creating template instances on files or folders. The selected options for this field type are stored in an array of strings, where each string in the array corresponds to the key of the chosen `multiSelect` option. An example metadata template JSON response body is shown below. The value for the key `audience1` shows an example of the new data type (array of strings) that we are introducing in this change. ``` { "audience1": ["internal", "internalEng"], "documentType": "Q1 plans", "competitiveDocument": "no", "status": "active", "author": "Jones", "currentState": "proposal", "$type": "marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe", "$parent": "file_5010739061", "$id": "2094c584-68e1-475c-a581-534a4609594e", "$version": 0, "$typeVersion": 0, "$template": "marketingCollateral", "$scope": "enterprise_12345" } ``` **Reference:** https://developer.box.com/changelog/#2018-02-28-breaking-change-to-metadata-apis --- --- # Additional Resources This section contains 682 documentation items covering quick-start, page. ## Untitled *Type: quick-start | Category: Guides * Quick Starts # Quick Starts **Reference:** https://developer.box.com/get-started/ --- ## Untitled *Type: page | Category: Box UI Elements * Box UI Elements Box AI API agent configurator Choose from multiple AI models from leading providers, all accessible through a single, easy… # Box UI Elements Box AI API agent configurator Choose from multiple AI models from leading providers, all accessible through a single, easy-to-use platform. Customize Box AI API parameters and fine-tune LLM parameters. Build complex AI configurations with our intuitive form-based interface. See your JSON configuration update in real-time as you make changes. Copy configuration and paste it directly in your project. **Reference:** https://developer.box.com/agent-configurator/ --- ## Untitled *Type: page | Category: Box Platform * Box Platform Start building with Box Platform Manage users with Box Platform Build experiences with Box Platform Integrate apps with Box… # Box Platform Start building with **Box Platform** Manage users with **Box Platform** Build experiences with **Box Platform** Integrate apps with **Box Platform** All the developer resources to help you get the most from Box products I'm new to Box Platform. How do I start? We got you covered! Follow these steps to build new applications and discover Box Platform capabilities. Box Platform covers many use cases that may require different user types. Learn more about the difference between the types. When creating applications, you can choose from several types. Read this guide to see which one fits your needs best. Box Platform supports OAuth 2.0, JSON Web Token(JWT), Client Credentials, and App Token authentication. Learn more and select the method that applies to your app. Now, you can start building! Launch the Developer Console and create an application of your choice. Read about the authorization requirements you have to fulfill to start using you app. Finally, explore our developer toolkit: API Reference, SDKS, Box CLI, Postman Collection, Box UI Elements and much more! Browse by SDK and tools Development with Box Platform is easy with SDKs, Box CLI, Postman collection, front-end UI elements, and much more. *Box API Reference* *box-python-sdk-gen* *box-java-sdk* *box-typescript-sdk-gen* *box-dotnet-sdk-gen* *box-ios-sdk* *box-swift-sdk-gen* *Box Postman Collection* *box-cli* *box-ui-elements* *Box Embed* See more details Additional Box Platform concepts Want to learn more? Use these guides to discover supplementary information on the inner workings of Box Platform, broaden your understanding, and improve your platform applications. Use Box API to download files to the application's server, or directly by the end user in a browser. Upload your files directly with the file upload API or use the chunked upload APIs for larger files. Browse the common errors reference to learn more about HTTP status codes used to communicate issues with request processing. Explore how metadata allows users and applications to define and store custom data associated with files and folders. Use Webhooks to monitor Box content for events, and receive notifications to a URL of your choice when they occur. Find relevant content in Box using full-text search queries. Box search API is supported in all our SDKs and the CLI. Integrate Box and Salesforce! Most recently we launched support for Salesforce Flows, a low code/no code solution. Browse all guides Additional resources **Reference:** https://developer.box.com/ --- ## Untitled *Type: page | Category: Developer Newsletter * Developer Newsletter Throughout the year, we send out a newsletter to our community with the top developer events, product releases, and… # Developer Newsletter Throughout the year, we send out a newsletter to our community with the top developer events, product releases, and community highlights. If you want to receive the newsletter, you are signed up automatically after you have access the [developer console](https://cloud.app.box.com/developers/console) for the first time. ## Past Newsletters Below is an archive of previous newsletters sent out. | Year | Month | Archive | | --- | --- | --- | | 2019 | September | Preview | | 2019 | December | Preview | | 2020 | April | Preview | | 2020 | July | Preview | | 2020 | December | Preview | | 2021 | April | Preview | | 2021 | August | Preview | | 2021 | November | Preview | | 2022 | February | Preview | | 2022 | June | Preview | | 2022 | August | Preview | | 2022 | September | Preview | | 2022 | November | Preview | | 2023 | February | Preview | | 2023 | May | Preview | | 2023 | June | Preview | | 2023 | August | Preview | | 2023 | November | Preview | | 2023 | December | Preview | | 2024 | January | Preview | | 2024 | February | Preview | | 2024 | March | Preview | | 2024 | April | Preview | | 2024 | May | Preview | | 2024 | June | Preview | | 2024 | July | Preview | | 2024 | August | Preview | | 2024 | September | Preview | | 2024 | October | Preview | | 2024 | November | Preview | **Reference:** https://developer.box.com/newsletter/ --- ## Untitled *Type: page | Category: Box UI Elements * Box UI Elements Create experiences with Box UI Elements Box UI Elements are pre-built UI components that allow you to extend custom portals… # Box UI Elements Create experiences with Box UI Elements Box UI Elements are pre-built UI components that allow you to extend custom portals with the elements of the main Box web application. Interactive Demos Box UI Elements are available both as React components and framework-agnostic JavaScript libraries. Get started Explore more Box UI Elements Follow more guides and documentation to help get you up and running. See how to embed Box AI in the Content Preview UI Element. Embed the Content Uploader and allow users to upload files. Display files based on specified metadata with the Content Explorer. Provide collaboration capabilities within the Content Preview. Build custom portals Learn more from videos, blog posts and sample code related to Box UI Elements. Build a content portal with a customized experience using Box UI Elements. Featuring Box APIs, Box UI Elements, React, Tailwind CSS, and Vercel. See how to embed Box AI in the Content Preview UI Element. **Reference:** https://developer.box.com/box-ui-elements/ --- ## Untitled *Type: page | Category: SDKs & Tools * SDKs & Tools The following SDKs and tools are developed and supported by Box. SDKs Here you will find a list of SDKs you can use to build… # SDKs & Tools The following SDKs and tools are developed and supported by Box. ## SDKs Here you will find a list of SDKs you can use to build your application. Separately, we have listed the next generation Python, TypeScript, and .NET SDKs, which are the newest addition. .NET is still a beta feature, but we encourage you to give it a try and explore all the features they bring along. The tables below list SDKs along with additional information telling you if the project is maintained and has API parity. **Status:** Describes the current project status. To learn more about statuses visit [Box Open Source website](https://opensource.box.com/badges/). Active projects are actively developed by Box. They receive the latest security updates and new features. For support with these projects please visit GitHub or [our Platform support forum](https://community.box.com/). **API Parity**: Projects with full API parity are actively updated with all platform functionality as this becomes available on the Box Platform. Projects with partial API parity lack some functionality while we work on bringing these projects to full parity. ### Next generation SDKs The latest generation Box Python SDK, Box TypeScript SDK, .NET SDK, and Swift SDK are designed to elevate the developer experience and streamline your integration with the Box Content Cloud. Swift SDK is in a Public Beta phase. Here's what you can expect from the new SDKs: - **Full API Support**: New Box SDKs empower developers with complete coverage of the Box API ecosystem. You can access all the latest features and functionalities offered by Box and build feature-rich applications. - **Rapid API Updates**: The new auto-generation development approach allows for adding Box APIs to SDKs at a much faster pace (in a matter of days). This means you can leverage the most up-to-date features in your applications without delay. - **Embedded Documentation**: All objects and parameters are documented directly in the source code of the SDK so all the necessary information is stored in one place. - **Enhanced Convenience Methods**: The newly introduced convenience methods cover various aspects such as authentication, chunk uploads, exponential back-offs, automatic retries, type checkers which help to ensure that you’re using variables correctly, and much more. Download the **Box Platform** SDK in a programming language of your choice and get started: | Platform | Status | API Parity | | --- | --- | --- | | Python Gen SDK | Active | Full | | TypeScript Gen SDK | Active | Full | | .NET SDK | Active | Full | | Swift SDK (Beta) | Active | Full | | Java Gen SDK (Beta) | Active | Full | ### Legacy SDKs The table lists legacy Box SDKs that you can use when building your applications. For latest API support and features, use the next generation SDKs. | Platform | Status | API Parity | | --- | --- | --- | | Java SDK | Active | Full | | iOS Content SDK | Active | Full | | Android Content SDK | Deprecated | Partial | | .NET SDK | Stable | Full | | Python SDK | Stable | Full | | Node SDK | Stable | Full | As of May 31, 2023 Android SDK is no longer supported. You can still use your existing Android SDK applications with no impact, but you won't receive new features, updates, or bug fixes. If you would like to continue getting the latest and greatest Android features, we recommend using Java SDK to build apps on Android. Refer to [this](https://github.com/box/box-java-sdk/blob/main/doc/android.md) documentation for more details. ## Box CLI Box CLI is a user-friendly command line tool which allows both technical and non-technical users to leverage Box API to perform routine or bulk actions. | Platform | Status | API Parity | | --- | --- | --- | | CLI | Active | Full | ## Postman Collection [Postman](https://postman.com) is a tool that lets you build and test HTTP requests in an easy-to-use interface without configuring a full development environment. The **Box Postman Collection** is a set of preconfigured requests that make it possible to get started with the Box API without having to manually configure the requests. The simplest way to get started with Postman is with our Postman Quick Start guide. Get Started with the Box Postman Collection ## Salesforce Developer Toolkit The Box for Salesforce Developer Toolkit allows customers to programmatically customize the behavior of the Box for Salesforce integration. The Toolkit consists of several global APEX methods that can be used to trigger and extend the default behavior. The global methods can update the internal Salesforce record to Box folder mapping and handle permission management. This functionality is part of the latest Box for [Salesforce package](https://support.box.com/hc/en-us/articles/360044195713-Installing-and-Configuring-Box-For-Salesforce). # What the Toolkit does NOT provide The Toolkit is not a full-featured APEX wrapper for the BOX Content API. If this is what you are looking for, have a look at the [Box SDK for Salesforce](https://github.com/box/box-salesforce-sdk). ## Official UI Libraries Extend your application with pre-built UI components to browse, share, and preview files on Box. | | | | | --- | --- | --- | | Browse | Share | Preview | | | | | | Navigate and manipulate your files on Box using our pre-built UI. | Share files with our pre-built UI elements for file & folder collaboration. | Review over 120 files types, from PDFs to HD videos, with a rich preview experience. | | Platform | | | --- | --- | | iOS | Browse SDK, Share SDK, Preview SDK | | Android | Browse SDK, Share SDK, Preview SDK | | Javascript | Box UI Elements | ## Unofficial & Community Tools The following tools are developed by Box and maintained by Box and its community members. These tools do not receive regular product updates or security updates. | Platform | Maintained? | API Parity | | --- | --- | --- | | Salesforce SDK | Limited, by Box and community members | Partial | | Ruby SDK | Limited, by Box and community members | Partial | | Client-side JS SDK | Limited, by Box and community members | Partial | **Maintained:** Projects with limited maintenance are updated by Box in collaboration with the community. They receive irregular security updates. If you are a Box customer on a premium support plan, please contact customer services for any urgent feature requests for these tools. For other support queries with these projects please visit GitHub or [our Platform support forum](https://community.box.com/). **API Parity:**  Projects with limited API parity can lack some functionality as new features are not automatically rolled out to these projects as they become available for the Box Platform. If you are a Box customer on a premium support plan, please contact customer services for any urgent feature requests for these tools. **Reference:** https://developer.box.com/sdks-and-tools/ --- ## Untitled *Type: page | Category: Working with Box Sign * Working with Box Sign This learning page provides developers with practical insights into working with Box Sign, aiming to facilitate the… # Working with Box Sign This learning page provides developers with practical insights into working with [Box Sign](https://www.box.com/esignature), aiming to facilitate the integration of the Box Platform Sign engine into their applications. ## Quick start Use the [Quick start](page://sign/quick-start) to go straight into the creation of a signature request. ## Technical use cases In the [Technical use cases](page://sign/technical-use-cases), you will learn how to handle the different types of documents that can be used in a signature request: from unstructured documents that require a preparation step, through templates, to generated ready to sign documents. ## Request Options In the [Request options](page://sign/request-options), you will find a detailed exploration of the available customization and configuration options when sending signing requests through the Box Sign API. Learn how to tailor the signing experience to match your application's user interface, workflow, and specific requirements. Let's get started! **Reference:** https://developer.box.com/sign/ --- ## Untitled *Type: page | Category: Support & Community * Support & Community Our community and support services are aimed to help ensure that your questions and integrations with Box Platform are… # Support & Community Our community and support services are aimed to help ensure that your questions and integrations with Box Platform are answered. For developer support, please reach out to us via one of our channels: - [Box Developer Community](https://community.box.com/): For support with code, technical integrations, and general requests. - [Twitter](https://twitter.com/BoxPlatform): For general questions and support. - [File a support ticket](https://support.box.com/hc/en-us/requests/new): For account specific questions and support. To keep up to date with community projects and Platform changes, please use one of these available channels: - [Changelog](page://changelog): For API changes, deprecated services, and releases. - [Developer Newsletter](page://newsletter): For regular notifications of major events, projects, and releases. **Reference:** https://developer.box.com/support/ --- ## Untitled *Type: page | Category: Support & Community * Community Projects The community projects list publicly available tools and services that have been generated by the Box developer community… # Community Projects The community projects list publicly available tools and services that have been generated by the Box developer community. They are split up into three main categories: SDKs and wrappers, API connectors, and tools. Community projects and connectors are created and maintained by the community, and are not owned or maintained by Box. Want to submit your project? Please review the [Contribution Guidelines](https://github.com/box-community/community-guidelines/blob/master/.github/CONTRIBUTING.md) or reach out to us [via email](mailto:developer@box.com). ## SDKs and Wrappers | Name | Language | Description | | --- | --- | --- | | Box Java Wrapper | Java | Java wrapper for the Box API written by Claus Ibsen. The Github repo can be found here | | Box JavaScript SDK | Javascript | A promise-based client-side SDK for making requests to the Box API. | | Box Ruby SDK | Ruby | A Ruby client library for the Box Content API. | | Box R SDK | R | R interface for the Box API. | | Box Powershell SDK | Powershell | Powershell SDK to call the Box API. | | Powershell module | Powershell | Powershell module which leverages the Box Windows SDK to administrate Box environments. Allows for complete automation of Box. | | Box PHP / Laravel Wrapper | PHP | PHP wrapper for the Box API. | | Box PHP Wrapper | PHP | PHP wrapper for the Box API. | ## API Connectors | Name | Description | | --- | --- | | Azure Logic Apps | Build your business flow based on the data you get from Box. | | Cloud Elements | Easily integrate Box with Hubspot, Salesforce, Microsoft Dynamics, and other popular cloud services. | | IBM Bluemix | Integrate Box to power content and data for your IBM Bluemix application. | | Kloudless | Power your app with integrations to Box and other CRM, calendar, and ITSM software services. | | Mendix | Connect Box to apps built using the Mendix application platform. | | Microsoft Flow | Create automated workflows between your favorite apps and services to get notifications, synchronize files, collect data, and more. | | Mulesoft | Create data synchronization and process automation between Box and third party CRM, CMS, mobile and social applications. | | Stamplay | Build automated workflows to connect real business processes to Box. | | Workato | Automate your document workflows by integrating Box with your CRM, marketing, ERP, support and accounting apps. | ## Tools | Name | Language | Description | | --- | --- | --- | | ShareX | C# | Open source screen capture tool that lets you upload to Box | **Reference:** https://developer.box.com/support/community-projects/ --- ## Untitled *Type: page | Category: Working with Box Sign * API Basics Sign API The Sign request endpoint is used to create and manage signature requests. You can create, resend, and cancel signature… # API Basics ## Sign API The Sign request endpoint is used to create and manage signature requests. You can create, resend, and cancel signature requests. You can also list all signature requests and get details of a specific signature request. The endpoint is `https://{api.box.com}/2.0/sign_requests`. The following table lists the operations that you can perform on this endpoint. | Operation | Endpoint | Description | | --- | --- | --- | | GET | /sign_requests | List all signature requests. | | GET | /sign_requests/:id | Get details of a specific signature request. | | POST | /sign_requests | Create a signature request. | | POST | /sign_requests/:id/resend | Resend a signature request. | | POST | /sign_requests/:id/cancel | Cancel a signature request. | For full details on the request and response parameters, see the Sign request API reference. ## Sign templates API The Sign templates endpoint is used to list and get details of a template. You can not create, edit, or delete templates using the API. These templates are exclusively managed in the Box web application. The endpoint is `https://{api.box.com}/2.0/sign_templates`. The following table lists the operations that you can perform on this endpoint. | Operation | Endpoint | Description | | --- | --- | --- | | GET | /sign_templates | List all templates. | | GET | /sign_templates/:id | Get details of a specific template. | For a full details on the request and response parameters, see the Sign template request API reference. **Reference:** https://developer.box.com/sign/quick-start/api-basics/ --- ## Untitled *Type: page | Category: Working with Box Sign * Quick start Get a sense of how the Box Sign API is structured and how to create your first signature request. The Sign API does not follow… # Quick start Get a sense of how the [Box Sign API](page://sign/quick-start/api-basics) is structured and how to create your first signature request. The Sign API does not follow the traditional CRUD model. You can create, resend, and cancel signature requests. You can also list all signature requests and get details of a specific signature request. Sign Templates API is read-only. You can list all templates and get details of a specific template. Once you get a sense of the API, you can create [your first signature request](page://sign/quick-start/your-first-request). **Reference:** https://developer.box.com/sign/quick-start/ --- ## Untitled *Type: page | Category: Working with Box Sign * Your first request Imagine that you have a document stored in Box and you want to send it to a customer for signature. At a minimum your app… # Your first request Imagine that you have a document stored in Box and you want to send it to a customer for signature. At a minimum your app needs to know what document to sign, where to store the signed document, and the signer email. ## Creating a signature request You can use the Box Sign API or one of the available SDKs to create a signature request. See the example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <access token>' \ --data-raw '{ "is_document_preparation_needed": true, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1355143830404", "type": "file" } ], "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def sign_doc_single( client: Client, document_id: str, destination_folder_id: str, signer_email: str, prep_needed: bool = False, ) -> SignRequest: # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner(signer_email) # sign document sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=destination_folder, source_files=[source_file], is_document_preparation_needed=prep_needed, ) return sign_request def main(): conf = ConfigOAuth() client = get_client_oauth(conf) # Simple sign a pdf request with preparation sign_pdf_prep = sign_doc_single( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, True ) if sign_pdf_prep.prepare_url is not None: open_browser(sign_pdf_prep.prepare_url) ``` This will result in a signature request with a prepare document URL (simplified): ``` { "is_document_preparation_needed": true, "signers": [ { "email": "requester@example.com", "role": "final_copy_reader", }, { "email": "signer@example.com", "role": "signer", } ], "id": "348decab-48a8-4f2c-9436-8967afebf7bb", "prepare_url": "https://app.box.com/sign/document/xyz-abc-123/.../prepare_doc/", "source_files": [ { "id": "1355143830404", "type": "file", } ], "parent_folder": { "id": "234102987614", "type": "folder", }, "name": "Simple-PDF.pdf", "type": "sign-request", "status": "converting", "sign_files": { "files": [ { "id": "1381301154812", "type": "file", } ], "is_ready_for_download": true }, "template_id": null } ``` ``` Simple sign request with prep: xyz-abc-123 Status: converting Signers: signer@example.com Prepare url: https://app.box.com/sign/document/xyz-abc-123/.../prepare_doc/ ``` ## Check the status of the signature request Creating the signature request is an asynchronous process, and can generate errors. Your application should check the status of the request before proceeding, and handle any errors. A signature request can have the following statuses: - `converting`: The file is converted to a `.pdf` for the signing process once the sign request is sent. - `error_converting`: An issue occurred while converting the file to a `.pdf`. - `created`: When the `document_preparation_is_needed` is set to `true`, but the `prepare_url` has not yet been visited. - `sent`: The request was successfully sent, but no signer has interacted with it. - `error_sending`: An issue occurred while sending the request. - `viewed`: The first, or only, signer clicked on **Review document** in the signing email or visited the signing URL. - `downloaded`: The document was downloaded by the signer. - `signed`: All signers completed the request. - `signed and downloaded`: The document was signed and downloaded by the signer. - `declined`: If any signer declines the request. - `cancelled`: If the request is cancelled via UI or API. - `expired`: The date of expiration has passed with outstanding, incomplete signatures. - `finalizing`: All signers have signed the request, but the final document with signatures and the signing log have not been generated yet. - `error_finalizing`: The `finalizing` phase did not complete successfully. ## Preparing the document Depending on your technical use case you may need to prepare the document. In this specific example, we are signing a PDF, and the Box Sign engine has no idea where to place the signature pad field or any other inputs. This is why we used the `is_document_preparation_needed` flag. If a prepare URL is present, then your application should open the prepare URL in a browser, where the requester can add the signature pad field and any other inputs needed for the signer to complete the document. Once the document is prepared, the requester can send the signature request to the signer. This preparation step is not always necessary. Take a look at the technical use cases for more information. ## Completing the signature request The signer then receives an email from Box with a link to the signature request. The signer can click the link and sign the document. When the process is completed, both a signature log containing metadata and the signed document are stored in the destination folder. Congratulations! You have successfully created your first signature request. This represents the basic use case for Box Sign. The `create` method has many options that you can use to customize your signature request. Be sure to check the [request options](page://sign/request-options), and the [technical use cases](page://sign/technical-use-cases) sections for more information. **Reference:** https://developer.box.com/sign/quick-start/your-first-request/ --- ## Untitled *Type: page | Category: Working with Box Sign * Technical use cases In your application you will be signing different documents from many sources. How can your application process such… # Technical use cases In your application you will be signing different documents from many sources. How can your application process such documents in order for them to be recognized by the Box Sign service? A signature request can have multiple requirements, or inputs, beyond the traditional signature, such as name, date, and initials. These inputs are called signature properties. The Box Sign service needs to know where to place these inputs in the document, and how to recognize them. The first step is to consider if the document has the necessary information for the Box Sign service to recognize the signature properties. If not, then the [document is unstructured](page://sign/technical-use-cases/sign-unstructured-docs), and should be prepared before sending the signature request. This is called document preparation, and is an extra step automatically created by the Box Sign service. There are two other types of documents that already have the necessary information for the Box Sign service to recognize the signature properties. The [sign templates](page://sign/technical-use-cases/sign-template), managed in the Box application, and the [structured documents](page://sign/technical-use-cases/sign-structured-docs), which are dynamically generated documents, containing specific tags representing the signature properties. Signing unstructured docs **Reference:** https://developer.box.com/sign/technical-use-cases/ --- ## Untitled *Type: page | Category: Working with Box Sign * Signing structured docs A structured document in the context of Box Sign is a document that includes specific tags that can be recognized by… # Signing structured docs A structured document in the context of Box Sign is a document that includes specific tags that can be recognized by the Box Sign API. These tags are used to place the signature properties associated with a specific signer in the document, such as name, date, and signature. This allows your app to handle a dynamic generated document that is ready to be signed, which has a couple of advantages: The document can be dynamically generated, and the signature properties can be added to the document before creating the signature request, effectively bypassing the document preparation step. The document format can be handled outside of Box Sign templates, allowing higher flexibility and integration with external document management systems. ## Anatomy of a structured document Here is an example of a structured document, showing the formatting used to place tags in a Microsoft Word document: In the sample above `[[c|1]]` means a checkbox assigned to signer 1, and `[[s| 1]]` means a signature pad assigned to signer 1. Notice how the signature pad is using font size 48 to reserve space vertically for the signature. The `[[t|1|id:tag_full_name|n:enter your complete name]]` means a name tag assigned to signer 1, with the label `enter your complete name`, and using an id of `tag_full_name`. Check out this [document](https://support.box.com/hc/en-us/articles/4404085855251-Creating-templates-using-tags) for a complete description of all the tags available. Setting the tags to the same `color` as the background will make them invisible, but they will still be there. The number in the tags refer to the signer number, not the signing order, so `[[c|1]]` is the checkbox for signer 1, `[[c|2]]` is the checkbox for signer 2, and so on. Tag 0 is reserved for the sender, and always exists. So even if the sender does not need to input any data into the document, the other signers must start with 1. ## Create a signature request from a structured document This is the same as creating a signature request from an unstructured document. At minimum, you will need to specify the document, the receiving folder and the email of the `signer`. Since the structured document already contains the signature properties details and location, you can bypass the document preparation. This is how the flow would look like, from the generated document, create the signature request and finally sign the document: Consider this method: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer nQ...xY' \ --data-raw '{ "source_files": [ { "type": "file", "id": "1363379762284" } ], "parent_folder": { "id": "234102987614", "type": "folder" }, "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def create_sign_request_structured( client: Client, file_id: str, signer_email: str ) -> SignRequest: """Create a sign request with structured data""" # Sign request params source_file = FileBase(id=file_id, type=FileBaseTypeField.FILE) parent_folder = FolderMini( id=SIGN_DOCS_FOLDER, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner(signer_email) # Create a sign request sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=parent_folder, source_files=[source_file], ) return sign_request def main(): ... # Create a sign request with structured data sign_request = create_sign_request_structured( client, STRUCTURED_DOC, SIGNER_A ) check_sign_request(sign_request) ``` Resulting in (simplified): ``` { "is_document_preparation_needed": false, "signers": [ { "email": "sender@example.com", "role": "final_copy_reader", }, { "email": "signer@example.com", "role": "signer", } ], "id": "28199d6c-4662-471e-8426-4cbba9affcf1", "source_files": [ { "id": "1363379762284", "type": "file", "name": "Box-Dive-Waiver.docx", } ], "parent_folder": { "id": "234102987614", "type": "folder", "name": "signed docs" }, "name": "Box-Dive-Waiver.pdf", "type": "sign-request", "status": "converting", "sign_files": { "files": [ { "id": "1393138856442", "type": "file", "name": "Box-Dive-Waiver.pdf", } ], }, } ``` ``` Simple sign request: 6878e048-e9bd-4fb1-88c6-8e502783e8d0 Status: converting Signers: 2 final_copy_reader: sender@example.com signer: signer@example.com Prepare url: None ``` If you go to the **signer** email inbox, open the email from Box Sign, click the **Review Document** button, you'll see the document with the signature properties in place: After completing the process the signed document looks like this: ## Pre-populate the signature attributes If you have an external id in the document tags you can use it to pre-populate their values. For example, you can use the `tag_full_name` to pre-populate the name of the signer. See this method: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer nQ...xY' \ --data-raw '{ "prefill_tags": [ { "document_tag_id": "tag_full_name", "text_value": "Signer A" } ], "source_files": [ { "type": "file", "id": "1363379762284" } ], "parent_folder": { "id": "234102987614", "type": "folder" }, "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def create_sign_request_structured_with_prefill( client: Client, file_id: str, signer_name, signer_email: str ) -> SignRequest: """Create a sign request with structured data""" # Sign request params source_file = FileBase(id=file_id, type=FileBaseTypeField.FILE) parent_folder = FolderMini( id=SIGN_DOCS_FOLDER, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner(signer_email) # tags tag_full_name = SignRequestPrefillTag( document_tag_id="tag_full_name", text_value=signer_name, ) # Create a sign request sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=parent_folder, source_files=[source_file], prefill_tags=[tag_full_name], ) return sign_request def main(): ... # Create a sign request with name pre populate sign_request_pre_pop = create_sign_request_structured_with_prefill( client, STRUCTURED_DOC, "Signer A", SIGNER_A ) check_sign_request(sign_request_pre_pop) ``` Resulting in (simplified): ``` { "is_document_preparation_needed": false, "redirect_url": null, "declined_redirect_url": null, "are_text_signatures_enabled": true, "signature_color": null, "is_phone_verification_required_to_view": false, "email_subject": null, "email_message": null, "are_reminders_enabled": false, "signers": [ { "email": "sender@example.com", "role": "final_copy_reader", }, { "email": "signer@example.com", "role": "signer", } ], "id": "11ecebc0-a2b2-4c14-a892-3f56333cc4fa", "prefill_tags": [ { "document_tag_id": "tag_full_name", "text_value": "Signer A", } ], "source_files": [ { "id": "1363379762284", "type": "file", "name": "Box-Dive-Waiver.docx", } ], "parent_folder": { "id": "234102987614", "type": "folder", "name": "signed docs" }, "name": "Box-Dive-Waiver (1).pdf", "type": "sign-request", "status": "converting", "sign_files": { "files": [ { "id": "1393142670032", "type": "file", "name": "Box-Dive-Waiver (1).pdf", } ], }, } ``` ``` Simple sign request: 7b86e46c-72ba-4568-a6ff-787077cca007 Status: converting Signers: 2 final_copy_reader: sender@example.com signer: signer@example.com Prepare url: None ``` The document now has the name pre-populated: ## Extract information from a signed document Let's say you want to extract the name of the signer and the other properties from the signed document. This is useful if you need to tie the information from the signature request back into your systems. Let's create a method to extract the information from the signed request: ``` curl --location 'https://api.box.com/2.0/sign_requests/ 11ecebc0-a2b2-4c14-a892-3f56333cc4fa' \ --header 'Authorization: Bearer nQ...xY' ``` ``` def check_sign_request_by_id(client: Client, sign_request_id: str): """Check sign request by id""" sign_request = client.sign_requests.get_sign_request_by_id(sign_request_id) print(f"\nSimple sign request: {sign_request.id}") print(f" Status: {sign_request.status.value}") print(f" Signers: {len(sign_request.signers)}") for signer in sign_request.signers: print(f" {signer.role.value}: {signer.email}") for input in signer.inputs: content_type = input.content_type value = None if content_type == SignRequestSignerInputTypeField.CHECKBOX: value = input.checkbox_value elif content_type == SignRequestSignerInputTypeField.TEXT: value = input.text_value elif content_type == SignRequestSignerInputTypeField.DATE: value = input.date_value print( f" {input.type.value}: {value if value is not None else '<other>'}" ) print(f" Prepare url: {sign_request.prepare_url}") def main(): ... # Latest sign request LATEST_SIGN_REQUEST = "7b86e46c-72ba-4568-a6ff-787077cca007" check_sign_request_by_id(client, LATEST_SIGN_REQUEST) ``` Resulting in (simplified): ``` { "signers": [ { "email": "sender@example.com", "role": "final_copy_reader", }, { "email": "signer@example.com", "role": "signer", "signer_decision": { "type": "signed", "finalized_at": "2023-12-19T14:53:10.547Z", }, "inputs": [ { "document_tag_id": null, "checkbox_value": true, "type": "checkbox", "content_type": "checkbox", }, { "document_tag_id": "tag_full_name", "text_value": "Signer A", "type": "text", "content_type": "text", }, { "document_tag_id": null, "text_value": "Dec 19, 2023", "date_value": "2023-12-19", "type": "date", "content_type": "date", }, { "document_tag_id": null, "type": "signature", "content_type": "signature", } ], } ], "id": "11ecebc0-a2b2-4c14-a892-3f56333cc4fa", "prefill_tags": [ { "document_tag_id": "tag_full_name", "text_value": "Signer A", } ], "source_files": [ { "id": "1363379762284", "type": "file", "name": "Box-Dive-Waiver.docx", } ], "parent_folder": { "id": "234102987614", "type": "folder", "name": "signed docs" }, "name": "Box-Dive-Waiver (1).pdf", "type": "sign-request", "signing_log": { "id": "1393140642252", "type": "file", "name": "Box-Dive-Waiver (1) Signing Log.pdf", }, "status": "signed", "sign_files": { "files": [ { "id": "1393142670032", "type": "file", "name": "Box-Dive-Waiver (1).pdf", } ], }, } ``` ``` Simple sign request: 7b86e46c-72ba-4568-a6ff-787077cca007 Status: signed Signers: 2 final_copy_reader: sender@example.com signer: signer@example.com checkbox: True text: Rui Barbosa date: 2023-11-15 signature: <other> Prepare url: None ``` ## Summary Structured documents are a great way to integrate with external document management systems, creating dynamic documents that are ready for signature. If your document signature requirements have a lot of options, you can pre-populate these from another data source and save the user's time, but remember that the user who owns these properties can always change them. After the document is signed you can extract the information from the signature request, which is useful if you need to tie it back into your systems. **Reference:** https://developer.box.com/sign/technical-use-cases/sign-structured-docs/ --- ## Untitled *Type: page | Category: Working with Box Sign * Signing using templates A Box Sign template is a specific type of document that not only contains the text, but also the signature… # Signing using templates A [Box Sign template](https://support.box.com/hc/en-us/sections/21356768117651-Templates) is a specific type of document that not only contains the text, but also the signature requirements and placement. It is prepared for signing in advance, and as such can be sent directly to the signer or signers. Required fields include, for example, the signature pad field, the full name, and the date. These fields have an owner, meaning they are populated by a specific signer and cannot be shared between them. They can be `mandatory` or `optional` , and be pre-populated by your application. However even if pre-populated, they can always be changed by the `signer`. Within the Box web app, the template not only sets the signature fields, but also the number of signers, the order in which they sign, other roles and recipients such as `approver`, and `final_copy_recipient`, email notification settings, and a few more options. For a complete set of options of the signature request please refer to the [request options](page://sign/request-options) section. These templates are exclusively created and managed in the Box Sign web app, and can be used to create signature requests using the API or the web app. Let's start by creating a template. ## Creating a template From the Box app navigate to the sign menu on the left, then select templates. Then, click on the New Template button, and choose or upload the document from Box. For example, drag and drop a date, a name and a signature pad to the template, like so: You can add an [extra layer of security](page://sign/request-options/extra-security) for a recipient. It works for both a defined recipient with a pre-defined email address, and a placeholder recipient, where the template user has to provide their email address. Save the template. ## Identify the template In order to work with templates in the Box Sign API we are going to need the `template_id` . Consider this method to list all the templates available to the user: ``` curl --location 'https://api.box.com/2.0/sign_templates' \ --header 'Authorization: Bearer E9...Q0' ``` ``` def sign_templates_list(client: Client): """List all sign templates""" sign_templates = client.sign_templates.get_sign_templates() print(f"\nSign templates: {len(sign_templates.entries)}") for sign_template in sign_templates.entries: print(f" {sign_template.id} - {sign_template.name}") def main(): """Simple script to demonstrate how to use the Box SDK""" conf = ConfigOAuth() client = get_client_oauth(conf) user = client.users.get_user_me() print(f"\nHello, I'm {user.name} ({user.login}) [{user.id}]") sign_templates_list(client) ``` Returns something similar to (simplified): ``` { "limit": 10, "next_marker": null, "prev_marker": null, "entries": [ { "type": "sign-template", "id": "f2ec720d-47a6-4052-8210-9bfa8d6c349c", "name": "Simple-DOC.pdf", "parent_folder": { "id": "157064745449", "type": "folder", "name": "My Sign Requests" }, "source_files": [ { "id": "1393013714313", "type": "file", } ], "signers": [ { "email": "", "label": "", "role": "final_copy_reader", "inputs": [] }, { "email": "", "label": "Signer", "role": "signer", "inputs": [ { "document_tag_id": null, "id": "d02c8e16-5050-475e-b74b-9a952193e4f8", "type": "date", "date_value": null, "content_type": "date", }, { "document_tag_id": null, "id": "bdcc966e-2ebf-4b3b-aaee-99d4e1161a9e", "type": "text", "text_value": null, "is_required": true, "content_type": "full_name", }, { "document_tag_id": null, "id": "1a8f4cb1-5c09-46bd-96f5-0ab449f19640", "type": "signature", "text_value": null, "is_required": true, "content_type": "signature", } ] } ], } ] } ``` ``` Hello, I'm Rui Barbosa [18622116055] Sign templates: 1 94e3815b-f7f5-4c2c-8a26-e9ba5c486031 - Simple-PDF.pdf ``` ## Creating a signature request from a template The big advantage of using templates is that we do not need to worry about document preparation. Most of the signature options can be set in the template itself. This is how the flow would look like: Using a signature template, create the signature request, and finally sign the document. See this example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer E9...Q0' \ --data-raw '{ "template_id": "f2ec720d-47a6-4052-8210-9bfa8d6c349c", "parent_folder": { "id": "234102987614", "type": "folder" }, "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def create_sign_request(client: Client, template_id: str, signer_email: str): """Create sign request from template""" parent_folder = FolderMini( id=SIGN_DOCS_FOLDER, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner( email=signer_email, ) sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=parent_folder, template_id=template_id, ) return sign_request def main(): ... # Create sign request from template sign_request = create_sign_request(client, TEMPLATE_SIMPLE, SIGNER_A) check_sign_request(sign_request) ``` Resulting in (simplified): ``` { "signers": [ { "email": "sender@example.com", "role": "final_copy_reader", }, { "email": "signer@example.com", "role": "signer", } ], "id": "71e86670-5850-44cc-8b4d-9f5eab6c04de", "parent_folder": { "id": "234102987614", "type": "folder", "name": "signed docs" }, "name": "Simple-DOC (1).pdf", "type": "sign-request", "status": "created", "sign_files": { "files": [ { "id": "1393030489686", "type": "file", "name": "Simple-DOC (1).pdf", } ], }, "template_id": "f2ec720d-47a6-4052-8210-9bfa8d6c349c" } ``` ``` Simple sign request: b25674a2-540b-4201-ae18-a78f05ef1a9a Status: created Signers: 2 final_copy_reader: sender@example.com signer: signer@example.com Prepare url: None ``` The signer receives an email from Box.com with a link to the document, and can sign it. Since the template already had the signature requirements, document preparation was not needed. Notice the date was automatically populated with the current date. ## Pre-populate the signature attributes From a usability perspective, it is a good idea to pre-populate the inputs you require from your users. Some inputs may be intentionally left unpopulated. For example, when your legal department specifies that the “Yes, I agree” field must be explicitly set by the signer. Using the Box app sign template editor, you can assign an `external_id` to each of the inputs, and have the app populate them from any data source. Let’s implement this for the name. Go back to the template design and add an id to the name field: Save the template. Let’s create a new method to pre-populate the name: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer E9..Q0' \ --data-raw '{ "template_id": "f2ec720d-47a6-4052-8210-9bfa8d6c349c", "parent_folder": { "id": "234102987614", "type": "folder" }, "signers": [ { "email": "signer@example.com", "role": "signer" } ], "prefill_tags": [ { "document_tag_id": "signer_full_name", "text_value": "Signer A" } ] }' ``` ``` def create_sign_request_name_default( client: Client, template_id: str, signer_name, signer_email: str ): """Create sign request from template""" parent_folder = FolderMini( id=SIGN_DOCS_FOLDER, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner( email=signer_email, ) # tags tag_full_name = SignRequestPrefillTag( document_tag_id="signer_full_name", text_value=signer_name, ) sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=parent_folder, prefill_tags=[tag_full_name], template_id=template_id, ) return sign_request def main(): ... # Create sign request from template with name sign_request_name = create_sign_request_name_default( client, TEMPLATE_SIMPLE, "Signer A", SIGNER_A ) check_sign_request(sign_request_name) ``` Resulting in (simplified): ``` { "signers": [ { "email": "sender@example.com", "role": "final_copy_reader", }, { "email": "signer@example.com", "role": "signer", "is_in_person": false, } ], "id": "6f42a041-7ed8-4e08-9958-78a97259f80d", "prefill_tags": [ { "document_tag_id": "signer_full_name", "text_value": "Signer A", } ], "parent_folder": { "id": "234102987614", "type": "folder", "name": "signed docs" }, "name": "Simple-DOC (2).pdf", "type": "sign-request", "status": "created", "sign_files": { "files": [ { "id": "1393047116817", "type": "file", "name": "Simple-DOC (2).pdf", } ], }, "template_id": "f2ec720d-47a6-4052-8210-9bfa8d6c349c" } ``` ``` Simple sign request: adab1740-eeba-4392-a3f5-defddc79c946 Status: created Signers: 2 final_copy_reader: sender@example.com signer: signer@example.com Prepare url: None ``` Open the signer inbox and complete the sign request. When the signer views the document, the `signer` can still change it. ## Get more information about a template You've seen that you can list the templates available to a user. But you can also get more information about a specific template. Let’s create a method that returns basic information of a template, but details all the signature requirements: ``` curl --location 'https://api.box.com/2.0/sign_templates/ f2ec720d-47a6-4052-8210-9bfa8d6c349c' \ --header 'Authorization: Bearer OL..BQ' ``` ``` def sign_template_print_info(client: Client, template_id: str): sign_template = client.sign_templates.get_sign_template_by_id(template_id) print(f"\nSign template: {sign_template.id} - {sign_template.name}") print(f" Signers: {len(sign_template.signers)}") for signer in sign_template.signers: print(f" {signer.role.value}") if len(signer.inputs) > 0: print(" Tag ID\t Type\t Required") for input in signer.inputs: print( f" {input.document_tag_id} {input.type.value} {input.is_required}" ) def main(): ... # Print sign template details sign_template_print_info(client, TEMPLATE_SIMPLE) ``` Resulting in (simplified): ``` { "type": "sign-template", "id": "f2ec720d-47a6-4052-8210-9bfa8d6c349c", "name": "Simple-DOC.pdf", "parent_folder": { "id": "234102987614", "type": "folder", "name": "signed docs" }, "source_files": [ { "id": "1393013714313", "type": "file", } ], "signers": [ { "email": "", "label": "", "role": "final_copy_reader", }, { "email": "", "label": "Signer", "role": "signer", "inputs": [ { "document_tag_id": null, "id": "d02c8e16-5050-475e-b74b-9a952193e4f8", "type": "date", "is_required": true, "date_value": null, "content_type": "date", }, { "document_tag_id": "signer_full_name", "id": "bdcc966e-2ebf-4b3b-aaee-99d4e1161a9e", "type": "text", "text_value": null, "is_required": true, "content_type": "full_name", }, { "document_tag_id": null, "id": "1a8f4cb1-5c09-46bd-96f5-0ab449f19640", "type": "signature", "is_required": true, "content_type": "signature", } ] } ], } ``` ``` Sign template: 94e3815b-f7f5-4c2c-8a26-e9ba5c486031 - Simple-PDF.pdf Signers: 2 final_copy_reader signer Tag ID Type Required None date True signer_full_name text True None signature True ``` Notice that the `signer_full_name` is the `tag_id` we used to pre-populate the name. ## Summary Templates are a form of signing structured documents where the signature requirements are already defined and placed on the document. This not only keeps your contract management team happy, but it also creates a process which is consistent and requires a low level of effort from your users. Finally if your document signature requirements have a lot of options, you can pre-populate these from another data source and save the user some time. Remember that the user who owns these properties can always change them. There is no API entry point to create a template, so you will have to create and manage them manually from the Box app, unless the document already includes signature tags that can be used by the Box Sign engine. Take a look at our [Structured Docs](page://sign/technical-use-cases/sign-structured-docs) section for more information. **Reference:** https://developer.box.com/sign/technical-use-cases/sign-template/ --- ## Untitled *Type: page | Category: Working with Box Sign * Custom email and notifications Email subject and body By default, the email sent to the signers contains a link to the document, a generic… # Custom email and notifications ## Email subject and body By default, the email sent to the signers contains a link to the document, a generic subject, and a generic message. If you are using templates managed within Box, the subject and message body can be set in the template itself. However, if you are not using templates, you can still customize the email messages sent to the signers by passing the `email_subject` and the `email_message` parameters. Both parameters accept strings, but the `email_message` parameter also accepts HTML with some limitations. Only some HTML tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message parameter may contain the following HTML tags: - `a`, `abbr`, `acronym`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, `strong` Custom styles on these tags are not allowed. Be aware that when the text to HTML ratio is too high, the email may end up in spam filters or clipped. For example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ej...3t' \ --data-raw '{ "email_subject": "All we need is your signature to get started", "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1358047520478", "type": "file" } ], "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def sign_doc_single_more_options( client: Client, ... email_subject: str = None, email_message: str = None, ) -> SignRequest: ... # sign document sign_request = client.sign_requests.create_sign_request( ... email_subject=email_subject, email_message=email_message, ) return sign_request def main(): ... # Sign with custom email subject sign_custom_email_subject = sign_doc_single_more_options( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, prep_needed=False, email_subject="All we need is your signature to get started", ) ``` ## Manual notification By now, you've noticed that the signature request sends an email notification to the signers by default. This email is sent from a `box.com` domain and email system. You can take over the notification process by setting the `embed_url_external_user_id` parameter to an identifier of your choice for a specific signer. By setting this parameter, the signer will not receive an email notification, and within the signature request, you get back both an `embed_url` and an `iframeable_embed_url`. The `embed_url` can be opened directly, so it is suitable for your app to send it in an email, or by any other notifications system for the signer to open. The `iframeable_embed_url` is suited to be used with the Box Embedded Sign Client, which allows you to embed the Box Sign client on an iframe within your web app. For example see this request: ``` --header 'Content-Type: application/json' \ --header 'Authorization: Bearer fN...dD' \ --data-raw '{ "is_document_preparation_needed": false, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1355143830404", "type": "file" } ], "signers": [ { "email": "signer@example.com", "embed_url_external_user_id": "1234", "role": "signer" } ] }' ``` ``` def sign_doc_embed_url( client: Client, document_id: str, destination_folder_id: str, signer_email: str, signer_embed_url_id: str, ) -> SignRequest: # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner( email=signer_email, embed_url_external_user_id=signer_embed_url_id, ) # sign document sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=destination_folder, source_files=[source_file], ) return sign_request def main(): """Simple script to demonstrate how to use the Box SDK""" conf = ConfigOAuth() client = get_client_oauth(conf) # Sign with phone verification sign_with_embed_url = sign_doc_embed_url( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, SIGNER_A_EXTERNAL_ID, ) check_sign_request(sign_with_embed_url) ``` Returns (simplified): ``` { "is_document_preparation_needed": false, "signers": [ { "email": "sender@example.com", "role": "final_copy_reader", }, { "email": "signer@example.com", "role": "signer", "embed_url_external_user_id": "1234", "embed_url": "https://app.box.com/sign/document/22a990ce-4e24-463b-b2f4-124820fe161a/9331fe9ac85650d61645d4b0fd30fe3e0ebee7921720ab6ecca587654d3cd875/", "iframeable_embed_url": "https://app.box.com/embed/sign/document/22a990ce-4e24-463b-b2f4-124820fe161a/9331fe9ac85650d61645d4b0fd30fe3e0ebee7921720ab6ecca587654d3cd875/" } ], "id": "22a990ce-4e24-463b-b2f4-124820fe161a", } ``` ``` Simple sign request: 22a990ce-4e24-463b-b2f4-124820fe161a-defddc79c946 Status: created Signers: 2 final_copy_reader: sender@example.com signer: signer@example.com embed_url: https://app.box.com/sign/document/... iframeable_embed_url: https://app.box.com/embed/sign/document/... Prepare url: None ``` You can now take the embedded URLs and use your own notification process or embed the signature client within your own app. **Reference:** https://developer.box.com/sign/request-options/custom-email/ --- ## Untitled *Type: page | Category: Working with Box Sign * Signing unstructured docs Imagine a document management app, where users can upload a document and ask anyone to sign it. In this case your… # Signing unstructured docs Imagine a document management app, where users can upload a document and ask anyone to sign it. In this case your app will know what document to sign and who needs to sign, but it has no idea where to put the signature or its properties like name, date, initial, and so on. This contrasts with [using templates](page://sign/technical-use-cases/sign-template) or [structured documents](page://sign/technical-use-cases/sign-structured-docs) where your app knows what they are, and where the signature properties go. In these cases, and because each document can have a different structure, it is a good idea to always set the `is_document_preparation_needed` flag set to `true`, so that the sender has a chance to select and place the signature properties in the document before the signer gets the request. There are three steps to this flow, creating the signature request, then preparing the document, and finally signing it. This is how the flow looks like: Consider this example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <access token>' \ --data-raw '{ "is_document_preparation_needed": true, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1355143830404", "type": "file" } ], "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def sign_doc_single( client: Client, document_id: str, destination_folder_id: str, signer_email: str, prep_needed: bool = False, ) -> SignRequest: # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner(signer_email) # sign document sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=destination_folder, source_files=[source_file], is_document_preparation_needed=prep_needed, ) return sign_request def main(): conf = ConfigOAuth() client = get_client_oauth(conf) # Simple sign a pdf request with preparation sign_pdf_prep = sign_doc_single( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, True ) if sign_pdf_prep.prepare_url is not None: open_browser(sign_pdf_prep.prepare_url) ``` This results in a signature request with a prepare document URL (simplified): ``` { "is_document_preparation_needed": true, "signers": [ { "email": "requester@example.com", "role": "final_copy_reader", }, { "email": "signer@example.com", "role": "signer", } ], "id": "348decab-48a8-4f2c-9436-8967afebf7bb", "prepare_url": "https://app.box.com/sign/document/xyz-abc-123/.../prepare_doc/", "source_files": [ { "id": "1355143830404", "type": "file", } ], "parent_folder": { "id": "234102987614", "type": "folder", }, "name": "Simple-PDF.pdf", "type": "sign-request", "status": "converting", "sign_files": { "files": [ { "id": "1381301154812", "type": "file", } ], "is_ready_for_download": true }, "template_id": null } ``` ``` Simple sign request with prep: xyz-abc-123 Status: converting Signers: signer@example.com Prepare url: https://app.box.com/sign/document/xyz-abc-123/.../prepare_doc/ ``` Notice in the above script that, if a prepare document URL was generated by the signature request, then the app opens a browser for it. The requester can then apply the different signature properties, for example: Once the document is prepared, the requester can send the signature request to the signer. Back in the Box app you can see the status `In Progress`. The signer then receives an email from Box with a link to the signature request. When the process is completed, both a signature log containing metadata and the signed document are stored in the destination folder. **Reference:** https://developer.box.com/sign/technical-use-cases/sign-unstructured-docs/ --- ## Untitled *Type: page | Category: Working with Box Sign * Request options The Box Sign API offers a wide range of customization and configuration options when sending signature requests. These… # Request options The Box Sign API offers a wide range of customization and configuration options when sending signature requests. These options allow developers to tailor the user experience and workflow to match their application's specific requirements. **Reference:** https://developer.box.com/sign/request-options/ --- ## Untitled *Type: page | Category: Working with Box Sign * Redirect URLs Often after signing a document your company might want to redirect the user to a specific web page like a thank you or an… # Redirect URLs Often after signing a document your company might want to redirect the user to a specific web page like a thank you or an onboarding page. There are two features to support these requirements. When the signer completes the signature process, they can be redirected to a web page. The same can happen when the signer declines the signature request. We can customize these pages by passing the `redirect_url` and `decline_redirect_url` parameters. For example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ej...3t' \ --data-raw '{ "is_document_preparation_needed": true, "redirect_url": "https://community.box.com/", "declined_redirect_url": "https://developer.box.com/", "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1358047520478", "type": "file" } ], "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def sign_doc_single_more_options( ... redirect_url: str = None, declined_redirect_url: str = None, ) -> SignRequest: ... # sign document sign_request = client.sign_requests.create_sign_request( ... redirect_url=redirect_url, declined_redirect_url=declined_redirect_url, ) return sign_request def main(): ... # Sign with redirects sign_with_redirects = sign_doc_single_more_options( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, prep_needed=False, redirect_url="https://community.box.com/", declined_redirect_url="https://developer.box.com/", ) check_sign_request(sign_with_redirects) ``` If you sign you’ll be redirected to our forum page. If you decline you’ll be redirected to our developer page. **Reference:** https://developer.box.com/sign/request-options/custom-urls/ --- ## Untitled *Type: page | Category: Working with Box Sign * Extra security (2FA) Imagine you want an additional layer of security for your signature requests, by requesting the signer to use a… # Extra security (2FA) Imagine you want an [additional layer of security](https://support.box.com/hc/en-us/articles/4406861109907-Additional-Signer-Authentication) for your signature requests, by requesting the signer to use a password or a phone verification in the document signing step. You can add the additional layer of security in a template or when you create a signature request. ## Phone verification You can require the signer to use 2FA through their mobile phone to complete the signature request by passing the `verification_phone_number` parameter on the signer along with their phone number. For example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ej...3t' \ --data-raw '{ "is_document_preparation_needed": true, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1358047520478", "type": "file" } ], "signers": [ { "email": "verify@example.com", "role": "signer", "verification_phone_number": "+15551232190" } ] }' ``` ``` def sign_doc_verify_phone( client: Client, document_id: str, destination_folder_id: str, signer_email: str, signer_phone: str, ) -> SignRequest: # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner( email=signer_email, verification_phone_number=signer_phone, ) # sign document sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=destination_folder, source_files=[source_file], is_phone_verification_required_to_view=True, ) return sign_request def main(): ... # Sign with phone verification sign_with_phone_verification = sign_doc_verify_phone( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, SIGNER_A_PHONE, ) check_sign_request(sign_with_phone_verification) ``` When the signer tries to access the signature request a phone verification dialog pops up: Then the signer is prompted to enter the code sent in an SMS: ## Password verification You can require the signer to use a password to open the signature request by passing the `password` parameter in the `signer` object. For example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ej...3t' \ --data-raw '{ "is_document_preparation_needed": true, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1358047520478", "type": "file" } ], "signers": [ { "email": "verify@example.com", "role": "signer", "password": "1234" } ] }' ``` ``` def sign_doc_verify_password( client: Client, document_id: str, destination_folder_id: str, signer_email: str, signer_password: str, ) -> SignRequest: # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) # signer signer = SignRequestCreateSigner( email=signer_email, password=signer_password, ) # sign document sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=destination_folder, source_files=[source_file], ) return sign_request def main(): ... # Sign with phone verification sign_with_password_verification = sign_doc_verify_password( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, "1234", ) ``` Once the signer opens the signature request they should see something like this: As the password verification is done on the first step, it prevents the signer from accessing the document until the correct password is provided. **Reference:** https://developer.box.com/sign/request-options/extra-security/ --- ## Untitled *Type: page | Category: Working with Box Sign * Request expiration There are situations where you might need to set an expiration date for the signature request. For example, imagine a… # Request expiration There are situations where you might need to [set an expiration date](https://support.box.com/hc/en-us/articles/4404105810195-Sending-a-document-for-signature#:~:text=Step%205%3A%20Setting%20an%20expiration) for the signature request. For example, imagine a quote for a service that is valid for 30 days. This proposal has to be signed by a certain date, and if not, the signature request for the quote is no longer valid. All you need to do is pass the `days_valid` parameter. For example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ej...3t' \ --data-raw '{ "days_valid": 30, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1358047520478", "type": "file" } ], "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def sign_doc_single_more_options( ... days_valid: int = None, ) -> SignRequest: ... # sign document sign_request = client.sign_requests.create_sign_request( ... days_valid=days_valid, ) return sign_request ``` **Reference:** https://developer.box.com/sign/request-options/request-expiration/ --- ## Untitled *Type: page | Category: Working with Box Sign * In person signatures Imagine your application is used by a salesperson when they are face to face with a customer and an immediate signature… # In person signatures Imagine your application is used by a salesperson when they are face to face with a customer and an immediate signature is required, for example, to subscribe to a service or to confirm a purchase. In this case, the salesperson can use your application to create a signature request and then hand over the device to the customer to sign the document, immediately closing the deal. Doing this using the Box web application, for example from a template, is very straightforward. You set the signer or signers email so they can receive a copy of the signed document, flag them as in person, and as soon as you send the request, the Sign interface opens requesting the signature for the first signer, then for the second signer, and so on. In order to use this within your application, you need to create a signature request with the `is_in_person` flag set to `true` for each signer. However because your application needs to show the Sign interface to the signer, you also need to use the `embed_url_external_user_id`so that you get back the embedded URLs, and then either open a browser window or use an iframe to display the signature interface. ## Create an in person signature request Let's use a template with a single signer as an example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer Le...Cb' \ --data-raw '{ "template_id": "ee9a689e-96b6-4076-92a0-b9b765eb09ca", "parent_folder": { "id": "234102987614", "type": "folder" }, "signers": [ { "email": "signer@example.com", "role": "signer", "is_in_person": true, "embed_url_external_user_id": "1234" } ] }' ``` ``` def sign_doc_in_person( client: Client, document_id: str, destination_folder_id: str, signer_email: str, signer_embed_url_id: str, ) -> SignRequest: # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) signer = SignRequestCreateSigner( email=signer_email, embed_url_external_user_id=signer_embed_url_id, is_in_person=True, ) # sign document sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=destination_folder, source_files=[source_file], ) return sign_request def main(): """Simple script to demonstrate how to use the Box SDK""" conf = ConfigOAuth() client = get_client_oauth(conf) # Sign with phone verification sign_with_embed_url = sign_doc_embed_url( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, SIGNER_A_EXTERNAL_ID, ) check_sign_request(sign_with_embed_url) ``` Resulting in (simplified): ``` { "signers": [ { "email": "sender@example.com", "role": "final_copy_reader", "is_in_person": false, }, { "email": "signer@example.com", "role": "signer", "is_in_person": true, "embed_url_external_user_id": "1234", "embed_url": "https://app.box.com/sign/document/...", "iframeable_embed_url": "https://app.box.com/embed/sign/document/..." } ], "id": "a9159d31-d2fb-4e88-9306-02c00de013d1", "parent_folder": { "id": "234102987614", "type": "folder", "name": "signed docs" }, "name": "Simple-PDF (1).pdf", "type": "sign-request", "status": "created", "template_id": "ee9a689e-96b6-4076-92a0-b9b765eb09ca" } ``` ``` Simple sign request: a9159d31-d2fb-4e88-9306-02c00de013d1 Status: created Signers: 2 final_copy_reader: sender@example.com signer: signer@example.com embed_url: https://app.box.com/sign/document/... iframeable_embed_url: https://app.box.com/embed/sign/document/... Prepare url: None ``` Notice the `embed_url` and `iframeable_embed_url` in the response. Now when we browse to the embed URL, you see the signature interface: Once finished the signer will receive a copy of the signed document via their email. ## Multiple in person signers As long as the signer is flagged as `is_in_person`, the signing interface cycles through all the signers in the request. For example, if you add a second signer to the request: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer Le...Cb' \ --data-raw '{ "template_id": "ee9a689e-96b6-4076-92a0-b9b765eb09ca", "parent_folder": { "id": "234102987614", "type": "folder" }, "signers": [ { "email": "signer_a@example.com", "role": "signer", "is_in_person": true, "embed_url_external_user_id": "1234" }, { "email": "signer_b@example.com", "role": "signer", "is_in_person": true } ] }' ``` ``` def sign_doc_in_person_multiple( client: Client, document_id: str, destination_folder_id: str, signer_a_email: str, signer_a_embed_url_id: str, signer_b_email: str, ) -> SignRequest: # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) signer_a = SignRequestCreateSigner( email=signer_email, embed_url_external_user_id=signer_embed_url_id, is_in_person=True, ) signer_b = SignRequestCreateSigner( email=signer_email, is_in_person=True, ) # sign document sign_request = client.sign_requests.create_sign_request( signers=[signer_a, signer_b], parent_folder=destination_folder, source_files=[source_file], ) return sign_request def main(): """Simple script to demonstrate how to use the Box SDK""" conf = ConfigOAuth() client = get_client_oauth(conf) # Sign with phone verification sign_with_embed_url = sign_doc_embed_url( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, SIGNER_A_EXTERNAL_ID, SIGNER_B ) check_sign_request(sign_with_embed_url) ``` Results in (simplified): ``` { "signers": [ { "email": "sender@example.com", "role": "final_copy_reader", "is_in_person": false, }, { "email": "signer_a@example.com", "role": "signer", "is_in_person": true, "embed_url": "https://app.box.com/sign/document/...", "iframeable_embed_url": "https://app.box.com/embed/sign/document/..." }, { "email": "signer_b@example.com", "role": "signer", "is_in_person": true, "embed_url": null, "iframeable_embed_url": null } ], "id": "d066575f-f22b-42fc-b9e2-701468776475", "parent_folder": { "id": "234102987614", "type": "folder", "name": "signed docs" }, "name": "Simple-PDF (3).pdf", "type": "sign-request", "status": "created", "template_id": "ee9a689e-96b6-4076-92a0-b9b765eb09ca" } ``` ``` Simple sign request: d066575f-f22b-42fc-b9e2-701468776475 Status: created Signers: 3 final_copy_reader: sender@example.com signer: signer_a@example.com embed_url: https://app.box.com/sign/document/... iframeable_embed_url: https://app.box.com/embed/sign/document/... signer: signer_b@example.com Prepare url: None ``` Browsing to the embedded URL shows the signature interface for the first signer: Once the first signer has signed, the signature interface automatically switches to the second signer: **Reference:** https://developer.box.com/sign/request-options/in-person/ --- ## Untitled *Type: page | Category: Working with Box Sign * Multiple signers and roles Multiple signers What if you have a document that needs to be signed by multiple people? This is typical for… # Multiple signers and roles ## Multiple signers What if you have a document that needs to be signed by multiple people? This is typical for contracts between two or more entities. Having multiple signers introduces another dimension to the Box Sign process, the order in which the signers need to sign the document. If you do not specify the order, the request is sent to everyone at the same time, and when all parties have signed the document, they each receive a copy with all signatures. If you specify the signing order, the signature request is sent to the first signer. Only when the first signer signs the document, the request is sent to the second signer, and so on. Let’s see this working with an example scholarship contract between a university and a student. In this case the institution/teacher must sign the document first. Creating a method specific for this: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ej...3t' \ --data-raw '{ "is_document_preparation_needed": true, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1358047520478", "type": "file" } ], "signers": [ { "email": "institution@example.com", "role": "signer", "order": 1 }, { "email": "student@example.com", "role": "signer", "order": 2 }, ] }' ``` ``` def sign_contract( client: Client, document_id: str, destination_folder_id: str, institution_email: str, student_email: str, prep_needed: bool = False, ) -> SignRequest: """Sign contract""" # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) # signers institution = SignRequestCreateSigner( email=institution_email, role=SignRequestCreateSignerRoleField.SIGNER, order=1, ) student = SignRequestCreateSigner( email=student_email, role=SignRequestCreateSignerRoleField.SIGNER, order=2, ) # create sign request sign_request = client.sign_requests.create_sign_request( signers=[institution, student], parent_folder=destination_folder, source_files=[source_file], is_document_preparation_needed=prep_needed, ) return sign_request def main(): ... # Multiple signers sign_contract_multi = sign_contract( client, CONTRACT, SIGN_DOCS_FOLDER, institution_email=SIGNER_A, student_email=SIGNER_B, prep_needed=True, ) if sign_contract_multi.prepare_url is not None: open_browser(sign_contract_multi.prepare_url) ``` In this particular example the document needs to be prepared, so the browser to the prepare URL opens. Drag the signature pad, the full name and the date to the appropriate places in the document, and click Send Request: Notice you now have two signers, with the order already specified. The `color` is also important to identify which signer is which (in this case the institution is blue and the student is green), determining which signature pad, name and date belongs to which signer. If you look at the signature request details, you should see something like this: Indicating that the first request was sent, but the second is waiting for the first to be completed. Go ahead and complete the signature process for both signers. Notice that when you get the second request it is already signed by the first signer. ## Roles So far we have been working with the `signer` role. However there are other roles that you can use to customize the signature process. The available roles are, `signer`, `approver`, and `final copy reader` From a developer perspective, this means: **Signer**: Any person who is allowed to add data to the document. This includes adding a signature, initials, date, but also filling out text fields, check boxes, and radio buttons, even if it does not include a signature. **Approver**: This role will be asked if they approve the signature request. This approval happens before the preparation step, if enabled, and before the request is sent to any of the signers. This role is useful if you need to get approval from someone before sending the document to the signers. **Final copy reader**: This role does not interact with the signature process, but will receive a copy of the signed document. Let's use roles to be a bit more creative in the scholarship example. Imagine that the scholarship needs to be approved by the dean, and the legal department receives a final copy of the contract. The flow starts with the signature request, flowed by the dean approval, the institution signature, the student signature, and finally the legal department receives a copy of the signed document: Let's create a method for this: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ej...3t' \ --data-raw '{ "is_document_preparation_needed": true, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1358047520478", "type": "file" } ], "signers": [ { "email": "institution@example.com", "role": "signer", "order": 1 }, { "email": "student@example.com", "role": "signer", "order": 2 }, { "email": "dean@example.com", "role": "approver" }, { "email": "legal@example.com", "role": "final_copy_reader" } ] }' ``` ``` def sign_contract_step( client: Client, document_id: str, destination_folder_id: str, institution_email: str, student_email: str, dean_email: str, legal_email: str, ) -> SignRequest: """Sign contract""" # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) # signers institution = SignRequestCreateSigner( email=institution_email, role=SignRequestCreateSignerRoleField.SIGNER, order=1, ) student = SignRequestCreateSigner( email=student_email, role=SignRequestCreateSignerRoleField.SIGNER, order=2, ) dean = SignRequestCreateSigner( email=dean_email, role=SignRequestCreateSignerRoleField.APPROVER, ) legal = SignRequestCreateSigner( email=legal_email, role=SignRequestCreateSignerRoleField.FINAL_COPY_READER, ) # create sign request sign_request = client.sign_requests.create_sign_request( signers=[institution, student, dean, legal], parent_folder=destination_folder, source_files=[source_file], is_document_preparation_needed=True, ) return sign_request def main(): ... # Multiple signers and steps sign_contract_multi_step = sign_contract_step( client, CONTRACT, SIGN_DOCS_FOLDER, institution_email=SIGNER_A, student_email=SIGNER_B, dean_email=APPROVER, legal_email=FINAL_COPY, ) if sign_contract_multi_step.prepare_url is not None: open_browser(sign_contract_multi_step.prepare_url) ``` Like before you need to prepare the document, so open the prepare URL in your browser. Notice in the example the institution is represented by blue on the left, and the student by green on the right, and both are signers. Neither the `approver` nor the `final copy reader` can have inputs associated with them. If you do this, their roles will be adjusted to `signer`: Continuing the signature process: - The dean approves the scholarship - The institution signs the scholarship - The student signs the scholarship - The legal department receives a copy of the signed document. **Reference:** https://developer.box.com/sign/request-options/multiple-signers/ --- ## Untitled *Type: page | Category: Working with Box Sign * Resend requests What if the signer did not receive the email, the email was lost, or the signer deleted the email by mistake? You can resend… # Resend requests What if the signer did not receive the email, the email was lost, or the signer deleted the email by mistake? You can resend the signature request email to the `signer` , either manually or you can turn on the automatic resend option. ## Manual resend To manually resend the signature request email to the signer, call the `resend_sign_request` method on the `sign_requests` object. You can only do it once every 10 minutes. Here is an example: ``` curl --location --request POST 'https://api.box.com/2.0/sign_requests/ 52f6f86c-c0b3-401e-a4ec-1709f277c469/resend' \ --header 'Authorization: Bearer ej...3t' ``` ``` def sign_send_reminder(client: Client, sign_request_id: str): """Send reminder to signers""" sign_request = client.sign_requests.resend_sign_request(sign_request_id) return sign_request ``` ## Automatic resend The automatic resend option sends a reminder email to signers that have not signed the document yet, after 3, 8, 13, and 18 days. To enable automatic resend set the `are_reminders_enabled` parameter to `true`. For example: ``` curl --location 'https://api.box.com/2.0/sign_requests' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer <access token>' \ --data-raw '{ "are_reminders_enabled": true, "parent_folder": { "id": "234102987614", "type": "folder" }, "source_files": [ { "id": "1355143830404", "type": "file" } ], "signers": [ { "email": "signer@example.com", "role": "signer" } ] }' ``` ``` def sign_doc_single_more_options( client: Client, document_id: str, destination_folder_id: str, signer_email: str, prep_needed: bool = False, auto_reminder: bool = False, ) -> SignRequest: """Single doc sign by single signer""" # Sign request params source_file = FileBase(id=document_id, type=FileBaseTypeField.FILE) destination_folder = FolderMini( id=destination_folder_id, type=FolderBaseTypeField.FOLDER ) # signer signer = SignRequestCreateSigner(signer_email) # sign document sign_request = client.sign_requests.create_sign_request( signers=[signer], parent_folder=destination_folder, source_files=[source_file], is_document_preparation_needed=prep_needed, are_reminders_enabled=auto_reminder, ) return sign_request def main(): ... # Sign with redirects sign_with_auto_reminder = sign_doc_single_more_options( client, SIMPLE_PDF, SIGN_DOCS_FOLDER, SIGNER_A, prep_needed=False, auto_reminder = True, ) ``` **Reference:** https://developer.box.com/sign/request-options/resend-requests/ --- ## Untitled *Type: page | Category: Working with Box Sign * Sign webhooks Sign webhooks allow you to receive notifications about events that happen with Box Sign signature requests. You can use them… # Sign webhooks Sign webhooks allow you to receive notifications about events that happen with Box Sign signature requests. You can use them to trigger actions in your own application, or to notify your users about events that happen in Box Sign. This is particularly important since the signature requests are asynchronous, and the signers can interact with them at any time, possibly outside of your application. ## Sign related events There are Box Sign-related events that can trigger the webhooks. Like most of Box events the listeners are set at the folder or document level. The most common use case is to listen to the events at the folder where the signature requests are created. This way you can listen to all the signature requests created in that folder. Some examples of events that can be listened to are: - `SIGN_REQUEST.COMPLETED`, when a signature request is completed. - `SIGN_REQUEST.DECLINED`, when a signature request is declined. - `SIGN_REQUEST.EXPIRED`, when a signature request expires. - `SIGN_REQUEST.SIGNER_EMAIL_BOUNCED`, when a signer's email is bounced. - `SIGN_REQUEST.SIGNER_SIGNED`, when the signature request is signed. - `SIGN_REQUEST.SIGNATURE_REQUESTED`, when the signature is requested from the signer. - `SIGN_REQUEST.ERROR_FINALIZING`, when the signature request could not be processed. **Reference:** https://developer.box.com/sign/webhooks/ --- ## Untitled *Type: page* Documentation High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available… # Documentation ## High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available by topic: - [Authentication](https://developer.box.com/d428a57bd4889ec8d15c393c4114f1d7/authentication.md) - [Client](https://developer.box.com/143730815748e8d3be0de65a363b9f8b/client.md) - [Classifications](https://developer.box.com/f1bf41dc1b0fa806f014f8c5ef66398f/classifications.md) - [Collaborations](https://developer.box.com/a8deacbf7c7aec0bf5d2517167dfecc6/collaborations.md) - [Collaboration Allowlist](https://developer.box.com/2bbe0b98b335c979acdd08be3d43d01d/collaboration-allowlist.md) - [Collections](https://developer.box.com/e25161cb12e3320d1ab928f547797536/collections.md) - [Comments](https://developer.box.com/110e688c968175285555001234bea4a1/comments.md) - [Device Pins](https://developer.box.com/a4977220196aa51be31dad6990f4ae60/device-pins.md) - [Enterprise](https://developer.box.com/0a1036051f4ab42add3e8ef488c65a7f/enterprise.md) - [Events](https://developer.box.com/9da434c92a42385439c07666754720bb/events.md) - [Files](https://developer.box.com/e37f8e07a0bbd3ad10865b2ab07fa4b5/files.md) - [File Requests](https://developer.box.com/44e15a1734d3dd965d5774c18f6ec359/file_requests.md) - [Folders](https://developer.box.com/cd22d73c970edf75b3964c50a3003bef/folders.md) - [Groups](https://developer.box.com/80a71872d2ae5176890767a525c6a5f5/groups.md) - [Information Barrier Reports](https://developer.box.com/6d14a2360a53849697dbdedf4e39bf9f/information-barrier-reports.md) - [Information Barrier Segment Members](https://developer.box.com/84ed112835c93ff408943ba34868b730/information-barrier-segment-members.md) - [Information Barrier Segment Restrictions](https://developer.box.com/de07196d0920c283a27c06e9453c3444/information-barrier-segment-restrictions.md) - [Information Barrier Segments](https://developer.box.com/c8e42c03df1b5f368b74b4bbd89518a5/information-barrier-segments.md) - [Information Barriers](https://developer.box.com/a9f6c7490eb1e535308567b42c7a2bd2/information-barriers.md) - [Integration Mappings](https://developer.box.com/762a2604c694072de7128e07c0d2da3e/integration-mappings.md) - [Legal Hold Policies](https://developer.box.com/f6f9f00b76b159cd8a4615a55416f8de/legal-hold-policies.md) - [Metadata](https://developer.box.com/11257628e7a6027222a06363c4d3b2a2/metadata.md) - [Recent Items](https://developer.box.com/4d81cc8152b9a29d4fa3be3b89640b0c/recent-items.md) - [Retention Policies](https://developer.box.com/5a3d805495d4cc495cbe519f249b98bc/retention-policies.md) - [Search](https://developer.box.com/283a3b0a03bb048565dd7d2d4e35f6e1/search.md) - [Shared Items](https://developer.box.com/133dd18558863edd0de21f2f1ac4931a/shared-items.md) - [Sign Requests](https://developer.box.com/48757b9e5a5f08e38fe3d1ea75213815/sign-requests.md) - [Sign Templates](https://developer.box.com/8eb7b125724b23302549c217b7afe0a8/sign-templates.md) - [Storage Policies](https://developer.box.com/127ef6eef52e4e56f73da7cb35736016/storage-policies.md) - [Tasks](https://developer.box.com/fb582628bcdf34bacd84485ad8b1720b/tasks.md) - [Terms of Service](https://developer.box.com/932f3810fb86d1a28be4edb39d4c82da/terms-of-service.md) - [Trash](https://developer.box.com/a103079767ff771d1548093312b2b9fc/trash.md) - [Users](https://developer.box.com/4518ab9f39785de366b4be251298c810/users.md) - [Watermarking](https://developer.box.com/a73c217b233a91b80963baed59afb8a0/watermarking.md) - [Web Links](https://developer.box.com/6480363d7eaf8fd9dd2a51782e2a2c5b/web-links.md) - [Webhooks](https://developer.box.com/6efbed44c155682758bada5b9d5a8af5/webhooks.md) ## JSDocs In-depth documentation of available functions is also available via autogenerated [JSDocs](https://rawgit.com/box/box-node-sdk/main/docs/jsdoc/index.html). --- ## Untitled *Type: page* Authentication The Box API uses OAuth2 for authentication, which can be difficult to implement. The SDK makes it easier by providing classes… # Authentication The Box API uses OAuth2 for authentication, which can be difficult to implement. The SDK makes it easier by providing classes that handle obtaining tokens and automatically refreshing them when possible. See the [OAuth 2 overview](https://developer.box.com/en/guides/authentication/) for a detailed overview of how the Box API handles authentication. [Ways to Authenticate](#ways-to-authenticate) - [Developer Token](#developer-token) - [Server Auth with JWT](#server-auth-with-jwt) [Traditional 3-Legged OAuth2](#traditional-3-legged-oauth2) - [Token Store](#token-store) [Box View Authentication with App Tokens](#box-view-authentication-with-app-tokens) [Client Credentials Grant Authentication](#client-credentials-grant-authentication) [As-User](#as-user) [Proxy Support](#proxy-support) [Token Exchange](#token-exchange) - [Annotator Tokens](#annotator-tokens) [Revoking Tokens](#revoking-tokens) ## Ways to Authenticate ### Developer Token The fastest way to get started using the API is with developer tokens. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. The following example creates an API client with a developer token: ``` var BoxSDK = require('box-node-sdk'); var sdk = new BoxSDK({ clientID: 'YOUR-CLIENT-ID', clientSecret: 'YOUR-CLIENT_SECRET' }); var client = sdk.getBasicClient('YOUR-DEVELOPER-TOKEN'); ``` ### Server Auth with JWT Server auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/en/guides/authentication/user-types/app-users/#service-accounts) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. If you generated your public and private keys automatically through the [Box Developer Console](https://app.box.com/developers/console), you can use the JSON file created there to configure your SDK instance and create a client to make calls as the Service Account: ``` var BoxSDK = require('box-node-sdk'); var jsonConfig = require('/path/to/config.json'); var sdk = BoxSDK.getPreconfiguredInstance(jsonConfig); var serviceAccountClient = sdk.getAppAuthClient('enterprise'); ``` Otherwise, you'll need to provide the necessary configuration fields directly to the SDK constructor: ``` var BoxSDK = require('box-node-sdk'); var sdk = new BoxSDK({ clientID: 'YOUR-CLIENT-ID', clientSecret: 'YOUR-CLIENT_SECRET', appAuth: { keyID: 'YOUR-KEY-ID', privateKey: 'YOUR-PRIVATE_KEY', passphrase: 'YOUR-PRIVATE-KEY-PASSPHRASE' } }); var serviceAccountClient = sdk.getAppAuthClient('enterprise', 'YOUR-ENTERPRISE-ID'); ``` App auth applications also often have associated App Users, which are [created and managed directly by the application](https://developer.box.com/en/guides/authentication/user-types/app-users/) — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user or managed user to make calls as that user. See the [API documentation](https://developer.box.com/) and [sample app](https://github.com/box/box-node-sdk/blob/main/examples/app-auth) for detailed instructions on how to use app auth. Clients for making calls as an App User or Managed User can be created with the same SDK instance as in the above examples, similarly to creating a Service Account client: ``` var appUserClient = sdk.getAppAuthClient('user', 'YOUR-APP-USER-ID'); ``` ### Traditional 3-Legged OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/en/guides/authentication/oauth2/). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code. ``` var BoxSDK = require('box-node-sdk'); var sdk = new BoxSDK({ clientID: 'YOUR-CLIENT-ID', clientSecret: 'YOUR-CLIENT_SECRET' }); // the URL to redirect the user to var authorize_url = sdk.getAuthorizeURL({ response_type: 'code' }); ``` After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirect_uri` which will contain an auth code. This auth code can then be used along with your client ID and client secret to establish an API connection. A `PersistentClient` will automatically refresh the access token as needed. ``` var BoxSDK = require('box-node-sdk'); var sdk = new BoxSDK({ clientID: 'YOUR-CLIENT-ID', clientSecret: 'unused' }); var client = sdk.getBasicClient('YOUR-APP-TOKEN'); ``` ### Client Credentials Grant Authentication Allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service (anonymous) or user account. #### Obtaining Service Account token The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account, you will have to provide enterprise ID with client ID and secret: ``` const BoxSDK = require('box-node-sdk'); const sdkConfig = { boxAppSettings: { clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET" }, enterpriseID: "ENTERPRISE_ID" } const sdk = BoxSDK.getPreconfiguredInstance(sdkConfig) const client = sdk.getAnonymousClient(); ``` #### Obtaining User token To obtain user account you will have to provide user ID with client ID and secret. ``` const BoxSDK = require('box-node-sdk'); const sdkConfig = { boxAppSettings: { clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET" }, enterpriseID: "ENTERPRISE_ID" //The enterprise id in this case is optional and can be ommited. } const sdk = BoxSDK.getPreconfiguredInstance(sdkConfig) const client = sdk.getCCGClientForUser("USER_ID"); ``` ## As-User The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an `As-User: USER-ID` header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). The following examples assume that the `client` has been instantiated with an access token belonging to an admin-level user or Service Account with appropriate privileges to make As-User calls. The `asUser(userID)` method sets up the client to impersonate a given user. All calls made with this instance of client will be made in context of the impersonated user. ``` client.asUser('USER-ID'); client.folders.getItems('0') .then(items => { // items contains the collection of files and folders // in the root folder of the user with USER-ID }); ``` The `asSelf()` method removes the As-User header and returns the client to making calls as the admin user or Service Account it was initialized as. ``` client.asSelf(); ``` ## Token Exchange You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). This is useful if you want to use the [Box UI Kits](https://developer.box.com/en/guides/embed/ui-elements/), since they generally do not need full read/write permissions to run. To exchange the token held by a client for a new token with only `item_preview` scope, restricted to a single file, suitable for the [Content Preview UI Kit](https://developer.box.com/en/guides/embed/ui-elements/preview/): ``` client.exchangeToken('item_preview', 'https://api.box.com/2.0/files/123456789') .then(tokenInfo => { // tokenInfo.accessToken contains the new downscoped access token }); ``` To exchange the client's token for one with scopes to upload and delete items, but not to view their contents, which would be suitable for an less-trusted server-side process; ``` client.exchangeToken(['item_upload', 'item_delete']) .then(tokenInfo => { // tokenInfo.accessToken contains the new downscoped access token }); ``` #### Annotator Tokens To generate an annotator token for use with [Box View annotations](https://developer.box.com/en/guides/embed/ui-elements/annotations/), pass the `actor` options to the token exchange method: ``` var options = { actor: { id: 'EXTERNAL_IDENTIFIER', name: 'Jane Doe' } }; client.exchangeToken('item_preview', 'https://api.box.com/2.0/files/123456', options) .then(tokenInfo => { // tokenInfo.accessToken contains the new annotator token }); ``` This will attach an external user name and ID to annotations made with the token, in order to attribute them to someone who does not have a Box account. ## Revoking tokens Access tokens for a client can be revoked when needed. As this removes the client's way of authenticating this client can no longer be used after this call. ``` client.revokeTokens("<TOKEN>") .then(() => { // the client's access token have been revoked }); ``` --- ## Untitled *Type: page* Classifications Classfications are a type of metadata that allows users and applications to define and assign a content classification to… # Classifications Classfications are a type of metadata that allows users and applications to define and assign a content classification to files and folders. Classifications use the metadata APIs to add and remove classifications, and assign them to files. For more details on metadata templates please see the [metadata documentation](https://developer.box.com/11257628e7a6027222a06363c4d3b2a2/metadata.md). [Classifications](#classifications) - [Add initial classifications](#add-initial-classifications) - [List all classifications](#list-all-classifications) - [Add another classification](#add-another-classification) - [Update a classification](#update-a-classification) - [Delete a classification](#delete-a-classification) - [Delete all classifications](#delete-all-classifications) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Get classification on file](#get-classification-on-file) - [Remove classification from file](#remove-classification-from-file) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Get classification on folder](#get-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Add initial classifications If an enterprise does not already have a classification defined, the first classification(s) can be added with the [`metadata.createTemplate(templateName, fields, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#createTemplate) method. ``` client.metadata.createTemplate( 'Classification', [ { type: "enum", key: "Box__Security__Classification__Key", displayName: "Classification", hidden: false, options: [ { key: "Classified", staticConfig: { classification: { colorID: 7, classificationDefinition: "Top Seret" } } } ] } ], { hidden: false, templateKey: 'securityClassification-6VMVochwUWo' } ) .then(template => { // the new classification template }); ``` ## List all classifications To retrieve a list of all the classifications in an enterprise call the [`metadata.getTemplateSchema(scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#getTemplateSchema) method to get the classifciations template, which will contain a list of all the classifications ``` client.metadata.getTemplateSchema('enterprise', 'securityClassification-6VMVochwUWo') .then(template => { // the classification template }); ``` ## Add another classification To add another classification, call the [`metadata.updateTemplate(scope, template, operations, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#updateTemplate) method with the an operation to add a new classification to the template. ``` var operations = [{ op: "addEnumOption", fieldKey: "Box__Security__Classification__Key", data: { key: "Sensitive", classification: { classificationDefinition: "Sensitive information that must not be shared.", colorID: 4 } } }]; client.metadata.updateTemplate('enterprise', 'securityClassification-6VMVochwUWo', operations) .then(template => { // the updated classification template }); ``` ## Update a classification To update an existing classification, call the [`metadata.updateTemplate(scope, template, operations, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#updateTemplate) method with the an operation to update the existing classification already present on the template. ``` var operations = [{ op: "editEnumOption", fieldKey: "Box__Security__Classification__Key", enumOptionKey: "Sensitive", data: { key: "Very Sensitive", classification: { classificationDefinition: "Sensitive information that must not be shared.", colorID: 4 } } }]; client.metadata.updateTemplate('enterprise', 'securityClassification-6VMVochwUWo', operations) .then(template => { // the updated classification template }); ``` ## Add classification to file To add a classification to a file, call [`files.setMetadata(fileID, scope, template, classification, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#setMetadata) with the name of the classification template, as well as the details of the classification to add to the file. ``` var classification = { Box__Security__Classification__Key: "Sensitive" }; client.files.addMetadata('11111', 'enterprise', 'securityClassification-6VMVochwUWo', classification) .then(metadata => { // the classification applied to the file }); ``` ## Update classification on file To update a classification on a file, call [`files.setMetadata(fileID, scope, template, classification, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#updateMetadata) with the name of the classification template, as well as the details of the classification to add to the file. ``` var classification = { Box__Security__Classification__Key: "Sensitive" }; client.files.addMetadata('11111', 'enterprise', 'securityClassification-6VMVochwUWo', classification) .then(metadata => { // the updated classification applied to the file }); ``` ## Get classification on file Retrieve the classification on a file by calling [`files.getMetadata(fileID, scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getMetadata) with the ID of the file. ``` client.files.getMetadata('11111', 'enterprise', 'securityClassification-6VMVochwUWo') .then(metadata => { // the metadata instance, which includes the applied metadata }); ``` ## Remove classification from file A classification can be removed from a file by calling [`files.deleteMetadata(fileID, scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#deleteMetadata). ``` client.files.deleteMetadata('11111', 'enterprise', 'securityClassification-6VMVochwUWo') .then(() => { // removal succeeded — no value returned });; ``` ## Add classification to folder To add a classification to a folder, call [`folders.setMetadata(folderID, scope, template, classification, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#setMetadata) with the name of the classification template, as well as the details of the classification to add to the folder. ``` var classification = { Box__Security__Classification__Key: "Sensitive" }; client.folders.addMetadata('11111', 'enterprise', 'securityClassification-6VMVochwUWo', classification) .then(metadata => { // the classification applied to the folder }); ``` ## Update classification on folder To update a classification on a folder, call [`folders.setMetadata(folderID, scope, template, classification, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#updateMetadata) with the name of the classification template, as well as the details of the classification to add to the folder. ``` var classification = { Box__Security__Classification__Key: "Sensitive" }; client.folders.addMetadata('11111', 'enterprise', 'securityClassification-6VMVochwUWo', classification) .then(metadata => { // the updated classification applied to the folder }); ``` ## Get classification on folder Retrieve the classification on a folder by calling [`folders.getMetadata(folderID, scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#getMetadata) with the ID of the folder. ``` client.folders.getMetadata('11111', 'enterprise', 'securityClassification-6VMVochwUWo') .then(metadata => { // the metadata instance, which includes the applied metadata }); ``` ## Remove classification from folder A classification can be removed from a folder by calling [`folders.deleteMetadata(folderID, scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#deleteMetadata). ``` client.folders.deleteMetadata('11111', 'enterprise', 'securityClassification-6VMVochwUWo') .then(() => { // removal succeeded — no value returned });; ``` --- ## Untitled *Type: page* Client The client object is the primary interface for making API calls through the SDK. It automatically manages API access token upkeep… # Client The client object is the primary interface for making API calls through the SDK. It automatically manages API access token upkeep when possible, and has a number of options for altering the way calls are made. The various ways of creating an authenticated client are described in the [Authentication documentation](https://developer.box.com/d428a57bd4889ec8d15c393c4114f1d7/authentication.md). [Custom API Calls](#custom-api-calls) - [GET](#get) - [POST](#post) - [PUT](#put) - [DELETE](#delete) - [OPTIONS](#options) ## Custom API Calls The client allows users to make API calls to any arbitrary API endpoint or URL, in order to provide flexibility for developers who may want to make calls not directly supported by the convenience methods provided by the managers (e.g. `client.folders.get()`). These API calls will be sent with the client's access token and any other client settings, but requires passing in the URL, full request parameters, and handling the full response manually. The URL argument for custom calls can be either an API endpoint path (e.g. `'/files/1234'`) or a full URL (e.g. `'https://api.box.com/2.0/files/1234'`). The `params` object contains [request parameters](https://github.com/request/request#requestoptions-callback) and is often useful for passing query string, request body, or header parameters. The response object that results from the call is an instance of [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage). By default the entire response will have already been read and the body will be attached as `response.body`. ### GET To make a GET call, call the [`client.get(url, params, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/BoxClient.html#get) method with the URL of the endpoint and the request params. ``` var params = { qs: { fields: 'name,id' } }; client.get('/files/1234', params, function(err, response) { if (err) { // handle error } console.log(response.body); }); ``` ### POST To make a POST call, call the [`client.post(url, params, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/BoxClient.html#post) method with the URL of the endpoint and the request params. ``` var params = { body: { name: 'My New Folder', parent: { id: '0' } } }; client.post('/folders', params, function(err, response) { if (err) { // handle error } console.log(response.body); }); ``` ### PUT To make a PUT call, call the [`client.put(url, params, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/BoxClient.html#put) method with the URL of the endpoint and the request params. ``` var params = { body: { name: 'Changed Folder Name' } }; client.put('/folders/1234', params, function(err, response) { if (err) { // handle error } console.log(response.body); }); ``` ### DELETE To make a DELETE call, call the [`client.del(url, params, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/BoxClient.html#del) method with the URL of the endpoint and the request params. ``` client.del('/folders/1234', null, function(err, response) { if (err) { // handle error } console.log(response.body); }); ``` ### OPTIONS To make an OPTIONS call, call the [`client.options(url, params, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/BoxClient.html#options) method with the URL of the endpoint and the request params. ``` client.options('/files/content', null, function(err, response) { if (err) { // handle error } console.log(response.body); }); ``` --- ## Untitled *Type: page* Collections Collections are used to store a custom user-defined set of items that may not all be in the same folder. Currently, the only… # Collections Collections are used to store a custom user-defined set of items that may not all be in the same folder. Currently, the only collection available is the `favorites` collection ([source](https://box.dev/reference/resources/collection/)). - [Get a User's Collections](#get-a-users-collections) - [Get the Items in a Collection](#get-the-items-in-a-collection) - [Add File to a Collection](#add-file-to-a-collection) - [Remove File from a Collection](#remove-file-from-a-collection) - [Add Folder to a Collection](#add-folder-to-a-collection) - [Remove Folder from a Collection](#remove-folder-from-a-collection) - [Add Web Link to a Collection](#add-web-link-to-a-collection) - [Remove Web Link from a Collection](#remove-web-link-from-a-collection) ## Get a User's Collections Get a list of all collections the user has defined by calling [`collections.getAll(callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collections.html#getAll). A user always has a default collection called "Favorites" which they can add items to. ``` client.collections.getAll() .then(collections => { /* collections -> { total_count: 1, entries: [ { type: 'collection', id: '11111', name: 'Favorites', collection_type: 'favorites' } ], limit: 100, offset: 0 } */ }); ``` ## Get the Items in a Collection Get a list of the items in a collection by passing the ID of the collection to [`collections.getItems(collectionID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collections.html#getItems). ``` client.collections.getItems('81934', {fields: 'name', limit: 2}) .then(items => { /* items -> { total_count: 24, entries: [ { type: 'folder', id: '192429928', sequence_id: '1', etag: '1', name: 'Stephen Curry Three Pointers' }, { type: 'file', id: '818853862', sequence_id: '0', etag: '0', name: 'Warriors.jpg' } ], offset: 0, limit: 2 } */ }); ``` ## Add File to a Collection To add a file to a collection, call the [`files.addToCollection(fileID, collectionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#addToCollection) method with the IDs of the file and collection. ``` client.files.addToCollection('87263', '235747', callback); ``` ## Remove File from a Collection To remove a file from a collection, call the [`files.removeFromCollection(fileID, collectionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#removeFromCollection) method with the IDs of the file and collection. ``` client.files.removeFromCollection('87263', '235747', callback); ``` ## Add Folder to a Collection To add a folder to a collection, call the [`folders.addToCollection(folderID, collectionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#addToCollection) method with the IDs of the folder and collection. ``` client.folders.addToCollection('87263', '235747', callback); ``` ## Remove Folder from a Collection To remove a folder from a collection, call the [`folders.removeFromCollection(folderID, collectionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#removeFromCollection) method with the IDs of the folder and collection. ``` client.folders.removeFromCollection('87263', '235747', callback); ``` ## Add Web Link to a Collection To add a web link to a collection, call the [`weblinks.addToCollection(webLinkID, collectionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/WebLinks.html#addToCollection) method with the IDs of the web link and collection. ``` client.weblinks.addToCollection('87263', '235747', callback); ``` ## Remove Web Link from a Collection To remove a web link from a collection, call the [`weblinks.removeFromCollection(webLinkID, collectionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/WebLinks.html#removeFromCollection) method with the IDs of the web link and collection. ``` client.weblinks.removeFromCollection('87263', '235747', callback); ``` --- ## Untitled *Type: page* Collaborations Collaborations are used to share folders and files between users or groups. They also define what permissions a user has for… # Collaborations Collaborations are used to share folders and files between users or groups. They also define what permissions a user has for a folder or file. - [Add a Collaboration](#add-a-collaboration) - [Edit a Collaboration](#edit-a-collaboration) - [Remove a Collaboration](#remove-a-collaboration) - [Get a Collaboration's Information](#get-a-collaborations-information) - [Get the Collaborations on a Folder](#get-the-collaborations-on-a-folder) - [Get the Collaborations on a File](#get-the-collaborations-on-a-file) - [Get Pending Collaborations](#get-pending-collaborations) - [Respond to Pending Collaborations](#respond-to-pending-collaborations) ## Add a Collaboration A collaboration can be added for an existing user with [`collaborations.createWithUserID(userID, itemID, role, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#createWithUserID). The `role` parameter determines what permissions the collaborator will have on the folder. You can create a collaboration on a file by setting the `type` option to `'file'`. ``` // Invite user 123456 to collaborate on folder 987654 client.collaborations.createWithUserID('123456', '987654', client.collaborationRoles.EDITOR) .then(collaboration => { /* collaboration -> { type: 'collaboration', id: '11111', created_by: { type: 'user', id: '22222', name: 'Inviting User', login: 'inviter@example.com' }, created_at: '2016-11-16T21:33:31-08:00', modified_at: '2016-11-16T21:33:31-08:00', expires_at: null, status: 'accepted', accessible_by: { type: 'user', id: '123456', name: 'Collaborator User', login: 'collaborator@example.com' }, role: 'editor', acknowledged_at: '2016-11-16T21:33:31-08:00', item: { type: 'folder', id: '987654', sequence_id: '0', etag: '0', name: 'Collaborated Folder' } } */ }); ``` ``` // Invite user 123456 to collaborate on file 987654 var options = { type: client.itemTypes.FILE }; client.collaborations.createWithUserID('123456', '987654', client.collaborationRoles.EDITOR, options) .then(collaboration => { /* collaboration -> { type: 'collaboration', id: '11111', created_by: { type: 'user', id: '22222', name: 'Inviting User', login: 'inviter@example.com' }, created_at: '2016-11-16T21:33:31-08:00', modified_at: '2016-11-16T21:33:31-08:00', expires_at: null, status: 'accepted', accessible_by: { type: 'user', id: '123456', name: 'Collaborator User', login: 'collaborator@example.com' }, role: 'editor', acknowledged_at: '2016-11-16T21:33:31-08:00', item: { type: 'file', id: '987654', sequence_id: '0', etag: '0', name: 'Collaborated File' } } */ }); ``` You can also add a collaboration by providing an email address with [`collaborations.createWithUserEmail(email, itemID, role, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#createWithUserEmail). If the recipient doesn't have a Box account, they will be asked create one. ``` client.collaborations.createWithUserEmail('collaborator@example.com', '987654', client.collaborationRoles.VIEWER) .then(collaboration => { /* collaboration -> { type: 'collaboration', id: '11111', created_by: { type: 'user', id: '22222', name: 'Inviting User', login: 'inviter@example.com' }, created_at: '2016-11-16T21:33:31-08:00', modified_at: '2016-11-16T21:33:31-08:00', expires_at: null, status: 'accepted', accessible_by: { type: 'user', id: '33333', name: 'Collaborator User', login: 'collaborator@example.com' }, role: 'viewer', acknowledged_at: '2016-11-16T21:33:31-08:00', item: { type: 'folder', id: '987654', sequence_id: '0', etag: '0', name: 'Collaborated Folder' } } */ ``` Groups can also be added as collaborators by providing the group ID to [`collaborations.createWithGroupID(groupID, itemID, role, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#createWithGroupID). All members of the group will receive the same role and permissions. ``` client.collaborations.createWithGroupID('56473', '987654', client.collaborationRoles.UPLOADER) .then(collaboration => { /* collaboration -> { type: 'collaboration', id: '11111', created_by: null, created_at: '2016-11-16T21:48:44-08:00', modified_at: '2016-11-16T21:48:44-08:00', expires_at: null, status: 'accepted', accessible_by: { type: 'group', id: '56473', name: 'My Group' }, role: 'uploader', acknowledged_at: '2016-11-16T21:48:44-08:00', item: { type: 'folder', id: '987654', sequence_id: '0', etag: '0', name: 'Collaborated Folder' } } */ }); ``` ## Edit a Collaboration A collaboration can be edited by calling [`collaborations.update(collaborationID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#update) with the fields to be updated. For example, to change the role of a collaboration: ``` client.collaborations.update('11111', {role: client.collaborationRoles.PREVIEWER}) .then(collaboration => { /* collaboration -> { type: 'collaboration', id: '11111', created_by: { type: 'user', id: '22222', name: 'Inviting User', login: 'inviter@example.com' }, created_at: '2015-11-03T18:36:37-08:00', modified_at: '2016-11-16T21:01:19-08:00', expires_at: null, status: 'accepted', accessible_by: { type: 'user', id: '33333', name: 'Collaborated User', login: 'collaborator@example.com' }, role: 'previewer', acknowledged_at: '2015-11-03T18:36:37-08:00', item: { type: 'folder', id: '44444', sequence_id: '1', etag: '1', name: 'Collaborated Folder' } } */ }); ``` ## Remove a Collaboration A collaboration can be removed by calling [`collaborations.delete(collaborationID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#delete). ``` client.collaborations.delete('56473') .then(() => { // removal succeeded — no value provided }); ``` ## Get a Collaboration's Information Calling [`collaborations.get(collaborationID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#get) on a collaboration returns a snapshot of the collaboration's info. ``` var collaborationID = '22222'; client.collaborations.get(collaborationID) .then(collaboration => { /* collaboration -> { type: 'collaboration', id: '22222', created_by: { type: 'user', id: '11111', name: 'Example User', login: 'user@example.com' }, created_at: '2012-12-12T10:54:37-08:00', modified_at: '2012-12-12T11:30:43-08:00', expires_at: null, status: 'accepted', accessible_by: { type: 'user', id: '33333',, name: 'Collaborator User', login: 'collaborator@example.com' }, role: 'editor', acknowledged_at: '2012-12-12T11:30:43-08:00', item: { type: 'folder', id: '12345', sequence_id: '0', etag: '0', name: 'Shared Pictures' } } */ }); ``` ## Get the Collaborations on a Folder You can get all of the collaborations on a folder by calling [`folders.getCollaborations(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#getCollaborations) on the folder. ``` var folderID = '12345'; client.folders.getCollaborations(folderID) .then(collaborations => { /* collaborations -> { total_count: 1, entries: [ { type: 'collaboration', id: '11111', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2011-11-29T12:56:35-08:00', modified_at: '2012-09-11T15:12:32-07:00', expires_at: null, status: 'accepted', accessible_by: { type: 'user', id: '33333', name: 'Collaborator User', login: 'collaborator@example.com' }, role: 'editor', acknowledged_at: '2011-11-29T12:59:40-08:00', item: null } ] } */ }); ``` ## Get the Collaborations on a File You can get the collection of collaborations on a file by calling [`files.getCollaborations(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getCollaborations) with the ID of the file. ``` var fileID = '98765'; client.files.getCollaborations(fileID) .then(collaborations => { /* collaborations -> { total_count: 1, entries: [ { type: 'collaboration', id: '11111', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2011-11-29T12:56:35-08:00', modified_at: '2012-09-11T15:12:32-07:00', expires_at: null, status: 'accepted', accessible_by: { type: 'user', id: '33333', name: 'Collaborator User', login: 'collaborator@example.com' }, role: 'editor', acknowledged_at: '2011-11-29T12:59:40-08:00', item: null } ] } */ }); ``` ## Get Pending Collaborations A collection of all the user's pending collaborations can be retrieved with [`collaborations.getPending(callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#getPending). ``` client.collaborations.getPending() .then(collaborations => { /* collaborations -> { total_count: 1, entries: [ { type: 'collaboration', id: '11111', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2011-11-29T12:56:35-08:00', modified_at: '2012-09-11T15:12:32-07:00', expires_at: null, status: 'pending', accessible_by: { type: 'user', id: '33333', name: 'Collaborator User', login: 'collaborator@example.com' }, role: 'editor', acknowledged_at: '2011-11-29T12:59:40-08:00', item: null } ] } */ }); ``` ## Respond to Pending Collaborations You can accept or reject a pending collaboration by calling [`collaborations.respondToPending(collaborationID,newStatus, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#respondToPending) with a status of `'accepted'` or `'rejected'`. ``` var collaborationID = '22222'; client.collaborations.respondToPending(collaborationID, 'accepted') .then(collaboration => { /* collaboration -> { type: 'collaboration', id: '22222', created_by: { type: 'user', id: '11111', name: 'Example User', login: 'user@example.com' }, created_at: '2012-12-12T10:54:37-08:00', modified_at: '2012-12-12T11:30:43-08:00', expires_at: null, status: 'accepted', accessible_by: { type: 'user', id: '33333',, name: 'Collaborator User', login: 'collaborator@example.com' }, role: 'editor', acknowledged_at: '2012-12-12T11:30:43-08:00', item: { type: 'folder', id: '12345', sequence_id: '0', etag: '0', name: 'Shared Pictures' } } */ }); ``` --- ## Untitled *Type: page* AI AI allows to send an intelligence request to supported large language models and returns an answer based on the provided prompt and items… # AI AI allows to send an intelligence request to supported large language models and returns an answer based on the provided prompt and items. [AI](#ai) - [Send AI request](#send-ai-request) - [Send AI text generation request](#send-ai-text-generation-request) - [Get AI agent default configuration](#get-ai-agent-default-configuration) ## Send AI request To send an AI request to the supported large language models, call the [`ai.ask(body, options?, callback?)`](http://opensource.box.com/box-node-sdk/jsdoc/AIManager.html#ask) method with the prompt and items. The `items` parameter is a list of items to be processed by the LLM, often files. The `prompt` provided by the client to be answered by the LLM. The prompt's length is limited to 10000 characters. The `mode` specifies if this request is for a single or multiple items. If you select `single_item_qa` the items array can have one element only. Selecting `multiple_item_qa` allows you to provide up to 25 items. ``` client.ai.ask( { prompt: 'What is the capital of France?', items: [ { type: 'file', id: '12345' } ], mode: 'single_item_qa' }) .then(response => { /* response -> { "answer": "Paris", "created_at": "2021-10-01T00:00:00Z", "completion_reason": "done" } */ }); ``` NOTE: The AI endpoint may return a 412 status code if you use for your request a file which has just been updated to the box. It usually takes a few seconds for the file to be indexed and available for the AI endpoint. ## Send AI text generation request To send an AI text generation request to the supported large language models, call the [`ai.textGen(body, options?, callback?)`](http://opensource.box.com/box-node-sdk/jsdoc/AIManager.html#textGen) method with the prompt, items and dialogue history. The `dialogue_history` parameter is history of prompts and answers previously passed to the LLM. This provides additional context to the LLM in generating the response. The `items` parameter is a list of items to be processed by the LLM, often files. The `prompt` provided by the client to be answered by the LLM. The prompt's length is limited to 10000 characters. ``` client.ai.textGen( { prompt: 'What is the capital of France?', items: [ { type: 'file', id: '12345' } ], dialogue_history: [ { prompt: 'What is the capital of France?', answer: 'Paris', created_at: '2021-10-01T00:00:00Z' }, { prompt: 'What is the capital of Germany?', answer: 'Berlin', created_at: '2021-10-01T00:00:00Z' } ] }) .then(response => { /* response -> { "answer": "The capital of France is Paris.", "created_at": "2021-10-01T00:00:00Z", "completion_reason": "done" } */ }); ``` ## Get AI agent default configuration To get an AI agent default configuration call the [ai.getAiAgentDefaultConfig(options?, callback?)](http://opensource.box.com/box-node-sdk/jsdoc/AIManager.html#getAiAgentDefaultConfig) method. The `mode` parameter filters the agent configuration to be returned. It can be either `ask` or `text_gen`. The `language` parameter specifies the ISO language code to return the agent config for. If the language is not supported, the default agent configuration is returned. The `model` parameter specifies the model for which the default agent configuration should be returned. ``` client.ai.getAiAgentDefaultConfig({ mode: 'ask', language: 'en', model:'openai__gpt_3_5_turbo' }).then(response => { /* response -> { "type": "ai_agent_ask", "basic_text": { "llm_endpoint_params": { "type": "openai_params", "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>", "temperature": 0, "top_p": 1 }, "model": "openai__gpt_3_5_turbo", "num_tokens_for_completion": 8400, "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "system_message": "You are a helpful travel assistant specialized in budget travel" }, ... } */ }); ``` --- ## Untitled *Type: page* Device Pins Device pins allow enterprises to control what devices can use native Box applications. To learn more about device pinning… # Device Pins Device pins allow enterprises to control what devices can use native Box applications. To learn more about device pinning, please see the [Device Pinning documentation](https://community.box.com/t5/For-Admins/Device-Pinning-Overview-And-FAQs/ta-p/172). - [Get Device Pin](#get-device-pin) - [Delete Device Pin](#delete-device-pin) - [Get All Device Pins](#get-all-device-pins) ## Get Device Pin To get information about a specific device pin, call the [`devicePins.get(pinID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/DevicePins.html#get) method with the ID of the device pin. ``` client.devicePins.get('11111') .then(pin => { /* pin -> { type: 'device_pinner', id: '11111', owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, product_name: 'iPad' } */ }); ``` ## Delete Device Pin To remove a specific device pin, call the [`devicePins.delete(pinID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/DevicePins.html#delete) method with the ID of the device pin. ``` client.devicePins.delete('28345') .then(() => { // deletion succeeded — no value returned }); ``` ## Get All Device Pins Get all device pins records for the current enterprise by calling the [`devicePins.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/DevicePins.html#getAll) method. ``` client.devicePins.getAll() .then(pins => { /* pins -> { entries: [ { type: 'device_pinner', id: '11111', owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, product_name: 'iPad' }, { type: 'device_pinner', id: '11112', owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, product_name: 'iPhone' } ], limit: 100, order: [ { by: 'id', direction: 'ASC' } ] } */ }); ``` --- ## Untitled *Type: page* Collaboration Allowlists Collaboration Allowlists are used to determine specific email domains that can collaborate with a Box Enterprise… # Collaboration Allowlists Collaboration Allowlists are used to determine specific email domains that can collaborate with a Box Enterprise. Certain users can be exempted from these restrictions, for example if they are a trusted person who needs to collaborate outside of the normally-allowed set of domains. - [Add a Domain to Collaboration Allowlist](#add-a-domain-to-collaboration-allowlist) - [Get a Allowlisted Domain's Information](#get-a-allowlisted-domains-information) - [Get Allowlisted Domains for an Enterprise](#get-allowlisted-domains-for-an-enterprise) - [Remove a Domain from Collaboration Allowlist](#remove-a-domain-from-collaboration-allowlist) - [Exempt a User from the Collaboration Allowlist](#exempt-a-user-from-the-collaboration-allowlist) - [Get an Exempt User's Information](#get-an-exempt-users-information) - [Get the User Collaboration Allowlists for an Enterprise](#get-the-user-collaboration-allowlists-for-an-enterprise) - [Remove a User Exemption from the Collaboration Allowlist](#remove-a-user-exemption-from-the-collaboration-allowlist) ## Add a Domain to Collaboration Allowlist You can allowlist a certain domain to allow collaboration with that domain for your enterprise by calling [`collaborationAllowlist.addDomain(domain, direction, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#addDomain). The `direction` parameter determines the level of restriction on which way the collaboration flows. Set to `inbound` will allow users outside of our enterprise to collaboration with content inside your enterprise. Set to `outbound` will allow users inside your enterprise to collaboration with content owned by someone outside your enterprise. Set to `both` will allow both `inbound` and `outbound`. ``` client.collaborationAllowlist.addDomain('test.com', client.collaborationAllowlist.directions.INBOUND, callback); ``` ## Get a Allowlisted Domain's Information Information about a specific collaboration allowlist record, which shows the domain that is allowlisted, can be retrieved by calling [`collaborationAllowlist.getAllowlistedDomain(domainID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#getAllowlistedDomain). ``` client.collaborationAllowlist.getAllowlistedDomain('12345', {}, callback); ``` ## Get Allowlisted Domains for an Enterprise You can retrieve a collection of allowlisted domains for an enterprise with [`collaborationAllowlist.getAllAllowlistedDomains(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#getAllAllowlistedDomains). ``` client.collaborationAllowlist.getAllAllowlistedDomains(callback); ``` Alternatively you can limit the number of allowlisted domains you wish to retrieve by setting a limit. The default is 100 entries and the maximum is 1,000 entries. ``` var options = { limit: 50; }; client.collaborationAllowlist.getAllAllowlistedDomains(options, callback); ``` ## Remove a Domain from Collaboration Allowlist You can remove a domain from the collaboration allowlist with [`collaborationAllowlist.removeDomain(domainID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#removeDomain). ``` client.collaborationAllowlist.removeDomain('12345', callback); ``` ## Exempt a User from the Collaboration Allowlist You can make a specific user exempt from the collaboration allowlist, which allows them to collaborate with users from any domain, by calling [`collaborationAllowlist.addExemption(userID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Collaborations.html#addExemption). ``` client.collaborationAllowlist.addExemption('5678', callback); ``` ## Get an Exempt User's Information To retrieve information about a specific user exemption record, you can use [`collaborationAllowlist.getExemption(exemptionID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#getExemption). ``` client.collaborationAllowlist.getExemption(`12345`, callback); ``` ## Get All Exempt Users for an Enterprise To retrieve a collection of users who are exempt from the collaboration allowlist for an enterprise, call [`collaborationAllowlist.getAllExemptions(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#getAllExemptions). ``` client.collaborationAllowlist.getAllExemptions(options, callback); ``` Alternatively you can limit the number of user collaboration allowlists you wish to retrieve by setting a limit, the default is 100 entries and the maximum is 1000 entries. ``` var options = { limit: 50; }; client.collaborationAllowlist.getAllExemptions(options, callback); ``` ## Remove a User Exemption from the Collaboration Allowlist To remove a user exemption from collaboration allowlist and make that user subject to allowlist restrictions again, you can call [`collaborationAllowlist.removeExemption(exemptionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#removeExemption). ``` client.collaborationAllowlist.removeExemption('12345678', callback); ``` --- ## Untitled *Type: page* Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. Get a Comment's Information Get… # Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. - [Get a Comment's Information](#get-a-comments-information) - [Get the Comments on a File](#get-the-comments-on-a-file) - [Add a Comment to a File](#add-a-comment-to-a-file) - [Reply to a Comment](#reply-to-a-comment) - [Change a Comment's Message](#change-a-comments-message) - [Delete a Comment](#delete-a-comment) ## Get a Comment's Information Calling [`comments.get(commentID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Comments.html#get) on a comment returns a snapshot of the comment's info. ``` client.comments.get('11111') .then(comment => { /* comment -> { type: 'comment', id: '11111', is_reply_comment: false, message: 'Great work!', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2012-12-12T11:25:01-08:00', item: { id: '33333', type: 'file' }, modified_at: '2012-12-12T11:25:01-08:00' } */ }); ``` ## Get the Comments on a File You can get all of the comments on a file by calling the [`files.getComments(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getComments) method. ``` var fileID = '12345'; client.files.getComments(fileID) .then(comments => { /* comments -> { total_count: 1, entries: [ { type: 'comment', id: '11111', is_reply_comment: false, message: 'Great work!', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2012-12-12T11:25:01-08:00', item: { id: '33333', type: 'file' }, modified_at: '2012-12-12T11:25:01-08:00' } ] } */ }); ``` ## Add a Comment to a File A comment can be added to a file with the [`comments.create(fileID, text, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Comments.html#create) method. ``` client.comments.create('33333', 'Is this the latest version?') .then(comment => { /* comment -> { type: 'comment', id: '11111', is_reply_comment: false, message: 'Is this the latest version?', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2012-12-12T11:25:01-08:00', item: { id: '33333', type: 'file' }, modified_at: '2012-12-12T11:25:01-08:00' } */ }); ``` A comment's message can also contain @mentions by using the string `@[userid:username]` anywhere within the message, where userid and username are the ID and username of the person being mentioned. [See the documentation](https://developers.box.com/docs/#comments-comment-object) on the `tagged_message` field for more information on @mentions. To make a tagged comment, use the [`comments.createTaggedComment(fileID, text, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Comments.html#createTaggedComment) method. ``` client.comments.createTaggedComment('33333', '@[23560:Bob] Is this the latest version?') .then(comment => { /* comment -> { type: 'comment', id: '11111', is_reply_comment: false, tagged_message: '@[23560:Bob] Is this the latest version?', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2012-12-12T11:25:01-08:00', item: { id: '33333', type: 'file' }, modified_at: '2012-12-12T11:25:01-08:00' } */ }); ``` ## Reply to a Comment To reply to a comment, call [`comments.reply(commentID, text, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Comments.html#reply) with the ID of the comment to reply to and the text of the reply comment. ``` // Reply to the comment with ID 11111 client.comments.reply('11111', 'Yes, this is the latest version.') .then(comment => { /* comment -> { type: 'comment', id: '44444', is_reply_comment: true, message: 'Yes, this is the latest version', created_by: { type: 'user', id: '55555', name: 'Example User 2', login: 'user2@example.com' }, created_at: '2012-12-13T07:19:08-08:00', item: { id: '33333', type: 'file' }, modified_at: '2012-12-13T07:19:08-08:00' } */ }); ``` A comment's message can also contain at-mentions by using the string `@[userid:username]` anywhere within the message, where `userid` and `username` are the ID and username of the person being mentioned. [See the documentation](https://developers.box.com/docs/#comments-comment-object) on the `tagged_message` field for more information on at-mentions. To make a tagged reply, use the [`comments.createTaggedReply(commentID, text, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Comments.html#createTaggedReply) method. ``` client.comments.createTaggedReply('11111', '@[22222:Sam] Yes, this is the most recent version!') .then(comment => { /* comment -> { type: 'comment', id: '44444', is_reply_comment: false, tagged_message: '@[22222:Sam] Yes, this is the most recent version!', created_by: { type: 'user', id: '55555', name: 'Example User 2', login: 'user2@example.com' }, created_at: '2012-12-13T07:19:08-08:00', item: { id: '33333', type: 'file' }, modified_at: '2012-12-13T07:19:08-08:00' } */ }); ``` ## Change a Comment's Message The message of a comment can be changed with the [`comments.update(commentID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Comments.html#update) method. ``` client.comments.update('11111', {message: 'New message'}) .then(comment => { /* comment -> { type: 'comment', id: '11111', is_reply_comment: false, message: 'New message', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2012-12-12T11:25:01-08:00', item: { id: '33333', type: 'file' }, modified_at: '2012-12-12T11:25:01-08:00' } */ }); ``` ## Delete a Comment A comment can be deleted with the [`comments.delete(commentID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Comments.html#delete) method. ``` client.comments.delete('11111') .then(() => { // deletion successful — no value returned }); ``` --- ## Untitled *Type: page* Configuration The BoxSDKNode is the base object used to configure client. Configure Proxy To set up your proxy, add your proxy settings to… # Configuration The `BoxSDKNode` is the base object used to configure [client](https://developer.box.com/143730815748e8d3be0de65a363b9f8b/client.md). ## Configure Proxy To set up your proxy, add your proxy settings to the `BoxSDK` object as shown below. You must include the proxy url, which should contain the `protocol`, `url`, and `port`, which in the case below are `http`, `sample.proxyurl.com` and `80` respectively. While the port, username and password are optional, the protocol and url are required. If your proxy does not require authentication, you can set the username and password to null or omit the parameters completely. The supported proxy protocols are `http`, `https`, `socks`, `socks4`, `socks4a`, `socks5`, `socks5h`, `pac+data`, `pac+file`, `pac+ftp`, `pac+http` and `pac+https`. ``` let sdk = new BoxSDK({ clientID: 'YOUR-CLIENT-ID', clientSecret: 'YOUR-CLIENT_SECRET', proxy: { url: 'http://sample.proxyurl.com:80', username: 'sample-username', password: 'sample-password', } }); ``` ## Configure how client retries calls and handles timeouts You can confugure how many retries, how long to wait between retries or upload timeout: ``` sdk = BoxSDKNode.getPreconfiguredInstance(APP_SETTINGS); var additonalParams = { numMaxRetries: 3, retryIntervalMS: 3000, uploadRequestTimeoutMS: 90000 }; sdk.configure(additonalParams); ``` The `numMaxRetries` sets the maximum number of retries when API request fails. Default value is `5`. The `retryIntervalMS` is used to calculate the wait time between retries. It is a number of miliseconds. SDK uses `Exponential backoff` algorithm to calculate the wait time. Default value is `2000` ms. The `uploadRequestTimeoutMS` sets the timeout after which an upload request is aborted Default value is `60000` ms. The `configure` method appends config values to existing configuration. So if you want you can configure sdk in several steps: ``` sdk = BoxSDKNode.getPreconfiguredInstance(APP_SETTINGS); sdk.configure({ retryIntervalMS: 3000 }); // you need to extend number of retires in some scenario sdk.configure({ numMaxRetries: 10 }); ``` ## Disable stream PassThrough for streaming responses By default the SDK uses `PassThrough` stream to handle streaming responses. It helps to support delayed reading of the response body, but in some cases it can cause memory leaks or not fully works. To disable `PassThrough` stream use the `disableStreamPassThrough` method: ``` sdk = BoxSDKNode.getPreconfiguredInstance(APP_SETTINGS); sdk.configure({ disableStreamPassThrough: true }); ``` ## Configure Base URL The Base Url is the URL that is used by the SDK to access Box. The default base URL are already defined for the `BoxSDKNode` but if you want to change default behaviour use the `configure` method on the sdk instance: ``` sdk = BoxSDKNode.getPreconfiguredInstance(APP_SETTINGS); var additonalParams = { apiRootURL: 'https://my.company.url.com', uploadAPIRootURL: 'https://my.company.url.com/upload', authorizeRootURL: 'https://my.company.url.com/authorize' }; sdk.configure(additonalParams); ``` The `apiRootURL` sets to what URL all API calls will be directed. Final URL used to access Box is built using `apiRootURL` and the API Version (`2.0`). For example by default the `apiRootURL` is set to `https://api.box.com` so after appending currently supported API version the URL is : `https://api.box.com/2.0`. The `uploadAPIRootURL` is used to configure the base URL used while uploading files. Final URL used to access Box is built using `uploadAPIRootURL` and API Version (`2.0`). For example by default the `uploadAPIRootURL` is set to `https://upload.box.com/api` so after appending currently supported API version the URL is : `https://upload.box.com/api/2.0`. The `authorizeRootURL` is used to configure the base URL used to obtain OAuth2 authorization tokens. --- ## Untitled *Type: page* Enterprise Get Enterprise Users Invite User to Enterprise Add New User Add New App User Transfer User Content Get Enterprise Users Get a… # Enterprise - [Get Enterprise Users](#get-enterprise-users) - [Invite User to Enterprise](#invite-user-to-enterprise) - [Add New User](#add-new-user) - [Add New App User](#add-new-app-user) - [Transfer User Content](#transfer-user-content) ## Get Enterprise Users Get a list of users in the current enterprise by calling the [`enterprise.getUsers(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Enterprise.html#getUsers) method. This method supports offset-based pagination and marker-based pagintation. To use offset-based pagination, do not pass in the `usemarker` parameter or set it to `false`. To use marker-based pagination, pass in the `usemarker` parameter as `true`. Use the `fields` option to specify the desired response fields, and `limit` (along with `offset` or `marker`) to control result set paging. Requesting information for only the fields you need can improve performance by reducing the size of the network response. ``` client.enterprise.getUsers({usemarker: true, marker: 'JFUirotE56hfyr56FH123'}) .then(users => { /* users -> { total_count: 1, entries: [ { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com', created_at: '2012-05-03T21:39:11-07:00', modified_at: '2012-08-23T14:57:48-07:00', language: 'en', space_amount: 5368709120, space_used: 52947, max_upload_size: 104857600, status: 'active', job_title: '', phone: '5555551374', address: '10 Cloud Way Los Altos CA', avatar_url: 'https://app.box.com/api/avatar/large/deprecated' } ] } */ }); ``` ## Invite User to Enterprise Invite a user to an enterprise by calling the [`enterprise.inviteUser(enterpriseID, email, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Enterprise.html#inviteUser) method with the ID of the enterprise and the user's email address. ``` client.enterprise.inviteUser('1345', 'jsmith@box.com', callback); ``` ## Add New User To provision a new managed user within the current enterprise, call the [`enterprise.addUser(login, name, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Enterprise.html#addUser) method with the email address the user will use to log in and the user's name. ``` client.enterprise.addUser( 'eddard@winterfell.example.com', 'Ned Stark', { role: client.enterprise.userRoles.COADMIN, address: '555 Box Lane', status: client.enterprise.userStatuses.CANNOT_DELETE_OR_EDIT }) .then(user => { /* user -> { type: 'user', id: '44444', name: 'Ned Stark', login: 'eddard@winterfell.example.com', created_at: '2012-11-15T16:34:28-08:00', modified_at: '2012-11-15T16:34:29-08:00', role: 'coadmin', language: 'en', timezone: 'America/Los_Angeles', space_amount: 5368709120, space_used: 0, max_upload_size: 2147483648, status: 'active', job_title: '', phone: '', address: '555 Box Lane', avatar_url: 'https://www.box.com/api/avatar/large/deprecated' } */ }); ``` ## Add New App User To provision a new app user within the current enterprise, call the [`enterprise.addAppUser(name, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Enterprise.html#addAppUser) method with the user's name. ``` client.enterprise.addAppUser('Daenerys Targaryen', { external_app_user_id: 'external-id' }) .then(appUser => { /* appUser -> { type: 'user', id: '55555', name: 'Daenerys Targaryen', login: 'AppUser_59659_vuNs7OCQ7y@box.com', created_at: '2015-04-20T20:09:59-07:00', modified_at: '2015-04-20T20:09:59-07:00', language: 'en', timezone: 'America/Los_Angeles', space_amount: 5368709120, space_used: 0, max_upload_size: 16106127360, status: 'active', job_title: '', phone: '', address: '', avatar_url: '' } */ }); ``` ## Transfer User Content To transfer one managed user's content to another user's account, call the [`enterprise.transferUserContent(sourceUserID, destUserID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Enterprise.html#transferUserContent) method with the IDs of the source and destination users. ``` var sourceUserID = '33333'; var destinationUserID = '44444'; client.enterprise.transferUserContent(sourceUserID, destinationUserID) .then(movedFolder => { /* movedFolder -> { type: 'folder', id: '123456789', sequence_id: '1', etag: '1', name: 'Other User's Files and Folders', created_at: '2018-04-23T11:00:07-07:00', modified_at: '2018-04-23T11:00:07-07:00', description: 'This folder contains files previously owned by Other User, and were transferred to you by your enterprise administrator. If you have any questions, please contact Enterprise Admin (admin@example.com).', size: 0, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_by: { type: 'user', id: '99999', name: 'Enterprise Admin', login: 'admin@example.com' }, modified_by: { type: 'user', id: '99999', name: 'Enterprise Admin', login: 'admin@example.com' }, trashed_at: null, purged_at: null, content_created_at: '2018-04-23T11:00:07-07:00', content_modified_at: '2018-04-23T11:00:07-07:00', owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, shared_link: null, folder_upload_email: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, item_status: 'active' } */ }); ``` --- ## Untitled *Type: page* Events The Box API supports two types of event streams -- one for the events specific to a particular user and one for all of the events in… # Events The Box API supports two types of event streams -- one for the events specific to a particular user and one for all of the events in an enterprise. [User Events](#user-events) - [Listening to the EventStream](#listening-to-the-eventstream) - [Deduplicating Events](#deduplicating-events) - [Get the Current Stream Position](#get-the-current-stream-position) - [Get Events](#get-events) [Enterprise Events](#enterprise-events) - [Listening to the Enterprise Event Stream](#listening-to-the-enterprise-event-stream) - [Handling errors](#handling-errors) - [Persisting the Stream State](#persisting-the-stream-state) ## User Events The Box API provides an events endpoint that utilizes long-polling to send events in real-time. The SDK provides an `EventStream` class (which implements [stream.Readable](https://nodejs.org/api/stream.html#stream_readable_streams)) that automatically handles long-polling and deduplicating events. - [Listening to the EventStream](#listening-to-the-eventstream) - [Get the Current Stream Position](#get-the-current-stream-position) - [Get Events](#get-events) ### Listening to the EventStream When the `EventStream` is started, it will begin long-polling asynchronously. Events received from the API are then forwarded to any listeners. ``` client.events.getEventStream(function(err, stream) { if (err) { // handle error } stream.on('data', function(event) { // handle the event }); }); ``` By default, the stream will start at the current time. You can start the stream at a past stream position by passing a position marker: ``` client.events.getEventStream('1408838928446360', function(err, stream) { /* ... */ }); ``` When you're done listening for events, call `stream.pause()` to stop long-polling. ### Deduplicating Events Since the Box API [may send duplicate events](https://developers.box.com/docs/#events), the `EventStream` will remember the last 5000 received events and automatically ignore them. ### Get the Current Stream Position It is possible to get the current stream position, which can later be used to fetch events from that point in time forward. ``` client.events.getCurrentStreamPosition(callback); ``` ### Get Events To get the latest chunk of events, you can call [`events.get(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Events.html#get). ``` client.events.get(null, callback); ``` You can also pass in a `stream_position` parameter to get events from a specific point in time: ``` client.events.get({stream_position: '1408838928446360'}, callback); ``` ### Destroying the Stream If you ever need to *stop* long-polling, use: ``` client.events.destroy(); ``` This *will not* cancel in-process network requests. It *will* ensure no further long-polling nor event fetching takes place. ## Enterprise Events The Box API has an enterprise events endpoint that is available to admin users and service accounts. The SDK includes an `EnterpriseEventStream` class (which implements [stream.Readable](https://nodejs.org/api/stream.html#stream_readable_streams)) that automatically handles polling for events and delivering them to the application. - [Listening to the Enterprise Event Stream](#listening-to-the-enterprise-event-stream) - [Handling errors](#handling-errors) - [Get the Stream Position](#get-the-stream-position) ### Listening to the Enterprise Event Stream When you attach a `'data'` event listener to an `EnterpriseEventStream`, it will begin fetching events from Box. Events received from the API are then forwarded to the listener. ``` client.events.getEnterpriseEventStream(function(err, stream) { if (err) { // Handle error } stream.on('data', function(event) { // Handle the event }); }); ``` To get events from admin events stream you have to pick stream_type from `admin_logs` or `admin_logs_streaming`. By default, the `admin_logs` stream is selected. Emphasis of this stream is on completeness over latency, which means that Box will deliver admin events in chronological order and without duplicates, but with higher latency. You can specify start and end time/dates. To monitor recent events that have been generated within Box across the enterprise use `admin_logs_streaming` as stream type. The emphasis for this feed is on low latency rather than chronological accuracy, which means that Box may return events more than once and out of chronological order. Events are returned via the API around 12 seconds after they are processed by Box (the 12 seconds buffer ensures that new events are not written after your cursor position). Only two weeks of events are available via this feed, and you cannot set start and end time/dates. Use `streamType` option to select stream type: ``` client.events.getEnterpriseEventStream({ streamType: 'admin_logs_streaming' }, callback); ``` By default, the stream will start at the current time. You can also start the stream from a specific date or from a previous stream position. To start from the earliest available events (~1 year), pass `streamPosition = '0'`. The stream will fetch all past events as quickly as your listener consumes them. Once the stream catches up to the current time, it will begin polling for new events every `pollingInterval` seconds (default = 60). ``` client.events.getEnterpriseEventStream({ startDate: '2016-01-01T00:00:00-08:00', pollingInterval: 60 }, callback); ``` Note that Box buffers enterprise events for ~60 seconds when using `admin_logs` stream type, before making them available to the `/events` API (to ensure that events are delivered in-order and without duplicates), so polling with an interval of less than 60 seconds is not normally needed with this event type. When using `admin_logs_streaming` you can set pooling interval to 12 seconds. If you pass `pollingInterval = 0`, then the stream will not use polling, but will end when all the currently available events have been delivered. ``` client.events.getEnterpriseEventStream({ startDate: '2016-01-01T00:00:00-08:00', endDate: '2017-01-01T00:00:00-08:00', pollingInterval: 0 }, callback); ``` You can also filter the event stream to only receive specific event types. The set of enterprise event types is available in `client.events.enterpriseEventTypes`. ``` client.events.getEnterpriseEventStream({ eventTypeFilter: [client.events.enterpriseEventTypes.UPLOAD, client.events.enterpriseEventTypes.DOWNLOAD] }, callback); ``` Since `EnterpriseEventStream` implements [stream.Readable](https://nodejs.org/api/stream.html#stream_readable_streams), you can use the usual flow-control mechanisms on the stream: ``` stream.pause(); stream.resume(); stream.isPaused(); ``` You can also pipe the output to a [stream.Writable](https://nodejs.org/api/stream.html#stream_writable_streams) stream (it must be an "object mode" stream): ``` stream.pipe(writableObjectModeStream); ``` ### Handling errors If an API or network error occurs, the stream will ignore the error and continue polling at the usual rate until the connection can be re-established. You can respond to errors with an `'error'` event listener: ``` stream.on('error', function(err) { // Handle the error. }); ``` ### Persisting the Stream State In many applications, you may need to persist the stream state so that you can resume processing events from the same point if your application is interrupted and restarted. You can attach a `newStreamState` event listener to be notified each time the stream position changes. ``` client.events.getEnterpriseEventStream(function(err, stream) { if (err) { // Handle error } // Restore the stream state from the previous run. stream.setStreamState(readState()); stream.on('newStreamState', function(streamState) { // Persist the stream state each time the stream position changes. writeState(streamState); }); stream.on('data', function(event) { // Handle the event. }); }); ``` --- ## Untitled *Type: page* File Requests File request objects represent a file request associated with a folder. Get a File Request's Information Copy a File Request's… # File Requests File request objects represent a file request associated with a folder. - [Get a File Request's Information](#get-a-file-requests-information) - [Copy a File Request's Information](#copy-a-file-requests-information) - [Update a File Request's Information](#update-a-file-requests-information) - [Delete a File Request](#delete-a-file-request) ## Get a File Request's Information Calling [`fileRequests.getById(fileRequestId: string)`](http://opensource.box.com/box-node-sdk/jsdoc/FileRequestsManager.html#getById) returns information on a file request [FileRequest](http://opensource.box.com/box-node-sdk/jsdoc/FileRequest.html). ``` client.fileRequests.getById(fileRequestId) ``` ## Copy a File Request's Information Calling [`fileRequests.copy(fileRequestId: string, copyBody: FileRequestCopyBody)`](http://opensource.box.com/box-node-sdk/jsdoc/FileRequestsManager.html#copy) copies an existing file request that is already present on one folder, and applies it to another folder. If you want to set certain fields of the newly copied file request when it is created, set those fields in the [`FileRequestCopyBody`](http://opensource.box.com/box-node-sdk/jsdoc/FileRequestCopyBody.html) that you pass into copy method. ``` client.fileRequests.copy(fileRequestId, { folder: { id: '157979815648', type: 'folder' } }).then((r: FileRequest) => { // do something with the copied file request console.log(r) }); ``` ## Update a File Request's Information Calling [`fileRequests.update(fileRequestId: string, updateBody: FileRequestUpdateBody)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#updateInfo) updates a file request. This can be used to activate or deactivate a file request using [`FileRequestUpdateBody`](http://opensource.box.com/box-node-sdk/jsdoc/FileRequestUpdateBody.html) that you pass into update method. ``` client.fileRequests.update(fileRequestId, { title: 'Updated title' }).then((r: FileRequest) => { // do something with the updated file request console.log(r) }); ``` ## Delete a File Request Calling `fileRequests.delete(fileRequestId: string)`][delete](http://opensource.box.com/box-node-sdk/jsdoc/FileRequestsManager.html#delete) deletes a file request permanently. ``` client.fileRequests.delete('2484517969').then(() => console.log('Removed file request')); ``` --- ## Untitled *Type: page* Groups Groups contain a set of users, and can be used in place of individual users in some operations, such as collaborations. Create Group… # Groups Groups contain a set of users, and can be used in place of individual users in some operations, such as collaborations. - [Create Group](#create-group) - [Get Group](#get-group) - [Update Group](#update-group) - [Delete Group](#delete-group) - [Add a User to a Group](#add-a-user-to-a-group) - [Get Membership](#get-membership) - [Get Group Memberships for a User](#get-group-memberships-for-a-user) - [Update Membership](#update-membership) - [Remove Membership](#remove-membership) - [Get Group Memberships](#get-group-memberships) - [Get Enterprise Groups](#get-enterprise-groups) - [Get Group Collaborations](#get-group-collaborations) ## Get All Groups To get a list of all groups in the calling user's enterprise, call the [`groups.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#getAll) method. Note that this requires permission to view an enterprise's groups, which is reserved for enterprise administrators. ``` client.groups.getAll() .then(groups => { /* groups -> { total_count: 1, entries: [ { type: 'group', id: '1786931', name: 'friends' } ], limit: 100, offset: 0 } */ }); ``` ## Create Group To create a new group, call the [`groups.create(name, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#create) method. ``` client.groups.create('My group', {description: 'An example group'}) .then(group => { /* group -> { type: 'group', id: '119720', name: 'Box Employees', created_at: '2013-05-16T15:27:57-07:00', modified_at: '2013-05-16T15:27:57-07:00' } */ }); ``` ## Get Group To retrieve the information for a group, call the [`groups.get(groupID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#get) method. ``` client.groups.get('11111') .then(group => { /* group -> { type: 'group', id: '11111', name: 'Everyone', created_at: '2014-09-15T13:15:35-07:00', modified_at: '2014-09-15T13:15:35-07:00' } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` client.groups.get('12345', {fields: 'name,description'}) .then(group => { // ... }); ``` ## Update Group To change the properties of a group object, call the [`groups.update(groupID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#update) method with `updates` being the set of properties to update. ``` client.groups.update('11111', {name: 'New group name'}) .then(group => { /* group -> { type: 'group', id: '11111', name: 'New group name', created_at: '2014-09-15T13:15:35-07:00', modified_at: '2014-09-16T13:15:35-07:00' } */ }); ``` ## Delete Group To delete a group, call the [`groups.delete(groupID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#delete) method. ``` client.groups.delete('11111') .then(() => { // deletion succeeded — no value returned }); ``` ## Add a User to a Group To add a user to a group, call the [`groups.addUser(groupID, userID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#addUser) method. ``` var groupID = '11111'; var userID = '22222'; client.groups.addUser(groupID, userID, {role: client.groups.userRoles.MEMBER}) .then(membership => { /* membership -> { type: 'group_membership', id: '33333', user: { type: 'user', id: '22222', name: 'Alison Wonderland', login: 'alice@example.com' }, group: { type: 'group', id: '11111', name: 'Employees' }, role: 'member', configurable_permissions: { can_run_reports: false, can_instant_login: false, can_create_accounts: false, can_edit_accounts: false } } */ }); ``` ## Get Membership To retrieve information about a specific membership record, which shows that a given user is in the group, call the [`groups.getMembership(membershipID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#getMembership) method. ``` client.groups.getMembership('33333') .then(membership => { /* membership -> { type: 'group_membership', id: '33333', user: { type: 'user', id: '22222', name: 'Alison Wonderland', login: 'alice@example.com' }, group: { type: 'group', id: '11111', name: 'Employees' }, role: 'member', configurable_permissions: { can_run_reports: false, can_instant_login: false, can_create_accounts: false, can_edit_accounts: false }, created_at: '2013-05-16T15:27:57-07:00', modified_at: '2013-05-16T15:27:57-07:00' } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` client.groups.getMembership('33333', {fields: 'user,created_at'}) .then(membership => { /* membership -> { type: 'group_membership', id: '33333', user: { type: 'user', id: '22222', name: 'Alison Wonderland', login: 'alice@example.com' }, created_at: '2013-05-16T15:27:57-07:00' */ }); ``` ## Get Group Memberships for a User To get a list of groups to which a user belongs, call the [`users.getGroupMemberships(userID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#getGroupMemberships) method. Note that this method requires the calling user to have permission to view groups, which is restricted to enterprise administrators. ``` var userID = '22222'; client.users.getGroupMemberships(userID) .then(memberships => { /* memberships -> { total_count: 1, entries: [ { type: 'group_membership', id: '12345', user: { type: 'user', id: '22222', name: 'Alison Wonderland', login: 'alice@example.com' }, group: { type: 'group', id: '11111', name: 'Employees' }, role: 'member' } ], limit: 100, offset: 0 } */ }); ``` ## Update Membership To update a membership record, call the [`groups.updateMembership(membershipID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#updateMembership) method with `updates` being the properties to update. ``` // Promote a user to group admin client.groups.updateMembership('12345', {role: client.groups.userRoles.ADMIN}) .then(membership => { /* membership -> { type: 'group_membership', id: '33333', user: { type: 'user', id: '22222', name: 'Alison Wonderland', login: 'alice@example.com' }, group: { type: 'group', id: '11111', name: 'Employees' }, role: 'admin', configurable_permissions: { can_run_reports: false, can_instant_login: false, can_create_accounts: false, can_edit_accounts: false }, created_at: '2013-05-16T15:27:57-07:00', modified_at: '2013-05-16T15:27:57-07:00' } */ }); ``` ## Remove Membership To remove a specific membership record, which removes a user from the group, call the [`groups.removeMembership(membershipID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#removeMembership) method with the ID of the membership record to remove. ``` client.groups.removeMembership('33333') .then(() => { // removal succeeded — no value returned }); ``` ## Get Group Memberships To get a list of all memberships to a group, call the [`groups.getMemberships(groupID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#getMemberships) method with the ID of the group to get the list of memberships for. ``` client.groups.getMemberships('11111') .then(memberships => { /* memberships -> { total_count: 2, entries: [ { type: 'group_membership', id: '44444', user: { type: 'user', id: '22222', name: 'Alice', login: 'alice@example.com' }, group: { type: 'group', id: '11111', name: 'Employees' }, role: 'member' }, { type: 'group_membership', id: '55555', user: { type: 'user', id: '66666', name: 'White Rabbit', login: 'rabbit@example.com' }, group: { type: 'group', id: '11111', name: 'Employees' }, role: 'member' } ], offset: 0, limit: 100 } */ }); ``` ## Get Group Collaborations To get a list of collaborations for a group, which show which items the group has access to, call the [`groups.getCollaborations(groupID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#getCollaborations) method. ``` client.groups.getCollaborations('11111') .then(collaborations => { /* collaborations -> { total_count: 1, entries: [ { type: 'collaboration', id: '22222', created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2013-11-14T16:16:20-08:00', modified_at: '2013-11-14T16:16:20-08:00', expires_at: null, status: 'accepted', accessible_by: { type: 'group', id: '11111', name: 'Remote Employees' }, role: 'viewer', acknowledged_at: '2013-11-14T16:16:20-08:00', item: { type: 'folder', id: '44444', sequence_id: '0', etag: '0', name: 'Documents' } } ], offset: 0, limit: 100 } */ }); ``` ## Terminate user groups session To terminate a user's session for groups, call the [`groups.terminateSession(groupIDs, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Groups.html#terminateSession) method. ``` var groupIDs = ['11111', '22222']; client.groups.terminateSession(groupIDs) .then((result) => { /* result -> { message: 'Request is successful, please check the admin events for the status of the job' } */ }); ``` --- ## Untitled *Type: page* Information Barrier Reports Information Barrier Reports Get shield information barrier report by ID List shield information barrier reports… # Information Barrier Reports [Information Barrier Reports](#information-barrier-reports) - [Get shield information barrier report by ID](#get-shield-information-barrier-report-by-id) - [List shield information barrier reports](#list-shield-information-barrier-reports) - [Create shield information barrier report](#create-shield-information-barrier-report) ## Get shield information barrier report by ID To retrieve a shield information barrier report by its ID, call the [`shieldInformationBarrierReports.getById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierReportsManager.html#getById) method. ``` const barrierReport = await client.shieldInformationBarrierReports.getById({ shield_information_barrier_report_id: '12345', }); console.log(`Shield information barrier report id ${barrierReport.id}`); ``` ## List shield information barrier reports To retrieves a list of shield information barrier reports based on provided barrier ID, call the [`shieldInformationBarrierReports.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierReportsManager.html#getAll) method. ``` const result = await client.shieldInformationBarrierReports.getAll({ shield_information_barrier_id: '123' }); console.log(`There are ${result.entries.length} shield information barrier reports`); ``` ## Create shield information barrier report To create a shield information barrier report for a given barrier, call the [`shieldInformationBarrierReports.create(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierReportsManager.html#create) method with a `shield_information_barrier` object in the body of the request. ``` const barrierReport = await client.shieldInformationBarrierReports.create({ shield_information_barrier: { id: '123', type: 'shield_information_barrier' } }); console.log(`Shield information barrier report with id ${barrierReport.id} was created`); ``` --- ## Untitled *Type: page* Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a… # Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a folder with another user or group, and perform other common folder operations (move, copy, delete, etc.). [Folders](#folders) - [Get a Folder's Information](#get-a-folders-information) - [Get a Folder's Items](#get-a-folders-items) - [Update a Folder's Information](#update-a-folders-information) - [Create a Folder](#create-a-folder) - [Copy a Folder](#copy-a-folder) - [Move a Folder](#move-a-folder) - [Rename a Folder](#rename-a-folder) - [Delete a Folder](#delete-a-folder) - [Lock a folder](#lock-a-folder) - [Get All Locks on a Folder](#get-all-locks-on-a-folder) - [Delete a Lock on a Folder](#delete-a-lock-on-a-folder) - [Find a Folder for a Shared Link](#find-a-folder-for-a-shared-link) - [Ceate or update a Shared Link](#create-or-update-a-shared-link) - [Get a Shared Link](#get-a-shared-link) - [Remove a Shared Link](#remove-a-shared-link) ## Get a Folder's Information Folder information can be retrieved by calling the [`folders.get(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#get) method. Use the `fields` option to specify the desired fields. ``` client.folders.get('11111') .then(folder => { /* folder -> { type: 'folder', id: '11111', sequence_id: '1', etag: '1', name: 'Pictures', created_at: '2012-12-12T10:53:43-08:00', modified_at: '2012-12-12T11:15:04-08:00', description: 'Some pictures I took', size: 629644, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_by: { type: 'user', id: '22222', name: 'Example User' login: 'user@example.com' }, modified_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, shared_link: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, item_status: 'active', item_collection: { total_count: 1, entries: [ { type: 'file', id: '33333', sequence_id: '3', etag: '3', sha1: '134b65991ed521fcfe4724b7d814ab8ded5185dc', name: 'tigers.jpeg' } ], offset: 0, limit: 100 } } */ }); ``` Requesting information for only the fields you need can improve performance and reduce the size of the network request. ``` client.folders.get( '12345', { fields: 'name,shared_link,permissions,collections,sync_state' } ).then(folder => { // ... }); ``` The user's root folder can be accessed by calling the [`folders.get(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#get) method with the `folderID` value of `'0'`. ``` client.folders.get('0') .then(rootFolder => { // ... }); ``` ## Get a Folder's Items Folder items can be retrieved by calling the [`folders.getItems(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#getItems) method. This method supports offset-based pagination and marker-based pagination. To use offset-based pagination, do not pass in the `usemarker` parameter or set it to `false`. To use marker-based pagination, pass in the `usemarker` parameter as `true`. Use the `fields` option to specify the desired fields, and `limit` and (`offset` or `marker`) to control result set paging. Requesting information for only the fields you need can improve performance by reducing the size of the network response. ``` client.folders.getItems( '12345', { usemarker: 'false', fields: 'name', offset: 0, limit: 25 }) .then(items => { /* items -> { total_count: 2, entries: [ { type: 'folder', id: '11111', sequence_id: '1', etag: '1', name: 'Personal Documents' }, { type: 'file', id: '22222', sequence_id: '0', etag: '0', name: 'Q2 Strategy.pptx' } ], offset: 0, limit: 25, order: [ { by: 'type', direction: 'ASC' }, { by: 'name', direction: 'ASC' } ] } */ }); ``` ## Update a Folder's Information Updating a folder's information is done by calling the [`folders.update(folderID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#update) method. Use the `updates` parameter to specify the fields to update and their new values. ``` client.folders.update('11111', {name: 'Pictures from 2017'}) .then(updatedFolder => { /* updatedFolder -> { type: 'folder', id: '11111', sequence_id: '1', etag: '1', name: 'Pictures from 2017', created_at: '2012-12-12T10:53:43-08:00', modified_at: '2012-12-12T11:15:04-08:00', description: 'Some pictures I took', size: 629644, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_by: { type: 'user', id: '22222', name: 'Example User' login: 'user@example.com' }, modified_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, shared_link: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, item_status: 'active', item_collection: { total_count: 1, entries: [ { type: 'file', id: '33333', sequence_id: '3', etag: '3', sha1: '134b65991ed521fcfe4724b7d814ab8ded5185dc', name: 'tigers.jpeg' } ], offset: 0, limit: 100 } } */ }); ``` If you want to ensure that your update does not overwrite any other updates (i.e. to prevent against possible race conditions), you can pass the last known value of the folder's `etag` field via the `etag` option; this will generate an error if the folder was modified between when you read that `etag` value and when your updates are processed by the API. ``` client.folders.update('22222', { name: 'Renamed Folder', etag: '5', fields: 'name' }) .then(updatedFolder => { /* updatedFolder -> { type: 'folder', id: '22222', sequence_id: '1', etag: '6', name: 'Renamed Folder' } */ }) .catch(err => { if (err.statusCode === 412) { // Precondition failed — the folder was modified before the update was processed // Read the folder again to ensure it is safe to update and then retry } }); ``` ## Create a Folder Create a child folder by calling the [`folders.create(parentFolderID, newFolderName, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#create) method. ``` client.folders.create('0', 'New Folder') .then(folder => { /* folder -> { type: 'folder', id: '123456', sequence_id: '0', etag: '0', name: 'New Folder', created_at: '2012-12-12T10:53:43-08:00', modified_at: '2012-12-12T11:15:04-08:00', description: '', size: 0, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_by: { type: 'user', id: '22222', name: 'Example User' login: 'user@example.com' }, modified_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, shared_link: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, item_status: 'active', item_collection: { total_count: 0, entries: [], offset: 0, limit: 100 } } */ }); ``` ## Copy a Folder Call the [`folders.copy(sourceFolderID, destinationFolderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#copy) method to copy a folder into another folder. ``` client.folders.copy('11111', '22222') .then(folderCopy => { /* folderCopy -> { type: 'folder', id: '1234567', sequence_id: '0', etag: '0', name: 'Pictures from 2017', created_at: '2012-12-12T10:53:43-08:00', modified_at: '2012-12-12T11:15:04-08:00', description: 'Some pictures I took', size: 629644, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, { type: 'folder', id: '22222', sequence_id: '3', etag: '3', name: 'Archives' } ] }, created_by: { type: 'user', id: '22222', name: 'Example User' login: 'user@example.com' }, modified_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, shared_link: null, parent: { type: 'folder', id: '22222', sequence_id: '3', etag: '3', name: 'Archives' }, item_status: 'active', item_collection: { total_count: 1, entries: [ { type: 'file', id: '44444', sequence_id: '0', etag: '0', sha1: '134b65991ed521fcfe4724b7d814ab8ded5185dc', name: 'tigers.jpeg' } ], offset: 0, limit: 100 } } */ }); ``` An optional `name` parameter can also be passed to rename the folder on copy. This can be used to avoid a name conflict when there is already an item with the same name in the target folder. ``` client.folders.copy('12345', '0', {name: 'Renamed folder'}) .then(folderCopy => { // ... }); ``` ## Move a Folder Call the [`folders.move(sourceFolderID, destinationFolderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#move) method with the destination you want the folder moved to. ``` var folderID = '11111'; var destinationFolderID = '22222'; client.folders.move(folderID, destinationfolderID) .then(folder => { /* folder -> { type: 'folder', id: '11111', sequence_id: '1', etag: '1', name: 'Pictures from 2017', created_at: '2012-12-12T10:53:43-08:00', modified_at: '2012-12-12T11:15:04-08:00', description: 'Some pictures I took', size: 629644, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, { type: 'folder', id: '22222', sequence_id: '3', etag: '3', name: 'Archives' } ] }, created_by: { type: 'user', id: '22222', name: 'Example User' login: 'user@example.com' }, modified_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, shared_link: null, parent: { type: 'folder', id: '22222', sequence_id: '3', etag: '3', name: 'Archives' }, item_status: 'active', item_collection: { total_count: 1, entries: [ { type: 'file', id: '33333', sequence_id: '3', etag: '3', sha1: '134b65991ed521fcfe4724b7d814ab8ded5185dc', name: 'tigers.jpeg' } ], offset: 0, limit: 100 } } */ }); ``` ## Rename a Folder Use the [`folders.update(folderID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#update) method to rename a folder by passing a new name for the folder in `updates.name`. ``` client.folders.update('12345', {name: 'New Name'}, callback); ``` ## Delete a Folder A folder can be deleted with the [`folders.delete(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#delete) method. ``` client.folders.delete('12345', {recursive: true}) .then(() => { // deletion succeeded — no value returned }); ``` ## Lock a Folder Use the [`folders.lock(folderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#lock) to lock a folder ``` var folderID = '11111'; client.folders.lock(folderID) .then(folderLock => { /* folderLock -> { "id": "12345678", "type": "folder_lock", "created_at": "2020-09-14T23:12:53Z", "created_by": { "id": "11446498", "type": "user" }, "folder": { "id": "12345", "type": "folder", "etag": "1", "name": "Contracts", "sequence_id": "3" }, "lock_type": "freeze", "locked_operations": { "delete": true, "move": true } } */ }); ``` ## Get All Locks on a Folder Use the [`folders.getLocks(folderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#lock) to get all locks on a folder. ``` var folderID = '11111'; client.folders.getLocks(folderID) .then(folderLocks => { /* folderLocks -> { "entries": [ { "folder": { "id": "12345", "etag": "1", "type": "folder", "sequence_id": "3", "name": "Contracts" }, "id": "12345678", "type": "folder_lock", "created_by": { "id": "11446498", "type": "user" }, "created_at": "2020-09-14T23:12:53Z", "locked_operations": { "move": true, "delete": true }, "lock_type": "freeze" } ], "limit": 1000, "next_marker": null } */ }); ``` ## Delete a Lock on a Folder Use the [`folders.deleteLock(folderLockID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#deleteLock) method to delete a folder lock. ``` var folderLockID = '12345'; client.folders.deleteLock(folderLockID) .then(() => { // deletion succeeded — no value returned }); ``` ## Find a Folder for a Shared Link To find a folder given a shared link, use the [`sharedItems.get(url, password, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SharedItems.html#get) method. ``` client.sharedItems.get( 'https://app.box.com/s/gjasdasjhasd', 'letmein' ),then(folder => { //... }); ``` ## Create or update a Shared Link To create or update a shared link for a file use [`folders.update(folderID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#update) method, passing a new `shared_link` value in the `updates` parameter. ``` client.folders.update('12345', { shared_link: { access: "open", password: "do-not-use-this-password", unshared_at: "2022-12-12T10:53:43-08:00", vanity_name: "my-shared-link", permissions: { can_view: true, can_download: true } } }).then(folder => { // ... }) ``` This will make a shared link to be `open` to everyone, but users will need to provide `password` to access the folder. This link will be unshared at `"2022-12-12T10:53:43-08:00"`. By setting `vanity_name` we create custom URL `https://app.box.com/v/my-shared-link`. Custom URLs should not be used when sharing sensitive content as vanity URLs are a lot easier to guess than regular shared links. Additionally, everyone who has this link can `view` and `download` the folder. You can create shared link using default values ``` client.folders.update('12345', { shared_link: {} }).then(folder => { // ... }) ``` - Default `access` value comes from the access level specified by the enterprise admin. - Default `password`, `unshared_at`, `vanity_name` will be empty. - Default `permissions` allows to view and download folder. You can remove any field set on a link by sending value `null` (or empty object when it comes to `permissions`). This will cause it's value to be default. For example, let's remove `access` and `permissions`: ``` client.folders.update('12345', { shared_link: { access: null, permissions: {} } }).then(folder => { // ... }) ``` This will remove `open` access, and it will fall back to default value set by the enterprise admin. The `permissions` we set on a shared link will be removed and default permissions will be applied. Other properties of the shared link will not be changed as we are not sending them. ## Get a Shared Link To check for an existing shared link on a folder, inspect the `shared_link` field on a folder object. This object, when present, contains a `unicode` string containing the shared link URL. ``` client.folders.get('11111', { fields: 'shared_link' }) .then(folder => { let url = folder.shared_link.url //... }) ``` ## Remove a Shared Link A shared link for a folder can be removed calling [`folders.update(folderID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#update) with `null` for the `shared_link` value. ``` client.folders.update('12345', { shared_link: null }).then(folder => { // ... }) ``` --- ## Untitled *Type: page* Information Barrier Segment Members Information Barrier Segment Members Get shield information barrier segment member by ID List shield… # Information Barrier Segment Members [Information Barrier Segment Members](#information-barrier-segment-members) - [Get shield information barrier segment member by ID](#get-shield-information-barrier-segment-member-by-id) - [List shield information barrier segment members](#list-shield-information-barrier-segment-members) - [Create shield information barrier segment member](#create-shield-information-barrier-segment-member) - [Delete shield information barrier segment member by ID](#delete-shield-information-barrier-segment-member-by-ID) ## Get shield information barrier segment member by ID To retrieve a shield information barrier segment member by its ID, call the [`shieldInformationBarrierSegmentMembers.getById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentMembersManager.html#getById) method. ``` const barrierSegmentMember = await client.shieldInformationBarrierSegmentMembers.getById({ shield_information_barrier_segment_member_id: '12345', }); console.log(`Shield information barrier segment member id ${barrierSegmentMember.id}`); ``` ## List shield information barrier segment members To retrieves a list shield information barrier segment members based on provided segment IDs, call the [`shieldInformationBarrierSegmentMembers.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentMembersManager.html#getAll) method. ``` const result = await client.shieldInformationBarrierSegmentMembers.getAll({ shield_information_barrier_segment_id: '123' }); console.log(`There are ${result.entries.length} shield information barrier segment members`); ``` ## Create shield information barrier segment member To creates a new shield information barrier segment member, call the [`shieldInformationBarrierSegmentMembers.create(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentMembersManager.html#create) method with two objects in the body of the request, `barrer segment` and `user` where only `id` and `type` properties are required in each of them. ``` const barrierSegmentMember = await client.shieldInformationBarrierSegmentMembers.create({ shield_information_barrier_segment: { id: '234', type: 'shield_information_barrier_segment' }, user: { id: '456', type: 'user' } }); console.log(`Shield information barrier segment member id ${barrierSegmentMember.id} created`); ``` ## Delete shield information barrier segment member by ID To delete the shield information barrier segment member based on provided ID, call the [`shieldInformationBarrierSegmentMembers.delete(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentMembersManager.html#deleteById) method. ``` await client.shieldInformationBarrierSegmentMembers.deleteById({ shield_information_barrier_segment_member_id: '12345' }); ``` --- ## Untitled *Type: page* Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other… # Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other common file operations (move, copy, delete, etc.). [Files](#files) - [Get a File's Information](#get-a-files-information) - [Update a File's Information](#update-a-files-information) - [Download a File](#download-a-file) - [Get a File's Download URL](#get-a-files-download-url) - [Upload a File](#upload-a-file) [Chunked Upload](#chunked-upload) - [Automatic Uploader](#automatic-uploader) [Manual Process](#manual-process) - [Create Upload Session](#create-upload-session) - [Upload Part](#upload-part) - [Commit Upload Session](#commit-upload-session) - [Abort Upload Session](#abort-upload-session) - [Get Upload Session Parts](#get-upload-session-parts) - [Get Upload Session Status](#get-upload-session-status) [Upload Preflight Check](#upload-preflight-check) [Move a File](#move-a-file) [Copy a File](#copy-a-file) [Delete a File](#delete-a-file) [Get File Versions](#get-file-versions) [Upload a New Version of a File](#upload-a-new-version-of-a-file) [Download a Previous Version of a File](#download-a-previous-version-of-a-file) [Delete a Previous File Version](#delete-a-previous-file-version) [Find a File for a Shared Link](#find-a-file-for-a-shared-link) [Create or update a Shared Link](#create-or-update-a-shared-link) [Get a Shared Link](#get-a-shared-link) [Get information about Shared Link Permissions Options](#get-information-about-shared-link-permissions-options) [Remove a Shared Link](#remove-a-shared-link) [Promote Version](#promote-version) [Get Embed Link](#get-embed-link) [Lock a File](#lock-a-file) [Unlock a File](#unlock-a-file) [Get Representation Info](#get-representation-info) [Get Representation Content](#get-representation-content) [Create a Zip File](#create-a-zip-file) [Download a Zip File](#download-a-zip-file) ## Get a File's Information Calling [`files.get(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#get) on a file returns a snapshot of the file's info. ``` client.files.get('11111') .then(file => { /* file -> { type: 'file', id: '11111', file_version: { type: 'file_version', id: '22222', sha1: '97b3dbba6eab7ad0f058240744c8636b7c7bea93' }, sequence_id: '1', etag: '1', sha1: '97b3dbba6eab7ad0f058240744c8636b7c7bea93', name: 'Puppy.png', description: '', size: 106833, path_collection: { total_count: 2, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, { type: 'folder', id: '33333', sequence_id: '0', etag: '0', name: 'Collaborated Folder' } ] }, created_at: '2016-11-16T22:01:44-08:00', modified_at: '2016-11-16T22:01:51-08:00', trashed_at: null, purged_at: null, content_created_at: '2016-10-29T18:33:50-07:00', content_modified_at: '2016-10-29T18:33:50-07:00', created_by: { type: 'user', id: '44444', name: 'Owner', login: 'owner@example.com' }, modified_by: { type: 'user', id: '44444', name: 'Owner', login: 'owner@example.com' }, owned_by: { type: 'user', id: '44444', name: 'Owner', login: 'owner@example.com' }, shared_link: null, parent: { type: 'folder', id: '33333', sequence_id: '0', etag: '0', name: 'Collaborated Folder' }, item_status: 'active' } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` // Only get information about a few specific fields. client.files.get('11111', { fields: 'size,owned_by' }) .then(file => { /* file -> { type: 'file', id: '11111', size: 106833, owned_by: { type: 'user', id: '44444', name: 'Owner', login: 'owner@example.com' } } */ }); ``` ## Update a File's Information Updating a file's information is done by calling [`files.update(fileID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#update) with the fields to be updated. ``` client.files.update('75937', { name : 'New name.pdf', fields: 'name' }) .then(updatedFile => { /* updatedFile => { type: 'file', id: '11111', name: 'New name.pdf' } */ }); ``` If you want to ensure that your updates do not overwrite any other updates (i.e. to prevent against possible race conditions), you can pass the last known value of the file's `etag` field via the `etag` option; this will generate an error if the file was modified between when you read that `etag` value and when your updates were processed by the API. ``` client.files.update('11111', { name: 'New name.pdf', etag: '5', fields: 'name' }) .then(updatedFile => { // ... }) .catch(err => { if (err.statusCode === 412) { // Precondition failed — the file was modified before our updates were processed // We should read the file again to ensure our updates are safe and retry } }); ``` ## Download a File A file can be downloaded by calling [`files.getReadStream(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getReadStream), which provides an instance of `stream.Readable` that will yield the file's contents. ``` var fs = require('fs'); client.files.getReadStream('12345', null, function(error, stream) { if (error) { // handle error } // write the file to disk var output = fs.createWriteStream('/path/to/file'); stream.pipe(output); }); ``` To download a previous version of the file, pass the `version` option: ``` client.files.getReadStream('123456', { version: '98765' }, callback); ``` To download only a subset of the file's contents, pass a byte range as an array of the byte indices to start and stop at to the `byteRange` option. **Note:** Byte indices are inclusive; for example, `[0, 99]` would download the first 100 bytes of the file. ``` client.files.getReadStream('12345', {byteRange: [0, 99] }, callback); ``` ## Get a File's Download URL The download URL of a file an be retrieved by calling [`files.getDownloadURL(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getDownloadURL). It returns the URL as a string. ``` client.files.getDownloadURL('12345') .then(downloadURL => { // downloadURL -> 'https://dl.boxcloud.com/...' }); ``` ## Upload a File The simplest way to upload a file to a folder is by calling the [`files.uploadFile(parentFolderID, filename, content, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#uploadFile) method with a `stream.Readable` or `Buffer` of the file to upload. ``` var fs = require('fs'); var stream = fs.createReadStream('/path/to/My File.pdf'); var folderID = '0' client.files.uploadFile(folderID, 'My File.pdf', stream) .then(file => { /* file -> { total_count: 1, entries: [ { type: 'file', id: '11111', file_version: { type: 'file_version', id: '22222', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' }, sequence_id: '0', etag: '0', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', name: 'My File.pdf', description: '', size: 68431, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_at: '2017-05-16T15:18:02-07:00', modified_at: '2017-05-16T15:18:02-07:00', trashed_at: null, purged_at: null, content_created_at: '2017-05-16T15:18:02-07:00', content_modified_at: '2017-05-16T15:18:02-07:00', created_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, shared_link: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } item_status: 'active' } ] } */ }); ``` To preserve file timestamps, you may pass the created and modified times as optional parameters: ``` var fs = require('fs'); var stream = fs.createReadStream('/path/to/file'); var options = { content_created_at: '2015-05-12T17:38:14-0600', content_modified_at: '2016-02-15T22:42:09-0600', }; client.files.uploadFile('98768', 'New File', stream, options) .then(file => { // ... }); ``` If you want to pass a Readable you must pass the content length as an optional parameter. Here is an example of passing Base64 String as file content: ``` var {Readable} = require('stream'); var base64Content = 'TXkgY29udGVudAo='; // your base64 content var base64Buffer = Buffer.from(base64Content, 'base64'); // we are using just Readable to create a stream, but you can use any library you want var stream = new Readable() stream._read = () => { stream.push(base64Buffer); stream.push(null); }; // you have to pass options and define content length var options = { content_length: Buffer.byteLength(base64Content, 'base64') }; client.files.uploadFile('0', 'My Base64 File.txt', stream, options); ``` ## Chunked Upload For large files or in cases where the network connection is less reliable, you may want to upload the file in parts. This allows a single part to fail without aborting the entire upload, and failed parts can then be retried. ### Automatic Uploader The SDK provides a method of automatically handling a chunked upload; simply call [`files.getChunkedUploader(folderID, size, name, file, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getChunkedUploader) with the ID of the destination folder, the size and file name of the file to be uploaded, and a `Buffer` or `ReadableStream` of the file to be uploaded. ``` // Upload a 2GB file "huge.pdf" into folder 12345 var stream = fs.createReadStream('huge.pdf'); client.files.getChunkedUploader('12345', 2147483648, 'huge.pdf', stream) .then(uploader => uploader.start()) .then(file => { /* file -> { total_count: 1, entries: [ { type: 'file', id: '11111', file_version: { type: 'file_version', id: '22222', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' }, sequence_id: '0', etag: '0', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', name: 'huge.pdf', description: '', size: 2147483648, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '12345', sequence_id: null, etag: null, name: 'My Folder' } ] }, created_at: '2017-05-16T15:18:02-07:00', modified_at: '2017-05-16T15:18:02-07:00', trashed_at: null, purged_at: null, content_created_at: '2017-05-16T15:18:02-07:00', content_modified_at: '2017-05-16T15:18:02-07:00', created_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, shared_link: null, parent: { type: 'folder', id: '12345', sequence_id: null, etag: null, name: 'My Folder' } item_status: 'active' } ] } */ }); ``` A new version of a file can be uploaded in the same way by calling [`files.getNewVersionChunkedUploader(fileID, size, file, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getNewVersionChunkedUploader) with the ID of the file to upload a new version of, along with the size of the new version and a `Buffer` or `ReadableStream` of the new version. ``` // Upload a new 2GB version of file 98765 var stream = fs.createReadStream('huge.pdf'); client.files.getNewVersionChunkedUploader('11111', 2147483648, stream) .then(uploader => uploader.start()) .then(file => { /* file -> { total_count: 1, entries: [ { type: 'file', id: '11111', file_version: { type: 'file_version', id: '22222', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' }, sequence_id: '0', etag: '0', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', name: 'huge.pdf', description: '', size: 2147483648, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '12345', sequence_id: null, etag: null, name: 'My Folder' } ] }, created_at: '2017-05-16T15:18:02-07:00', modified_at: '2017-05-21T15:18:02-07:00', trashed_at: null, purged_at: null, content_created_at: '2017-05-16T15:18:02-07:00', content_modified_at: '2017-05-21:18:02-07:00', created_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, shared_link: null, parent: { type: 'folder', id: '12345', sequence_id: null, etag: null, name: 'My Folder' } item_status: 'active' } ] } */ }); ``` File attributes can be set on the newly uploaded file by passing the via the `options.fileAttributes` parameter: ``` // Upload a new file and prepopulate the description field var stream = fs.createReadStream('huge.pdf'); var options = { fileAttributes: { description: 'A very large PDF' } }; client.files.getChunkedUploader('12345', 2147483648, 'huge.pdf', stream, options) .then(uploader => uploader.start()) .then(file => { // ... }); ``` ### Manual Process For more complicated upload scenarios, such as those being coordinated across multiple processes or when an unrecoverable error occurs with the automatic uploader, the endpoints for chunked upload operations are also exposed directly. For example, this is roughly how a chunked upload is done manually: ``` // Upload a 2GB file "huge.pdf" into folder 12345 var parts = []; var hash = crypto.createHash('sha1'); client.files.createUploadSession( '12345', 2147483648, 'huge.pdf', function(err, session) { if (err) { // handle error return; } var sessionID = session.upload_session_id; // for each part in order, given `part` and `offset`... hash.update(part); client.files.uploadPart( sessionID, part, offset, 2147483648, null, function(err, partData) { if (err) { // handle error return; } parts.push(partData.part); } ); // once all parts have been uploaded... client.files.commitUploadSession(sessionID, hash.digest('base64'), {parts: parts}, callback); } ); ``` The individual endpoint methods are detailed below: #### Create Upload Session To start a chunked upload, create an upload session for the file by calling [`files.createUploadSession(folderID, size, name, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#createUploadSession) with the ID of the folder to upload into, as well as the size and file name of file being uploaded. This will check the destination folder for conflicts before starting the upload and pass the information for the upload session back to the callback. ``` // Create a session to upload a 2GB file "huge.pdf" into folder 12345 client.files.createUploadSession('12345', 2147483648, 'huge.pdf', callback); ``` #### Upload Part Parts are then uploaded by calling [`files.uploadPart(sessionID, part, offset, totalSize, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#uploadPart) with the ID of the upload session that was created, a `Buffer` containing the part of the file starting at `offset`, and the total size of the file being uploaded. When the upload of a part succeeds, the callback will be called with a part record, which should be stored for later integrity checking. ``` // Upload the part starting at byte offset 8388608 to upload session '93D9A837B45F' with part ID 'feedbeef' client.files.uploadPart('93D9A837B45F', part, 8388608, 2147483648, {part_id: 'feedbeef'}, callback); ``` #### Commit Upload Session Once all parts of the file have been uploaded, finalize the upload by calling [`files.commitUploadSession(sessionID, fileHash, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#commitUploadSession) with the upload session ID and the base64-encoded SHA1 hash of the entire file. This will complete the upload and create the full file in the destination folder. Any valid file object attributes you want to assign to the newly-created file may be passed via the `options` parameter. See the [File object documentation](https://developer.box.com/en/reference/resources/file/) for more details. If you stored a list of part records for each uploaded part, you can pass them via `options.parts` for additional integrity checking. Otherwise, the API will assume that the list of parts is has received is the intended set. ``` // Finalize upload session 93D9A837B45F client.files.commitUploadSession( '93D9A837B45F', fileHash.digest('base64'), {description: 'A file I uploaded in chunks!'}, callback ); ``` #### Abort Upload Session An in-progress upload session may be destroyed, along with all parts already uploaded, by calling [`files.abortUploadSession(sessionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#abortUploadSession). This operation cannot be undone. ``` // Cancel upload session 93D9A837B45F client.files.abortUploadSession('93D9A837B45F', callback); ``` #### Get Upload Session Parts The list of parts successfully uploaded to an in-progress upload session can be retrieved by calling [`files.getUploadSessionParts(sessionID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getUploadSessionParts). The list is returned as a paged collection using the `limit` and `offset` options. ``` // Get the list of parts already uploaded client.files.getUploadSessionParts('93D9A837B45F', {limit: 100}, callback); ``` #### Get Upload Session Status Information about an in-progress upload session can be retrieved by calling [`files.getUploadSession(sessionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getUploadSession). ``` // Get info about upload session 93D9A837B45F client.files.getUploadSessionStatus('93D9A837B45F', callback); ``` ## Upload Preflight Check The Preflight Check in the [`files.preflightUploadFile(parentFolderID, fileData, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#preflightUploadFile) method will verify that a file will be accepted by Box before you send all the bytes over the wire. Preflight checks verify all permissions as if the file was actually uploaded including: - Folder upload permission - File name collisions - File size caps - Folder and file name restrictions - Folder and account storage quota A successful response does not guarantee that your upload call will succeed, but in practice it has been shown to reduce failed uploads by more than 99%. Highly active folders, common filenames, and accounts near their quota limits may get a success for the preflight, and then have a real conflict during the actual upload. ``` // Verify that uploading a 200MB file named "Preso.ppt" to folder 12345 would succeed client.files.preflightUploadFile( '12345', { name: 'Preso.ppt', size: 200000000 }, null, callback ); ``` For uploading a new version of a file, use the [`files.preflightUploadNewFileVersion(fileID, fileData, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#preflightUploadNewFileVersion) method. ``` // Check if uploading a larger version of this file will succeed client.files.preflightUploadNewFileVersion('87646', {size: 300000000}, null, callback); ``` ## Move a File To move a file from one folder to another, call [`files.move(fileID, newParentID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#move) with the ID of the file to move and the ID of the folder to move it to. ``` // Move file 12345 to folder 9876 client.files.move('12345', '9876', callback); ``` ## Copy a File A file can be copied to a new folder with the [`files.copy(fileID, newParentID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#copy) method. ``` var fileID = '11111'; var destinationFolderID = '22222'; client.files.copy(fileID, destinationFolderID) .then(fileCopy => { /* fileCopy -> { type: 'file', id: '11112', file_version: { type: 'file_version', id: '99999', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' }, sequence_id: '0', etag: '0', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', name: 'My File.pdf', description: '', size: 68431, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, { type: 'folder', id: '22222', sequence_id: null, etag: null, name: 'Personal Files' } ] }, created_at: '2017-05-16T15:18:02-07:00', modified_at: '2017-05-16T15:18:02-07:00', trashed_at: null, purged_at: null, content_created_at: '2017-05-16T15:18:02-07:00', content_modified_at: '2017-05-16T15:18:02-07:00', created_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, shared_link: null, parent: { type: 'folder', id: '22222', sequence_id: null, etag: null, name: 'Personal Files' } item_status: 'active' } */ }); ``` An optional `name` parameter can also be passed to rename the file on copy. This can be used to avoid a name conflict when there is already an item with the same name in the target folder. ``` client.files.copy('12345', '0', {name: 'Renamed file.png'}, callback); ``` You can specify specific file version to copy by passing optional `version` parameter. ``` client.files.copy('12345', '0', {version: '1'}, callback); ``` ## Delete a File Calling the [`files.delete(fileID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#delete) method will move the file to the user's trash. ``` client.files.delete('12345') .then(() => { // deletion succeeded — no value returned }); ``` If you want to ensure that your deletion does not overwrite any other updates (i.e. to prevent against possible race conditions), you can pass the last known value of the file's `etag` field via the `etag` option; this will generate an error if the file was modified between when you read that `etag` value and when the deletion is processed by the API. ``` client.files.delete('11111', { etag: '5' }) .then(() => { // File successfully deleted }) .catch(err => { if (err.statusCode === 412) { // Precondition failed — the file was modified before the deletion was processed // Read the file again to ensure it is safe to delete and then retry } }); ``` ## Get File Versions Retrieve a list of previous versions of a file by calling the [`files.getVersions(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getVersions). ``` client.files.getVersions('12345') .then(versions => { /* versions -> { total_count: 1, entries: [ { type: 'file_version', id: '22222', sha1: '359c6c1ed98081b9a69eb3513b9deced59c957f9', name: 'script.js', size: 92556, created_at: '2012-08-20T10:20:30-07:00', modified_at: '2012-11-28T13:14:58-08:00', modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } ] } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` // Only get information about a few specific fields. client.files.getVersions('12345', {fields: 'name,size,sha1'}) .then(versions => { /* versions -> { total_count: 1, entries: [ { type: 'file_version', id: '22222', sha1: '359c6c1ed98081b9a69eb3513b9deced59c957f9', name: 'script.js', size: 92556 } ] } */ }); ``` ## Upload a New Version of a File New versions of a file can be uploaded with the [`files.uploadNewFileVersion(fileID, content, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#uploadNewFileVersion) method. ``` var fs = require('fs'); var stream = fs.createReadStream('/path/to/file.pdf'); client.files.uploadNewFileVersion('11111', stream) .then(file => { /* file -> { total_count: 1, entries: [ { type: 'file', id: '11111', file_version: { type: 'file_version', id: '22222', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' }, sequence_id: '0', etag: '0', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', name: 'My File.pdf', description: '', size: 68431, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_at: '2017-05-16T15:18:02-07:00', modified_at: '2017-05-16T15:18:02-07:00', trashed_at: null, purged_at: null, content_created_at: '2017-05-16T15:18:02-07:00', content_modified_at: '2017-05-16T15:18:02-07:00', created_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, shared_link: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } item_status: 'active' } ] } */ }) ``` If the stream passed in is not an fs stream, you must pass the stream length as an optional parameter as shown below. To rename the file on upload or manually specify a modification timestamp for the file, pass the corresponding optional parameter: ``` var fs = require('fs'); var stream = fs.createReadStream('/path/to/file.pdf'); var options = { name: 'New filename.pdf', content_modified_at: '2016-02-15T22:42:09-0600', content_length: 5 }; client.files.uploadNewFileVersion('11111', stream, options) .then(file => { /* file -> { total_count: 1, entries: [ { type: 'file', id: '11111', file_version: { type: 'file_version', id: '22222', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' }, sequence_id: '0', etag: '0', sha1: '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', name: 'New filename.pdf', description: '', size: 68431, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_at: '2017-05-16T15:18:02-07:00', modified_at: '2017-05-16T15:18:02-07:00', trashed_at: null, purged_at: null, content_created_at: '2017-05-16T15:18:02-07:00', content_modified_at: '2016-02-15T22:42:09-0600', created_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Test User', login: 'test@example.com' }, shared_link: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } item_status: 'active' } ] } */ }) ``` ## Download a Previous Version of a File For users with premium accounts, previous versions of a file can be downloaded by calling [`files.getReadStream(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getReadStream) with `options.version` specified. ``` var fs = require('fs'); client.files.getReadStream('12345', {version: '2'}, function(error, stream) { if (error) { // handle error } // write the file version to disk var output = fs.createWriteStream('/path/to/file'); stream.pipe(output); }); ``` ## Delete a Previous File Version An old version of a file can be moved to the trash by calling the [`files.deleteVersion(fileID, versionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#deleteVersion) method. ``` var fileID = '11111'; var versionID = '22222'; client.files.deleteVersion(fileID, versionID) .then(() => { // deletion succeeded — no value returned }); ``` If you want to ensure that your deletion does not overwrite any other updates (i.e. to prevent against possible race conditions), you can pass the last known value of the file's `etag` field via the `etag` option; this will generate an error if the file was modified between when you read that `etag` value and when the deletion is processed by the API. ``` var fileID = '11111'; var versionID = '22222'; client.files.deleteVersion(fileID, versionID, { etag: '5' }) .then(() => { // File version successfully deleted }) .catch(err => { if (err.statusCode === 412) { // Precondition failed — the file was modified before the deletion was processed // Read the file again to ensure it is safe to delete and then retry } }); ``` ## Find a File for a Shared Link To find a file given a shared link, use the [`sharedItems.get(url, password, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SharedItems.html#get) method. ``` client.sharedItems.get( 'https://app.box.com/s/gjasdasjhasd', 'letmein' ),then(file => { //... }); ``` ## Create or update a Shared Link To create or update a shared link for a file use [`files.update(fileID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#update) method, passing a new `shared_link` value in the `updates` parameter: ``` client.files.update('12345', { shared_link: { access: "open", password: "do-not-use-this-password", unshared_at: "2022-12-12T10:53:43-08:00", vanity_name: "my-shared-link", permissions: { can_view: true, can_download: true, can_edit: true } } }).then(file => { // ... }) ``` This will make a shared link to be `open` to everyone, but users will need to provide `password` to access the file. This link will be unshared at `"2022-12-12T10:53:43-08:00"`. By setting `vanity_name` we create custom URL `https://app.box.com/v/my-shared-link`. Custom URLs should not be used when sharing sensitive content as vanity URLs are a lot easier to guess than regular shared links. Additionally, everyone who has this link can `view`, `download` and `edit` the file. You can create shared link using default values ``` client.files.update('12345', { shared_link: {} }).then(file => { // ... }) ``` - Default `access` value comes from the access level specified by the enterprise admin. - Default `password`, `unshared_at`, `vanity_name` will be empty. - Default `permissions` comes from the values specified by the enterprise admin. You can remove any field set on a link by sending value `null` (or empty object when it comes to `permissions`). This will cause it's value to be default. For example, let's remove `access` and `permissions`: ``` client.files.update('12345', { shared_link: { access: null, permissions: {} } }).then(file => { // ... }) ``` This will remove `open` access, and it will fall back to default value set by the enterprise admin. The `permissions` we set on a shared link will be removed and default permissions defined by the enterprise admin will be applied. Other properties of the shared link will not be changed as we are not sending them. ## Get a Shared Link To check for an existing shared link on a file, inspect the `shared_link` field on a file object. This object, when present, contains a `unicode` string containing the shared link URL. ``` client.files.get('11111', { fields: 'shared_link' }) .then(file => { let url = file.shared_link.download_url //... }) ``` ## Get information about Shared Link Permissions Options To check what permissions can be set on a shared link you can ask for `shared_link_permission_options`: ``` client.files.get('11111', { fields: 'shared_link_permission_options' }) .then(file => { let options = file.shared_link_permission_options // options = [ "can_download", "can_preview", "can_edit" ] }) ``` Allowed values are defined by the enterprise admin in "Enterprise Settings -> Content & Sharing -> Actions link recipients can take", possible values are `["can_preview"]`, `["can_preview", "can_download"]` or `["can_preview", "can_download", "can_edit"]`. ## Remove a Shared Link A shared link for a file can be removed calling [`files.update(fileID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#update) with `null` for the `shared_link` value. ``` client.files.update('12345', { shared_link: null }).then(file => { // ... }) ``` ## Promote Version Promote file version to the top of the stack by calling the [`files.promoteVersion(fileID, versionID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#promoteVersion) method. ``` var fileID = '11111'; var versionID = '22222'; client.files.promoteVersion(fileID, versionID) .then(version => { /* version -> { type: 'file_version', id: '33333', sha1: '12039d6dd9a7e6eefc78846802e', name: 'Stark Family Lineage.pptx', size: 37934912, created_at: '2013-11-20T13:20:50-08:00', modified_at: '2013-11-20T13:26:48-08:00', modified_by: { type: 'user', id: '44444', name: 'Eddard Stark', login: 'ned@winterfell.example.com' } } */ }); ``` ## Get Embed Link An embed link for a file can be generated by calling the [`files.getEmbedLink(fileID,callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getEmbedLink) method. Embed link is an expiring URL for embedding a Box file preview into a webpage, usually via an `<iframe>` element. For more information, see the [API documentation](https://developer.box.com/en/reference/resources/file/#param-expiring_embed_link). ``` client.files.getEmbedLink('12345') .then(embedURL => { // embedURL -> "https://app.box.com/preview/expiring_embed/..." }); ``` ## Lock a File A file can be locked, which prevents other users from editing the file, by calling the [`files.lock(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#lock) method You may optionally prevent other users from downloading the file, as well as set an expiration time for the lock. ``` var options = { expires_at: '2018-12-12T10:55:30-08:00', is_download_prevented: false } client.files.lock('11111', options) .then(file => { /* file -> { type: 'file', id: '11111', etag: '2', lock: { type: 'lock', id: '22222', created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2017-03-06T22:00:53-08:00', expires_at: '2018-12-12T10:55:30-08:00', is_download_prevented: false } } */ }); ``` ## Unlock a File A file can be unlocked by calling the [`files.unlock(fileID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#unlock) method. ``` client.files.unlock('11111') .then(file => { /* file -> { type: 'file', id: '11111', etag: '2', lock: null } */ }); ``` ## Get Representation Info A file's representation info can be retrieved by calling [`files.getRepresentationInfo(fileID, representationTypes, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getRepresentationInfo). You will be able to fetch information regarding PDF representation, thumbnail representation, multi-page images representation, and extracted text representation. ``` client.files.getRepresentationInfo('67890', client.files.representation.THUMBNAIL) .then(representations => { /* representations -> { entries: [ { content: { url_template: 'https://dl.boxcloud.com/.../{+asset_path}' }, info: { url: 'https://api.box.com/2.0/...' }, properties: { dimensions: '320x320', paged: 'false', thumb: 'true' }, representation: 'jpg', status: { state: 'success' } } ] } */ }); ``` You can specify your own set of representations to get info for by manually constructing the [X-Rep-Hints value](https://developer.box.com/en/reference/get-files-id/#param-X-Rep-Hints) and passing it as `representationTypes`. ``` client.files.getRepresentationInfo('67890', '[pdf][extracted_text]') .then(representations => { // ... }); ``` Setting the `generateRepresentations` option to `true` will automatically poll the status of all specified representations to generate them. ``` client.files.getRepresentationInfo('67890', '[pdf][extracted_text]', { generateRepresentations: true }) .then(representations => { // All representations should be generated // ... }); ``` ## Get Representation Content To get a stream over the contents of a single file representation, call the [`files.getRepresentationContent(fileID, representationType, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getRepresentationContent) method with the ID of the file and an [X-Rep-Hints value](https://developer.box.com/en/reference/get-files-id/#param-X-Rep-Hints) specifying the representation you want. **Note:** This method only supports getting the contents of a single representation; if your X-Rep-Hints value specifies multiple representations, the stream will be for an arbitrary one of them. ``` client.files.getRepresentationContent('12345', client.files.representation.PDF) .then(function(stream) { stream.on('data', function(chunk) { // read data from the stream }); }); ``` For representations with multiple files, e.g. multi-page images, you will need to pass an `assetPath` option to specify which file you want to fetch. ``` // If file 12345 is a document, its PNG representation will consist of one image per page of the document // Get the image of the first page of the document client.files.getRepresentationContent('12345', '[png?dimensions=1024x1024]', { assetPath: '1.png' }) .then(function(stream) { stream.on('data', function(chunk) { // read data from the stream }); }); ``` ## Create a Zip File Calling [`files.createZip(name, items, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#createZip) will let you create a new zip file with the specified name and with the specified items and will return a response with the download and status link. This file does not show up in your Box account, but will be temporarily available for download. ``` var name = 'test', items = [ { type: 'file', id: '466239504569' }, { type: 'folder', id: '466239504580' } ]; client.files.createZip(name, items) .then(zip => { /* zip -> { "download_url": "https://api.box.com/2.0/zip_downloads/124hfiowk3fa8kmrwh/content", "status_url": "https://api.box.com/2.0/zip_downloads/124hfiowk3fa8kmrwh/status", "expires_at": "2018-04-25T11:00:18-07:00", "name_conflicts": [ [ { "id": "100", "type": "file", "original_name": "salary.pdf", "download_name": "aqc823.pdf" }, { "id": "200", "type": "file", "original_name": "salary.pdf", "download_name": "aci23s.pdf" } ], [ { "id": "1000", "type": "folder", "original_name": "employees", "download_name": "3d366a_employees" }, { "id": "2000", "type": "folder", "original_name": "employees", "download_name": "3aa6a7_employees" } ] ] } */ }); ``` ## Download a Zip File Calling [`file.downloadZip(name, items, stream, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#downloadZip) will let you create a new zip file with the specified name and with the specified items and download it to the stream that is passed in. The return object is status object that contains information about the download, including whether it was successful. The created zip file does not show up in your Box account. ``` var name = 'test', items = [ { type: 'file', id: '466239504569' }, { type: 'folder', id: '466239504580' } ], stream = new Readable(); client.files.downloadZip(name, items, stream) .then(status => { /* status -> { "total_file_count": 20, "downloaded_file_count": 10, "skipped_file_count": 10, "skipped_folder_count": 10, "state": "succeeded" } */ }); ``` --- ## Untitled *Type: page* Information Barrier Segments Information barrier segments (or just segments) are defined groups of users. They are different from user… # Information Barrier Segments Information barrier segments (or just segments) are defined groups of users. They are different from user groups, however, because with segments, a user can be a member of one, and only one, segment. This requirement for uniqueness in segments also means that you can add only individual users to segments, not user groups. [Information Barrier Segments](#information-barrier-segments) - [Get shield information barrier segment with specified ID](#get-shield-information-barrier-segment-with-specified-id) - [List shield information barrier segments](#list-shield-information-barrier-segments) - [Create shield information barrier segment](#create-shield-information-barrier-segment) - [Update shield information barrier segment](#update-shield-information-barrier-segment) - [Delete shield information barrier segment](#delete-shield-information-barrier-segment) ## Get shield information barrier segment with specified ID To get a shield information barrier segment based on provided ID by, call the [`shieldInformationBarrierSegments.getById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentsManager.html#getById) method. ``` const barrierSegment = await client.shieldInformationBarrierSegments.getById({ shield_information_barrier_segment_id: '12345', }); console.log(`Shield information barrier segment id ${barrierSegment.id}`); ``` ## List shield information barrier segments To retrieve a list of shield information barrier segment objects for the specified Information Barrier ID, call the [`shieldInformationBarrierSegments.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentsManager.html#getAll) method. ``` const result = await client.shieldInformationBarrierSegments.getAll({ shield_information_barrier_id: '123' }); console.log(`There are ${result.entries.length} shield information barrier segments`); ``` ## Create shield information barrier segment To create a shield information barrier segment, call the [`shieldInformationBarrierSegments.create(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentsManager.html#create) method. The `name` and `shield_information_barrier` fields are required in the body, and the description is optional. ``` const barrierSegment = await client.shieldInformationBarrierSegments.create({ name: 'barrier segment name', description: 'barrier segment description', shield_information_barrier: { id: '123', type: 'shield_information_barrier' }, }); console.log(`Shield information barrier segment id ${barrierSegment.id} created`); ``` ## Update shield information barrier segment Updates the shield information barrier segment based on provided ID by calling [`shieldInformationBarrierSegments.update(body, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentsManager.html#update) method. ``` const barrierSegment = await client.shieldInformationBarrierSegments.update({ name: 'updated name', description: 'updated description', }, { shield_information_barrier_segment_id: '12345' }); console.log(`Shield information barrier segment id ${barrierSegment.id} updated`); ``` ## Delete shield information barrier segment To delete the shield information barrier segment based on provided ID, call the [`shieldInformationBarrierSegments.delete(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentsManager.html#deleteById) method. ``` await client.shieldInformationBarrierSegments.deleteById({ shield_information_barrier_segment_id: '12345' }); ``` --- ## Untitled *Type: page* Information Barriers Get shield information barrier with specified ID Get all shield information barriers Update shield information barrier… # Information Barriers - [Get shield information barrier with specified ID](#get-shield-information-barrier-with-specified-id) - [Get all shield information barriers](#get-all-shield-information-barriers) - [Update shield information barrier status](#update-shield-information-barrier-status) - [Create shield information barrier](#create-shield-information-barrier) ## Get shield information barrier with specified ID Get shield information barrier based on provided ID by [`shieldInformationBarriers.getById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierManager.html#getById) method. ``` const barrier = await client.shieldInformationBarriers.getById({ shield_information_barrier_id: 12345, }); console.log( `Shield information barrier id ${barrier.id}` ); ``` ## Get all shield information barriers Retrieves a list of shield information barrier objects for the enterprise of JWT by [`shieldInformationBarriers.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierManager.html#getAll) method. ``` const result = await client.shieldInformationBarriers.getAll(); console.log(`There are ${result.entries.length} shield information barriers`); ``` ## Update shield information barrier status Change status of shield information barrier with the specified ID. [`shieldInformationBarriers.changeStatusById(body, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierManager.html#changeStatusById) method. ``` const barrier = await client.shieldInformationBarriers.changeStatusById({ id: 12345, status: 'pending', }); console.log( `Shield information barrier id ${barrier.id} status is ${barrier.status}` ); ``` ## Create shield information barrier Creates a shield information barrier to separate individuals/groups within the same firm and prevents confidential information passing between them.[`shieldInformationBarriers.create(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierManager.html#create) method. ``` const barrier = await client.shieldInformationBarriers.create({ enterprise: { id: '12345', type: 'enterprise', }, }); console.log( `Shield information barrier id ${barrier.id} created` ); ``` --- ## Untitled *Type: page* Information Barrier Segment Restrictions Information Barrier Segment Restrictions Get shield information barrier segment restriction by ID… # Information Barrier Segment Restrictions [Information Barrier Segment Restrictions](#information-barrier-segment-restrictions) - [Get shield information barrier segment restriction by ID](#get-shield-information-barrier-segment-restriction-by-id) - [List shield information barrier segment restrictions](#list-shield-information-barrier-segment-restrictions) - [Create shield information barrier segment restriction](#create-shield-information-barrier-segment-restriction) - [Delete shield information barrier segment restriction by ID](#delete-shield-information-barrier-segment-restriction-by-id) ## Get shield information barrier segment restriction by ID To retrieve a shield information barrier segment restriction by its ID, call the [`shieldInformationBarrierSegmentRestrictions.getById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentRestrictionsManager.html#getById) method. ``` const barrierSegmentRestriction = await client.shieldInformationBarrierSegmentRestrictions.getById({ shield_information_barrier_segment_restriction_id: '12345', }); console.log(`Shield information barrier segment restriction id ${barrierSegmentRestriction.id}`); ``` ## List shield information barrier segment restrictions To retrieves a list of shield information barrier segment restrictions based on provided segment ID, call the [`shieldInformationBarrierSegmentRestrictions.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentRestrictionsManager.html#getAll) method. ``` const result = await client.shieldInformationBarrierSegmentRestrictions.getAll({ shield_information_barrier_segment_id: '123' }); console.log(`There are ${result.entries.length} shield information barrier segment restrictions`); ``` ## Create shield information barrier segment restriction To creates a new shield information barrier segment restriction, call the [`shieldInformationBarrierSegmentRestrictions.create(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentRestrictionsManager.html#create) method. As a body parameter, you need to pass an object with the properties: `type`, `shield_information_barrier_segment` and `restricted_segment`, like in the following example: ``` const barrierSegmentRestriction = await client.shieldInformationBarrierSegmentRestrictions.create({ type: 'shield_information_barrier_segment_restriction', shield_information_barrier_segment: { type: 'shield_information_barrier_segment', id: '1910967' }, restricted_segment: { type: 'shield_information_barrier_segment', id: '1910968' } }); console.log(`Shield information barrier segment restriction with id ${barrierSegmentRestriction.id} was created`); ``` ## Delete shield information barrier segment restriction by ID To delete the shield information barrier segment restriction based on provided ID, call the [`shieldInformationBarrierSegmentRestrictions.delete(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/ShieldInformationBarrierSegmentRestrictionsManager.html#deleteById) method. ``` await client.shieldInformationBarrierSegmentRestrictions.deleteById({ shield_information_barrier_segment_restriction_id: '12345' }); ``` --- ## Untitled *Type: page* Integration mappings With integration mappings, you can manage where content from partner apps is stored in Box. It is well suited for… # Integration mappings With integration mappings, you can manage where content from partner apps is stored in Box. It is well suited for situations in which a particular Slack channel already has a corresponding folder in Box and allows to map it for uploads instead of using the automatically created folder within the default structure. For more details on Slack mapping please see the [Box as the Content Layer for Slack](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). [Integration mappings](#integration-mappings) - [List Slack integration mappings](#list-slack-integration-mappings) - [Create Slack integration mapping](#create-slack-integration-mapping) - [Update Slack integration mapping](#update-slack-integration-mapping) - [Delete Slack integration mapping](#delete-slack-integration-mapping) ## List Slack integration mappings To get a list of all Slack integration mappings, call the [`integrationMappings.getSlackIntegrationMappings(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/IntegrationMappingsManager.html#getSlackIntegrationMappings) method. ``` const integrationMappings = await client.integrationMappings.getSlackIntegrationMappings(); console.log(`There are ${integrationMappings.entries.length} Slack integration mappings`); ``` The API gives you an option to filter the mappings by passing additional parameters. For example, if you want to get all integration mappings that are mapped to specific folder, you just need to pass the `box_item_id` param like below: ``` const integrationMappings = await client.integrationMappings.getSlackIntegrationMappings({box_item_id: '123'}); ``` On the other hand, if you want to get the mapping that is mapped to specific Slack channel, just pass the `partner_item_id` param, like below: ``` const integrationMappings = await client.integrationMappings.getSlackIntegrationMappings({partner_item_id: 'C12378991223'}); ``` If you want however to get all manually created mappings, you should pass the `is_manually_created` parameter set to true, like this: ``` const integrationMappings = await client.integrationMappings.getSlackIntegrationMappings({is_manually_created: true}); ``` ## Create Slack integration mapping To create a Slack integration mapping by mapping a Slack channel to a Box item, call the [`integrationMappings.createSlackIntegrationMapping(body, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/IntegrationMappingsManager.html#createSlackIntegrationMapping) method. To correctly create the mapping, `partner_item` and `box_item` properties need to be passed in the body of the request. In the `partner_item`, you specify the mapping for the Slack, where `id` is the ID of the channel, `type` should be always `channel` and either `slack_org_id` or `slack_workspace_id` should be passed. The `box_item` represents the mapping for Box, where `id` is the ID of the folder and `type` should be always set to `folder`. ``` const mapping = await client.integrationMappings.createSlackIntegrationMapping({ partner_item: { type: 'channel', id: 'C12378991223', slack_org_id: 'E1234567' }, box_item: { id: '12345', type: 'folder', } }); console.log( `Slack integration mapping with id ${mapping.id} was created` ); ``` When calling a creation slack integration mapping request, you may get response with `400` status code and description like that: ``` Box as File Storage for Slack (user id: 123, user email: AutomationUser_456@boxdevedition.com) must be a collaborator in role co-owner or the owner of the folder 789, before it can be mapped to the channel XYZ. Please create a collaboration or ensure the ownership for Box as File Storage for Slack and retry.", ``` In this case, follow the description and add `Box as File Storage for Slack` Service as a collaborator in the role of co-owner role to the folder specified in the mapping. ``` const collaboration = await client.collaborations.createWithUserID('123', '12345', client.collaborationRoles.CO_OWNER); ``` Then call again te request to create the slack integration mapping, which should now succeed. ## Update Slack integration mapping To update a Slack integration mapping, call the [`integrationMappings.updateSlackIntegrationMapping(body, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/IntegrationMappingsManager.html#updateSlackIntegrationMapping) method. You may want to call this method to change the mapping on Box by selecting a different folder or to modify the automatic management of channel member access to the underlying Box item. ``` const mapping = await client.integrationMappings.updateSlackIntegrationMapping({ box_item: { id: '12345', type: 'folder' }, options: { is_access_management_disabled: true } }, { integration_mapping_id: integrationMappingId }); console.log( `Slack integration mapping with id ${mapping.id} was updated` ); ``` ## Delete Slack integration mapping To delete a Slack integration mapping based on provided ID [`integrationMappings.deleteSlackIntegrationMappingById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/IntegrationMappingsManager.html#deleteSlackIntegrationMappingById) method. ``` await client.integrationMappings.deleteSlackIntegrationMappingById({ integration_mapping_id: 123456 }); ``` --- ## Untitled *Type: page* Legal Hold Policies A legal hold policy blocks permanent deletion of content during ongoing litigation. Admins can create legal hold… # Legal Hold Policies A legal hold policy blocks permanent deletion of content during ongoing litigation. Admins can create legal hold policies and then later assign them to specific folders, files, or users. - [Create Legal Hold Policy](#create-legal-hold-policy) - [Get Legal Hold Policy](#get-legal-hold-policy) - [Update Legal Hold Policy](#update-legal-hold-policy) - [Delete Legal Hold Policy](#delete-legal-hold-policy) - [Get Enterprise Legal Hold Policies](#get-enterprise-legal-hold-policies) - [Get Legal Hold Policy Assignments](#get-legal-hold-policy-assignments) - [Assign Legal Hold Policy](#assign-legal-hold-policy) - [Delete Legal Hold Policy Assignment](#delete-legal-hold-policy-assignment) - [Get Legal Hold Policy Assignment](#get-legal-hold-policy-assignment) - [Get File Version Legal Hold](#get-file-version-legal-hold) - [Get File Version Legal Holds](#get-file-version-legal-holds) ## Create Legal Hold Policy To create a new legal hold policy, call the [`legalHoldPolicies.create(name, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#create) method. ``` client.legalHoldPolicies.create('IRS Audit') .then(policy => { /* policy -> { type: 'legal_hold_policy', id: '11111', policy_name: 'IRS Audit', description: '', status: 'active', assignment_counts: { user: 0, folder: 0, file: 0, file_version: 0 }, is_ongoing: true, created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2017-01-24T16:57:22-08:00', modified_at: '2017-01-24T16:57:22-08:00', deleted_at: null, filter_started_at: null, filter_ended_at: null } */ }); ``` ## Get Legal Hold Policy To retrieve information about a specific legal hold policy, call the [`legalHoldPolicies.get(policyID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#get) method. ``` client.legalHoldPolicies.get('11111') .then(policy => { /* policy -> { type: 'legal_hold_policy', id: '11111', policy_name: 'IRS Audit', description: '', status: 'active', assignment_counts: { user: 1, folder: 0, file: 0, file_version: 0 }, created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2016-05-18T10:28:45-07:00', modified_at: '2016-05-18T11:25:59-07:00', deleted_at: null, filter_started_at: '2016-05-17T01:00:00-07:00', filter_ended_at: '2016-05-21T01:00:00-07:00' } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` client.legalHoldPolicies.get('12345', {fields: 'policy_name,created_at,created_by'}, callback); ``` ## Update Legal Hold Policy To update or modify an existing legal hold policy, call the [`legalHoldPolicies.update(policyID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#update) method where `updates` is the set of key-value pairs to be updated on the policy object. ``` client.legalHoldPolicies.update('11111', {description: 'Documents related to IRS audit'}) .then(policy => { /* policy -> { type: 'legal_hold_policy', id: '11111', policy_name: 'IRS Audit', description: 'Documents related to IRS audit', status: 'active', assignment_counts: { user: 1, folder: 0, file: 0, file_version: 0 }, created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2016-05-18T10:28:45-07:00', modified_at: '2016-05-18T11:25:59-07:00', deleted_at: null, filter_started_at: '2016-05-17T01:00:00-07:00', filter_ended_at: '2016-05-21T01:00:00-07:00' } */ }); ``` ## Delete Legal Hold Policy To delete a legal hold policy, call the [`legalHoldPolicies.delete(policyID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#delete) method. Note that this is an asynchronous process - the policy will not be fully deleted yet when the response comes back. ``` client.legalHoldPolicies.delete('11111') .then(() => { // deletion started — no value returned }); ``` ## Get Enterprise Legal Hold Policies To retrieve all of the legal hold policies for the given enterprise, call the [`legalHoldPolicies.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#getAll) method. ``` client.legalHoldPolicies.getAll({policy_name: 'Important'}) .then(policies => { /* policies -> { entries: [ { type: 'legal_hold_policy', id: '11111', policy_name: 'Important Policy 1' }, { type: 'legal_hold_policy', id: '22222', policy_name: 'Important Policy 2' } ], limit: 100, order: [ { by: 'policy_name', direction: 'ASC' } ] } */ }); ``` ## Get Legal Hold Policy Assignments To get a list of all legal hold policy assignments associated with a specified legal hold policy, call the [`legalHoldPolicies.getAssignments(policyID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#getAssignments) method. ``` client.legalHoldPolicies.getAssignments('8763245', {assign_to_type: 'folder'}) .then(assignments => { /* assignments -> { entries: [ { type: 'legal_hold_policy_assignment', id: '22222' } ], limit: 100, next_marker: 'someMarkerString' } */ }); ``` ## Assign Legal Hold Policy To assign a legal hold policy, call the [`legalHoldPolicies.assign(policyID, assignType, assignID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#assign) method. ``` client.legalHoldPolicies.assign('11111', 'folder', '12345') .then(assignment => { /* assignment -> { type: 'legal_hold_policy_assignment', id: '22222', legal_hold_policy: { type: 'legal_hold_policy', id: '11111', policy_name: 'IRS Audit' }, assigned_to: { type: 'folder', id: '12345' }, assigned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, assigned_at: '2016-05-18T17:38:03-07:00', deleted_at: null } */ }); ``` ## Delete Legal Hold Policy Assignment To delete a legal hold assignment and remove a legal hold policy from an item, call the [`legalHoldPolicies.deleteAssignment(assignmentID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#deleteAssignment) method. Note that this is an asynchronous process - the assignment will not be fully deleted yet when the response comes back. ``` client.legalHoldPolicies.deleteAssignment('22222') .then(() => { // deletion started — no value returned }); ``` ## Get Legal Hold Policy Assignment To retrieve information about a legal hold policy assignment, call the [`legalHoldPolicies.getAssignment(assignmentID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#getAssignment) method. ``` client.legalHoldPolicies.getAssignment('22222') .then(assignment => { /* assignment -> { type: 'legal_hold_policy_assignment', id: '22222', legal_hold_policy: { type: 'legal_hold_policy', id: '11111', policy_name: 'IRS Audit' }, assigned_to: { type: 'user', id: '33333' }, assigned_by: { type: 'user', id: '11111', name: 'Example User', login: 'user@example.com' }, assigned_at: '2016-05-18T10:32:19-07:00', deleted_at: null } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` client.legalHoldPolicies.getAssignment('22222', {fields: 'id,assigned_by,assigned_at'}) .then(assignment => { /* assignment -> { type: 'legal_hold_policy_assignment', id: '22222', assigned_by: { type: 'user', id: '11111', name: 'Example User', login: 'user@example.com' }, assigned_at: '2016-05-18T10:32:19-07:00' } */ }); ``` ## Get File Version Legal Hold A file version legal hold is a record for a held file version. To get information for a specific file version legal hold record, call the [`legalHoldPolicies.getFileVersionLegalHold(legalHoldID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#getFileVersionLegalHold) method. ``` client.legalHoldPolicies.getFileVersionLegalHold('55555') .then(fileVersionHold => { /* fileVersionHold -> { type: 'legal_hold', id: '55555', file_version: { type: 'file_version', id: '123456789' }, file: { type: 'file', id: '66666', etag: '1' }, legal_hold_policy_assignments: [ { type: 'legal_hold_policy_assignment', id: '22222' }, { type: 'legal_hold_policy_assignment', id: '33333' } ], deleted_at: null } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` client.legalHoldPolicies.getFileVersionLegalHold('8762345', {fields: 'id,file'}) .then(fileVersionHold => { /* fileVersionHold -> { type: 'legal_hold', id: '55555', file: { type: 'file', id: '66666', etag: '1' } } */ }); ``` ## Get File Version Legal Holds To retrieve a list of all file version legal holds for a given policy, call the [`legalHoldPolicies.getAllFileVersionLegalHolds(policyID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/LegalHoldPolicies.html#getAllFileVersionLegalHolds) method. ``` client.legalHoldPolicies.getAllFileVersionLegalHolds('11111') .then(holds => { /* holds -> { entries: [ { type: 'legal_hold', id: '22222' }, { type: 'legal_hold', id: '33333' }, { type: 'legal_hold', id: '44444' } ], limit: 100, order: [ { by: 'retention_policy_set_id, file_version_id', direction: 'ASC' } ] } */ }); ``` --- ## Untitled *Type: page* Recent Items Recent Items returns information about files that have been accessed by a user not long ago. It keeps track of items that were… # Recent Items Recent Items returns information about files that have been accessed by a user not long ago. It keeps track of items that were accessed either in the last 90 days or the last 1000 items accessed (both conditions must be met). - [Get a User's Recent Items](#get-a-users-recent-items) ## Get a User's Recent Items Get a list of all recent items the user has by calling [`recentItems.get(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RecentItems.html#get). ``` client.recentItems.get({limit: 1000}) .then(recentItems => { /* recentItems -> { next_marker: '', limit: 1000, order: { by: 'interacted_at', direction: 'DESC' }, entries: [ { type: 'recent_item', interaction_type: 'item_preview', interacted_at: '2017-06-06T15:46:28-07:00', item: { type: 'file', id: '11111', file_version: { type: 'file_version', id: '22222', sha1: 'd0a8c75ba72bf923bfb0c855bbcf1e8f7cc817dd' }, sequence_id: '0', etag: '0', sha1: 'd0a8c75ba72bf923bfb0c855bbcf1e8f7cc817dd', name: 'File2.txt' }, interaction_shared_link: "https://app.box.com/s/27jtnq2g8b7bu30pivpbz6nb2ef47mfs" }, { type: 'recent_item', interaction_type: 'item_preview', interacted_at: '2017-06-06T15:46:27-07:00', item: { type: 'file', id: '33333', file_version: { type: 'file_version', id: '44444', sha1: '12a715416bc96ba3ea860480c815657d5e0809da' }, sequence_id: '0', etag: '0', sha1: '12a715416bc96ba3ea860480c815657d5e0809da', name: 'Image1.png' }, interaction_shared_link: null } ] } */ }); ``` --- ## Untitled *Type: page* Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of… # Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of key:value pairs that belong to files/folders. For example, an important contract may have key:value pairs of `"clientNumber":"820183"` and `"clientName":"bioMedicalCorp"`. Metadata that belongs to a file/folder is grouped by templates. Templates allow the metadata service to provide a multitude of services, such as pre-defining sets of key:value pairs or schema enforcement on specific fields. Each file/folder can have multiple distinct template instances associated with it, and templates are also grouped by scopes. Currently, the only scopes support are `enterprise` and `global`. Enterprise scopes are defined on a per enterprises basis, whereas global scopes are Box application-wide. In addition to `enterprise` scoped templates, every file on Box has access to the `global` `properties` template. The Properties template is a bucket of free form key:value string pairs, with no additional schema associated with it. Properties are ideal for scenarios where applications want to write metadata to file objects in a flexible way, without pre-defined template structure. - [Create Metadata Template](#create-metadata-template) [Get Metadata Template](#get-metadata-template) - [Get by template scope and key](#get-by-template-scope-and-key) - [Get by ID](#get-by-id) [Update Metadata Template](#update-metadata-template) [Get Enterprise Metadata Templates](#get-enterprise-metadata-templates) [Delete Metadata Template](#delete-metadata-template) [Set Metadata on a File](#set-metadata-on-a-file) [Get Metadata on a File](#get-metadata-on-a-file) [Remove Metadata from a File](#remove-metadata-from-a-file) [Set Metadata on a Folder](#set-metadata-on-a-folder) [Get Metadata on a Folder](#get-metadata-on-a-folder) [Remove Metadata from a Folder](#remove-metadata-from-a-folder) [Create Cascade Policy](#create-cascade-policy) [Get Cascade Policy](#get-cascade-policy) [Get All Cascade Policies For a Folder](#get-all-cascade-policies-for-a-folder) [Force Apply Cascade Policy](#force-apply-cascade-policy) [Delete Cascade Policy](#delete-cascade-policy) [Query](#query) ## Create Metadata Template To create a new metadata template, call the [`metadata.createTemplate(templateName, fields, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#createTemplate) method. ``` // Create a new template, but hide it for now until it's ready for use client.metadata.createTemplate( 'Vendor Contract', [ { type: 'date', key: 'signed', displayName: 'Date Signed' }, { type: 'string', key: 'vendor', displayName: 'Vendor' }, { type: 'enum', key: 'fy', displayName: 'Fiscal Year', options: [ {key: 'FY17'}, {key: 'FY18'}, {key: 'FY19'} ] } ], { hidden: true, templateKey: 'vcontract', copyInstanceOnItemCopy: false } ) .then(template => { /* template -> { id: '17f2d715-6acb-45f2-b96a-28b15efc9faa', templateKey: 'vcontract', scope: 'enterprise_12345', displayName: 'Vendor Contract', hidden: true, copyInstanceOnItemCopy: false, fields: [ { type: 'date', key: 'signed', displayName: 'Date Signed', hidden: false }, { type: 'string', key: 'vendor', displayName: 'Vendor', hidden: false }, { type: 'enum', key: 'fy', displayName: 'Fiscal Year', options: [ { key: 'FY17' }, { key: 'FY18' }, { key: 'FY19' } ], hidden: false } ] } */ }); ``` ## Get Metadata Template ### Get by template scope and key To retrieve a specific metadata template by its scope and template key, call the [`metadata.getTemplateSchema(scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#getTemplateSchema) method with the scope and template key. ``` client.metadata.getTemplateSchema('enterprise', 'vcontract') .then(template => { /* template -> { id: '17f2d715-6acb-45f2-b96a-28b15efc9faa', templateKey: 'vcontract', scope: 'enterprise_12345', displayName: 'Vendor Contract', hidden: true, fields: [ { type: 'date', key: 'signed', displayName: 'Date Signed', hidden: false }, { type: 'string', key: 'vendor', displayName: 'Vendor', hidden: false }, { type: 'enum', key: 'fy', displayName: 'Fiscal Year', options: [ { key: 'FY17' }, { key: 'FY18' }, { key: 'FY19' } ], hidden: false } ] } */ }); ``` ### Get by ID To get a specific metadata template by its ID, call the [`metadata.getTemplateByID(templateID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#getTemplateByID) method with the ID of the template. ``` client.metadata.getTemplateByID('17f2d715-6acb-45f2-b96a-28b15efc9faa') .then(template => { /* template -> { id: '17f2d715-6acb-45f2-b96a-28b15efc9faa', templateKey: 'vcontract', scope: 'enterprise_12345', displayName: 'Vendor Contract', hidden: true, fields: [ { type: 'date', key: 'signed', displayName: 'Date Signed', hidden: false }, { type: 'string', key: 'vendor', displayName: 'Vendor', hidden: false }, { type: 'enum', key: 'fy', displayName: 'Fiscal Year', options: [ { key: 'FY17' }, { key: 'FY18' }, { key: 'FY19' } ], hidden: false } ] } */ }); ``` ## Update Metadata Template To update a metadata template, call the [`metadata.updateTemplate(scope, template, operations, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#updateTemplate) method with the operations to perform on the template. See the [API Documentation](https://developer.box.com/en/reference/put-metadata-templates-id-id-schema/) for more information on the operations available. ``` // Add a new option to the Fiscal Year field, and un-hide the template var operations = [ { op: 'addEnumOption', fieldKey: 'fy', data: { key: 'FY20' } }, { op: 'editTemplate', data: { hidden: false } } ]; client.metadata.updateTemplate('enterprise', 'vcontract', operations) .then(template => { /* template -> { templateKey: 'vcontract', scope: 'enterprise_12345', displayName: 'Vendor Contract', hidden: false, fields: [ { type: 'date', key: 'signed', displayName: 'Date Signed', hidden: false }, { type: 'string', key: 'vendor', displayName: 'Vendor', hidden: false }, { type: 'enum', key: 'fy', displayName: 'Fiscal Year', options: [ { key: 'FY17' }, { key: 'FY18' }, { key: 'FY19' }, { key: 'FY20' } ], hidden: false } ] } */ }); ``` ## Get Enterprise Metadata Templates Get all metadata templates for the current enterprise and scope by calling the [`metadata.getTemplates(scope, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#getTemplates) method. ``` client.metadata.getTemplates('enterprise') .then(templates => { /* templates -> { limit: 100, entries: [ { templateKey: 'documentFlow', scope: 'enterprise_12345', displayName: 'Document Flow', hidden: false, fields: [ { type: 'string', key: 'currentDocumentStage', displayName: 'Current Document Stage', hidden: false } { type: 'string', key: 'needsApprovalFrom', displayName: 'Needs Approval From', hidden: false }, { type: 'string', key: 'nextDocumentStage', displayName: 'Next Document Stage', hidden: false } { type: 'float', key: 'maximumDaysAllowedInCurrentStage', displayName: 'Maximum Days Allowed In Current Stage', hidden: false } { templateKey: 'marketingCollateral', scope: 'enterprise_12345', displayName: 'Marketing Collateral', hidden: false, fields: [ { type: 'string', key: 'audience1', displayName: 'Audience', hidden: false }, { type: 'string', key: 'previousState', displayName: 'Previous State', hidden: false } ] }, { templateKey: 'productInfo', scope: 'enterprise_12345', displayName: 'Product Info', hidden: false, fields: [ { type: 'float', key: 'skuNumber', displayName: 'SKU Number', hidden: false }, { type: 'enum', key: 'department', displayName: 'Department', hidden: false, options: [ { key: 'Beauty' }, { key: 'Shoes' }, { key: 'Accessories' }, { key: 'Clothing' }, { key: 'Handbags' }, { key: 'Bedding' }, { key: 'Watches' } ] }, { type: 'date', key: 'displayDate', displayName: 'Display Date', hidden: false } ] } ], next_marker: null, prev_marker: null } */ }); ``` Similarly, to get all metadata templates that are available to all enterprises use the `global` scope. ``` client.metadata.getTemplates('global') .then(templates => { // ... }); ``` ## Delete Metadata Template To delete a metadata template call the [`metadata.deleteTemplate(scope, template, callback)`](http://opensoure.box.com/box-node-sdk/Metadata.html#deleteTemplate) method with the template scope and template name. ``` client.metadata.deleteTemplate('enterprise', 'testtemplate', callback); ``` ## Set Metadata on a File To set metadata on a file, call [`files.setMetadata(fileID, scope, template, metadata, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#setMetadata) with the scope and template key of the metadata template, as well as an `Object` containing the metadata keys and values to set. **Note:** This method will unconditionally apply the provided metadata, overwriting existing metadata for the keys provided. To specifically create or update metadata, see the `addMetadata()` and `updateMetadata()` methods below. ``` var metadataValues = { audience: "internal", documentType: "Q1 plans", competitiveDocument: "no", status: "active", author: "Jones", currentState: "proposal" }; client.files.setMetadata('11111', client.metadata.scopes.ENTERPRISE, "marketingCollateral", metadataValues) .then(metadata => { /* metadata -> { audience: 'internal', documentType: 'Q1 plans', competitiveDocument: 'no', status: 'active', author: 'Jones', currentState: 'proposal', '$type': 'marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe', '$parent': 'file_11111', '$id': '2094c584-68e1-475c-a581-534a4609594e', '$version': 0, '$typeVersion': 0, '$template': 'marketingCollateral', '$scope': 'enterprise_12345' } */ }); ``` To add new metadata to a file, call [`files.addMetadata(fileID, scope, template, metadata, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#addMetadata) with a metadata template and an object of key/value pairs to add as metadata. **Note:**: This method will only succeed if the provided metadata template is not current applied to the file, otherwise it will fail with a Conflict error. ``` var metadataValues = { audience: "internal", documentType: "Q1 plans", competitiveDocument: "no", status: "active", author: "Jones", currentState: "proposal" }; client.files.addMetadata('11111', client.metadata.scopes.ENTERPRISE, "marketingCollateral", metadataValues) .then(metadata => { /* metadata -> { audience: 'internal', documentType: 'Q1 plans', competitiveDocument: 'no', status: 'active', author: 'Jones', currentState: 'proposal', '$type': 'marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe', '$parent': 'file_11111', '$id': '2094c584-68e1-475c-a581-534a4609594e', '$version': 0, '$typeVersion': 0, '$template': 'marketingCollateral', '$scope': 'enterprise_12345' } */ }); ``` Update a file's existing metadata by calling [`files.updateMetadata(fileID, scope, template, patch, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#updateMetadata) with an array of [JSON Patch](http://jsonpatch.com/) formatted operations. **Note:** This method will only succeed if the provided metadata template has already been applied to the file; if the file does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know the file will already have metadata applied, since it will save an API call compared to `setMetadata()`. ``` var updates = [ { op: 'test', path: '/competitiveDocument', value: 'no' }, { op: 'remove', path: '/competitiveDocument' }, { op: 'test', path: '/status', value: 'active' }, { op: 'replace', path: '/status', value: 'inactive' }, { op: 'test', path: '/author', value: 'Jones' }, { op: 'copy', from: '/author', path: '/editor' }, { op: 'test', path: '/currentState', value: 'proposal' }, { op: 'move', from: '/currentState', path: '/previousState' }, { op: 'add', path: '/currentState', value: 'reviewed' } ]; client.files.updateMetadata('11111', client.metadata.scopes.ENTERPRISE, "marketingCollateral", updates) .then(metadata => { /* metadata -> { audience: 'internal', documentType: 'Q1 plans', status: 'inactive', author: 'Jones', '$type': 'marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe', '$parent': 'file_11111', '$id': '2094c584-68e1-475c-a581-534a4609594e', '$version': 1, '$typeVersion': 0, editor: 'Jones', previousState: 'proposal', currentState: 'reviewed', '$template': 'marketingCollateral', '$scope': 'enterprise_12345' } */ }); ``` ## Get Metadata on a File Retrieve a specific metadata template on a file by calling [`files.getMetadata(fileID, scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getMetadata) with the ID of the file and which template to fetch. ``` client.files.getMetadata('11111', client.metadata.scopes.ENTERPRISE, 'marketingCollateral') .then(metadata => { /* metadata -> { audience: 'internal', documentType: 'Q1 plans', competitiveDocument: 'no', status: 'active', author: 'Jones', currentState: 'proposal', '$type': 'marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe', '$parent': 'file_11111', '$id': '2094c584-68e1-475c-a581-534a4609594e', '$version': 0, '$typeVersion': 0, '$template': 'marketingCollateral', '$scope': 'enterprise_12345' } */ }); ``` You can retrieve all metadata on a file by calling [`files.getAllMetadata(fileID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getAllMetadata). ``` client.files.getAllMetadata('11111') .then(metadata => { /* metadata -> { entries: [ { currentDocumentStage: 'Init', '$type': 'documentFlow-452b4c9d-c3ad-4ac7-b1ad-9d5192f2fc5f', '$parent': 'file_11111', '$id': '50ba0dba-0f89-4395-b867-3e057c1f6ed9', '$version': 4, '$typeVersion': 2, needsApprovalFrom: 'Smith', '$template': 'documentFlow', '$scope': 'enterprise_12345' }, { '$type': 'productInfo-9d7b6993-b09e-4e52-b197-e42f0ea995b9', '$parent': 'file_11111', '$id': '15d1014a-06c2-47ad-9916-014eab456194', '$version': 2, '$typeVersion': 1, skuNumber: 45334223, description: 'Watch', '$template': 'productInfo', '$scope': 'enterprise_12345' }, { Popularity: '25', '$type': 'properties', '$parent': 'file_11111', '$id': 'b6f36cbc-fc7a-4eda-8889-130f350cc057', '$version': 0, '$typeVersion': 2, '$template': 'properties', '$scope': 'global' } ], limit: 100 } */ }); ``` ## Remove Metadata from a File A metadata template can be removed from a file by calling [`files.deleteMetadata(fileID, scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#deleteMetadata). ``` client.files.deleteMetadata('67890', client.metadata.scopes.GLOBAL, client.metadata.templates.PROPERTIES) .then(() => { // removal succeeded — no value returned });; ``` ## Set Metadata on a Folder To set metadata on a folder, call [`folders.setMetadata(folderID, scope, template, metadata, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#setMetadata) with the scope and template key of the metadata template, as well as an `Object` containing the metadata keys and values to set. **Note:** This method will unconditionally apply the provided metadata, overwriting existing metadata for the keys provided. To specifically create or update metadata, see the `addMetadata()` and `updateMetadata()` methods below. ``` var metadataValues = { audience: "internal", documentType: "Q1 plans", competitiveDocument: "no", status: "active", author: "Jones", currentState: "proposal" }; client.folders.setMetadata('11111', client.metadata.scopes.ENTERPRISE, "marketingCollateral", metadataValues) .then(metadata => { /* metadata -> { audience: 'internal', documentType: 'Q1 plans', competitiveDocument: 'no', status: 'active', author: 'Jones', currentState: 'proposal', '$type': 'marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe', '$parent': 'folder_11111', '$id': '2094c584-68e1-475c-a581-534a4609594e', '$version': 0, '$typeVersion': 0, '$template': 'marketingCollateral', '$scope': 'enterprise_12345' } */ }); ``` To add new metadata to a folder, call [`folders.addMetadata(folderID, scope, template, metadata, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#addMetadata) with a metadata template and an object of key/value pairs to add as metadata. **Note:**: This method will only succeed if the provided metadata template is not current applied to the folder, otherwise it will fail with a Conflict error. ``` var metadataValues = { audience: "internal", documentType: "Q1 plans", competitiveDocument: "no", status: "active", author: "Jones", currentState: "proposal" }; client.folders.addMetadata('11111', client.metadata.scopes.ENTERPRISE, "marketingCollateral", metadataValues) .then(metadata => { /* metadata -> { audience: 'internal', documentType: 'Q1 plans', competitiveDocument: 'no', status: 'active', author: 'Jones', currentState: 'proposal', '$type': 'marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe', '$parent': 'folder_11111', '$id': '2094c584-68e1-475c-a581-534a4609594e', '$version': 0, '$typeVersion': 0, '$template': 'marketingCollateral', '$scope': 'enterprise_12345' } */ }); ``` Update a folder's existing metadata by calling [`folders.updateMetadata(fileID, scope, template, patch, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#updateMetadata) with an array of [JSON Patch](http://jsonpatch.com/) formatted operations. **Note:** This method will only succeed if the provided metadata template has already been applied to the folder; if the folder does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know the folder will already have metadata applied, since it will save an API call compared to `setMetadata()`. ``` var updates = [ { op: 'test', path: '/competitiveDocument', value: 'no' }, { op: 'remove', path: '/competitiveDocument' }, { op: 'test', path: '/status', value: 'active' }, { op: 'replace', path: '/status', value: 'inactive' }, { op: 'test', path: '/author', value: 'Jones' }, { op: 'copy', from: '/author', path: '/editor' }, { op: 'test', path: '/currentState', value: 'proposal' }, { op: 'move', from: '/currentState', path: '/previousState' }, { op: 'add', path: '/currentState', value: 'reviewed' } ]; client.folders.updateMetadata('11111', client.metadata.scopes.ENTERPRISE, "marketingCollateral", updates) .then(metadata => { /* metadata -> { audience: 'internal', documentType: 'Q1 plans', status: 'inactive', author: 'Jones', '$type': 'marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe', '$parent': 'folder_11111', '$id': '2094c584-68e1-475c-a581-534a4609594e', '$version': 1, '$typeVersion': 0, editor: 'Jones', previousState: 'proposal', currentState: 'reviewed', '$template': 'marketingCollateral', '$scope': 'enterprise_12345' } */ }); ``` ## Get Metadata on a Folder Retrieve a specific metadata template on a folder by calling [`folders.getMetadata(folderID, scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#getMetadata) with the ID of the folder and which template to fetch. ``` client.folders.getMetadata('11111', client.metadata.scopes.ENTERPRISE, 'marketingCollateral') .then(metadata => { /* metadata -> { audience: 'internal', documentType: 'Q1 plans', competitiveDocument: 'no', status: 'active', author: 'Jones', currentState: 'proposal', '$type': 'marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe', '$parent': 'folder_11111', '$id': '2094c584-68e1-475c-a581-534a4609594e', '$version': 0, '$typeVersion': 0, '$template': 'marketingCollateral', '$scope': 'enterprise_12345' } */ }); ``` You can retrieve all metadata on a folder by calling [`folders.getAllMetadata(folderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#getAllMetadata). ``` client.folders.getAllMetadata('11111') .then(metadata => { /* metadata -> { entries: [ { currentDocumentStage: 'Init', '$type': 'documentFlow-452b4c9d-c3ad-4ac7-b1ad-9d5192f2fc5f', '$parent': 'folder_11111', '$id': '50ba0dba-0f89-4395-b867-3e057c1f6ed9', '$version': 4, '$typeVersion': 2, needsApprovalFrom: 'Smith', '$template': 'documentFlow', '$scope': 'enterprise_12345' }, { '$type': 'productInfo-9d7b6993-b09e-4e52-b197-e42f0ea995b9', '$parent': 'folder_11111', '$id': '15d1014a-06c2-47ad-9916-014eab456194', '$version': 2, '$typeVersion': 1, skuNumber: 45334223, description: 'Watch', '$template': 'productInfo', '$scope': 'enterprise_12345' }, { Popularity: '25', '$type': 'properties', '$parent': 'folder_11111', '$id': 'b6f36cbc-fc7a-4eda-8889-130f350cc057', '$version': 0, '$typeVersion': 2, '$template': 'properties', '$scope': 'global' } ], limit: 100 } */ }); ``` ## Remove Metadata from a Folder A folder's metadata can be removed by calling [`folders.deleteMetadata(folderID, scope, template, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#deleteMetadata). ``` client.folders.deleteMetadata('67890', client.metadata.scopes.GLOBAL, client.metadata.templates.PROPERTIES) .then(() => { // removal succeeded — no value returned }); ``` ## Create Cascade Policy To set a metadata cascade policy, which applies metadata values on a folder to new items in the folder, call [`metadata.createCascadePolicy(scope, templateKey, folderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#createCascadePolicy) with the scope and template key of the metadata template to be cascaded, and the ID of the folder to apply the policy to. ``` var folderID = '22222'; client.metadata.createCascadePolicy('enterprise', 'testTemplate', folderID) .then(cascadePolicy => { /* cascadePolicy -> { id: '84113349-794d-445c-b93c-d8481b223434', type: 'metadata_cascade_policy', owner_enterprise: { type: 'enterprise', id: '11111' }, parent: { type: 'folder', id: '22222' }, scope: 'enterprise_11111', templateKey: 'testTemplate' } */ }); ``` ## Get Cascade Policy To retrieve information about a specific metadata cascade policy, call [`metadata.getCascadePolicy(policyID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#getCascadePolicy) with the ID of the cascade policy. ``` var policyID = '84113349-794d-445c-b93c-d8481b223434'; client.metadata.getCascadePolicy(policyID) .then(cascadePolicy => { /* cascadePolicy -> { id: '84113349-794d-445c-b93c-d8481b223434', type: 'metadata_cascade_policy', owner_enterprise: { type: 'enterprise', id: '11111' }, parent: { type: 'folder', id: '22222' }, scope: 'enterprise_11111', templateKey: 'testTemplate' } */ }); ``` ## Get All Cascade Policies For a Folder To get a list of all cascade policies for a folder, which show the metadata templates that are being applied to all items in that folder, call [`metadata.getCascadePolicies(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#getCascadePolicies) with the ID of the folder. You can set the `owner_enterprise_id` option to retrieve only cascade policies owned by a specific enterprise (defaults to the current enterprise). ``` var folderID = '22222'; client.metadata.getCascadePolicies(folderID) .then(cascadePolicies => { /* cascadePolicies -> { limit: 100, entries: [ { id: '84113349-794d-445c-b93c-d8481b223434', type: 'metadata_cascade_policy', owner_enterprise: { type: 'enterprise', id: '11111' }, parent: { type: 'folder', id: '22222' }, scope: 'enterprise_11111', templateKey: 'testTemplate' } ], next_marker: null, prev_marker: null } */ }); ``` ## Force Apply Cascade Policy To force apply a metadata cascade policy and apply metadata values to all existing items in the affected folder, call [`metadata.forceApplyCascadePolicy(policyID, resolutionMethod, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#forceApplyCascadePolicy) with the ID of the cascade policy to force apply and the conflict resolution method for dealing with items that already have a metadata value that conflicts with the folder. Specifying a resolution value of `'none'` will preserve the existing values on items, and specifying `'overwrite'` will overwrite values on the items in the folder with the metadata value from the folder. ``` var policyID = '84113349-794d-445c-b93c-d8481b223434'; client.metadata.forceApplyCascadePolicy(policyID, client.metadata.cascadeResolution.PRESERVE_EXISTING) .then(() => { // application started — no value returned }); ``` ## Delete Cascade Policy To remove a cascade policy and stop applying metadata from a folder to items in the folder, call [`metadata.deleteCascadePolicy(policyID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#deleteCascadePolicy) with the ID of the cascade policy to delete. ``` var policyID = '84113349-794d-445c-b93c-d8481b223434'; client.metadata.deleteCascadePolicy(policyID) .then(() => { // deletion succeeded — no value returned }); ``` ## Query To query Box items based on their metadata, call [`metadata.query(from, ancestorFolderId, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Metadata.html#query) with the metadata template and the folder ID to restrain the query. Additional options like a specific query, a marker, etc. can be passed in through the options object. **Important**: One of two possible response types are returned, based on whether the fields parameter is passed into the options parameter or not. The example directly below shows the response if the fields parameter is not passed in. ``` var from = 'enterprise_12345.someTemplate', ancestorFolderId = '5555', options = { query: 'amount >= :arg', query_params: { arg: 100 }, order_by: [ { field_key: 'amount', direction: 'asc' } ], limit: 100, marker: 'AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff' }; client.metadata.query(from, ancestorFolderId, options) .then(items => { /* items -> { "entries": [ { "item": { "type": "file", "id": "1617554169109", "file_version": { "type": "file_version", "id": "1451884469385", "sha1": "69888bb1bff455d1b2f8afea75ed1ff0b4879bf6" }, "sequence_id": "0", "etag": "0", "sha1": "69888bb1bff455d1b2f8afea75ed1ff0b4879bf6", "name": "My Contract.docx", "description": "", "size": 25600, "path_collection": { "total_count": 4, "entries": [ { "type": "folder", "id": "0", "sequence_id": null, "etag": null, "name": "All Files" }, { "type": "folder", "id": "15017998644", "sequence_id": "0", "etag": "0", "name": "Contracts" }, { "type": "folder", "id": "15286891196", "sequence_id": "1", "etag": "1", "name": "North America" }, { "type": "folder", "id": "16125613433", "sequence_id": "0", "etag": "0", "name": "2017" } ] }, "created_at": "2017-04-20T12:55:27-07:00", "modified_at": "2017-04-20T12:55:27-07:00", "trashed_at": null, "purged_at": null, "content_created_at": "2017-01-06T17:59:01-08:00", "content_modified_at": "2017-01-06T17:59:01-08:00", "created_by": { "type": "user", "id": "193973366", "name": "Box Admin", "login": "admin@company.com" }, "modified_by": { "type": "user", "id": "193973366", "name": "Box Admin", "login": "admin@company.com" }, "owned_by": { "type": "user", "id": "193973366", "name": "Box Admin", "login": "admin@company.com" }, "shared_link": null, "parent": { "type": "folder", "id": "16125613433", "sequence_id": "0", "etag": "0", "name": "2017" }, "item_status": "active" }, "metadata": { "enterprise_12345": { "someTemplate": { "$parent": "file_161753469109", "$version": 0, "customerName": "Phoenix Corp", "$type": "someTemplate-3d5fcaca-f496-4bb6-9046-d25c37bc5594", "$typeVersion": 0, "$id": "ba52e2cc-371d-4659-8d53-50f1ac642e35", "amount": 100, "claimDate": "2016-04-10T00:00:00Z", "region": "West", "$typeScope": "enterprise_123456" } } } } ], "next_marker": "" } */ }); ``` This second example shows the response if the fields parameter is passed in. ``` var from = 'enterprise_12345.someTemplate', ancestorFolderId = '5555', options = { query: 'amount >= :arg', query_params: { arg: 100 }, order_by: [ { field_key: 'amount', direction: 'asc' } ], fields: [ "id", "name", "sha1", "metadata.enterprise12345.someTemplate.amount" ] limit: 100, marker: 'AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff' }; client.metadata.query(from, ancestorFolderId, options) .then(items => { /* items -> { "entries":[ { "type": "file", "id": "1617554169109", "sha1": "69888bb1bff455d1b2f8afea75ed1ff0b4879bf6", "name": "My Contract.docx", "metadata": { "enterprise_12345": { "someTemplate": { "$parent": "file_161753469109", "$version": 0, "$type": "someTemplate-3d5fcaca-f496-4bb6-9046-d25c37bc5594", "$typeVersion": 0, "$id": "ba52e2cc-371d-4659-8d53-50f1ac642e35", "amount": 100, "$typeScope": "enterprise_123456" } } } } ], "next_marker":"" } */ }); ``` --- ## Untitled *Type: page* Search Search for Content Search for Content To get a list of items matching a search query, call the search.query(searchQuery, options… # Search - [Search for Content](#search-for-content) ## Search for Content To get a list of items matching a search query, call the [`search.query(searchQuery, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Search.html#query) method. There are many possible options for advanced search filtering, which are documented in the [Search API Reference](https://developer.box.com/en/guides/search/). ``` // Search for PDF or Word documents matching "Mobile" client.search.query( 'Mobile', { fields: 'name,modified_at,size,extension,permissions,sync_state', file_extensions: 'pdf,doc', limit: 200, offset: 0 }) .then(results => { /* results -> { total_count: 1, entries: [ { type: 'file', id: '11111', sequence_id: '1', etag: '1', sha1: 'f89d97c5eea0a68e2cec911s932eca34a52355d2', name: 'Box for Sales - Empowering Your Mobile Worker White paper 2pg (External).pdf', description: '', size: 408979, path_collection: { total_count: 2, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Marketing Active Work' } ] }, created_at: '2014-05-17T12:59:45-07:00', modified_at: '2014-05-17T13:00:20-07:00', trashed_at: null, purged_at: null, content_created_at: '2014-05-17T12:58:58-07:00', content_modified_at: '2014-05-17T12:58:58-07:00', created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, shared_link: null, parent: { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Marketing Active Work' }, item_status: 'active' } ], limit: 200, offset: 0 } */ }); ``` ``` // Search for all Powerpoint presentations with the TopSecret metadata applied client.search.query( '', { file_extensions: 'ppt,pptx', mdfilters: [ { templateKey: 'TopSecret', scope: 'enterprise', filters: {} } ] }) .then(results => { // ... }); ``` --- ## Untitled *Type: page* Shared Items Shared Items represent files and folders on Box accessed via a shared link. Get a Shared Item Get a Shared Item To get the file… # Shared Items Shared Items represent files and folders on Box accessed via a shared link. - [Get a Shared Item](#get-a-shared-item) ## Get a Shared Item To get the file or folder information for a shared link, call the [`sharedItems.get(url, password, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SharedItems.html#get) method. The `password` parameter should be passed as a `null` value if none is required. ``` client.sharedItems.get( 'https://app.box.com/s/1a2b3c4d5e', null, {fields: 'type,id,parent,extension,shared_link'}, callback ); ``` --- ## Untitled *Type: page* Sign Requests Get sign request by ID List sign requests Create sign request Cancel sign request Resend sign request Get sign request by ID… # Sign Requests - [Get sign request by ID](#get-sign-request-by-id) - [List sign requests](#list-sign-requests) - [Create sign request](#create-sign-request) - [Cancel sign request](#cancel-sign-request) - [Resend sign request](#resend-sign-request) ## Get sign request by ID Gets a sign request by ID [`signRequests.getById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SignRequestsManager.html#getById) method. ``` const sr = await client.signRequests.getById({ sign_request_id: 12345, }); console.log( `Sign request id ${sr.id} contains ${sr.source_files.length} files` ); ``` ## List sign requests Gets sign requests created by a user [`signRequests.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SignRequestsManager.html#getAll) method. ``` const result = await client.signRequests.getAll(); console.log(`There are ${result.count} sign requests`); ``` ## Create sign request Creates a sign request. This involves preparing a document for signing and sending the sign request to signers. [`signRequests.create(body, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SignRequestsManager.html#create) method. The list of source files is currently limited to ten files. Only the ID and type fields are required for each file. ``` const signRequest = await client.signRequests.create({ signers: [ { role: 'signer', email: 'user@example.com', }, ], source_files: [ { type: 'file', id: '12345', }, ], parent_folder: { type: 'folder', id: '1234567', }, }); console.log(`Created a new sign request id ${signRequest.id}`); ``` ## Cancel sign request Cancels a sign request [`signRequests.cancelById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SignRequestsManager.html#cancelById) method. ``` const signRequest = await client.signRequests.cancelById({ sign_request_id: 12345, }); console.log(`Sign request id ${sr.id} cancelled`); ``` ## Resend sign request Resends a sign request email to all outstanding signers [`signRequests.resendById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SignRequestsManager.html#resendById) method. ``` const id = 12345; await client.signRequests.resendById({ sign_request_id: id }); console.log(`Sign request id ${sr.id} resent`); ``` --- ## Untitled *Type: page* Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention… # Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console. - [Create Retention Policy](#create-retention-policy) - [Get Retention Policy](#get-retention-policy) - [Update Retention Policy](#update-retention-policy) - [Get Enterprise Retention Policies](#get-enterprise-retention-policies) - [Get Retention Policy Assignments](#get-retention-policy-assignments) - [Assign Retention Policy](#assign-retention-policy) - [Get Retention Policy Assignment](#get-retention-policy-assignment) - [Delete Retention Policy Assignment](#delete-retention-policy-assignment) - [Get File Version Retention](#get-file-version-retention) - [Get File Version Retentions](#get-file-version-retentions) ## Create Retention Policy To create a new retention policy, call the [`retentionPolicies.create(name, type, action, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#create) method. ``` client.retentionPolicies.create( 'Tax Documents', client.retentionPolicies.policyTypes.INDEFINITE, client.retentionPolicies.dispositionActions.REMOVE_RETENTION) ).then(policy => { /* policy -> { type: 'retention_policy', id: '123456789', policy_name: 'Tax Documents', policy_type: 'indefinite', retention_length: 'indefinite', retention_type: 'modifiable', description: 'Policy to retain all reports', disposition_action: 'remove_retention', can_owner_extend_retention: false, status: 'active', are_owners_notified: true, custom_notification_recipients: [] assignment_counts: { enterprise: 0, folder: 1, metadata_template: 0 }, created_by: { type: 'user', id: '11111', name: 'Example User', login: 'user@example.com' }, created_at: '2015-05-01T11:12:54-07:00', modified_at: '2015-06-08T11:11:50-07:00' } */ }); ``` ## Get Retention Policy To retrieve information about a specific retention policy, call the [`retentionPolicies.get(policyID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#get) method. ``` client.retentionPolicies.get('123456789').then((policy) => { /* policy -> { type: 'retention_policy', id: '123456789', policy_name: 'Tax Documents', policy_type: 'indefinite', retention_length: 'indefinite', retention_type: 'modifiable', description: 'Policy to retain all reports', disposition_action: 'remove_retention', can_owner_extend_retention: false, status: 'active', are_owners_notified: true, custom_notification_recipients: [] assignment_counts: { enterprise: 0, folder: 1, metadata_template: 0 }, created_by: { type: 'user', id: '11111', name: 'Example User', login: 'user@example.com' }, created_at: '2015-05-01T11:12:54-07:00', modified_at: '2015-06-08T11:11:50-07:00' } */ }); ``` ## Update Retention Policy To update or modify an existing retention policy, call the [`retentionPolicies.update(policyID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#update) method where `updates` is the set of key-value pairs to be updated on the policy object. ``` client.retentionPolicies .update('123456789', { status: 'retired' }) .then((policy) => { /* policy -> { type: 'retention_policy', id: '123456789', policy_name: 'Tax Documents', policy_type: 'indefinite', retention_length: 'indefinite', retention_type: 'modifiable', description: 'Policy to retain all reports', disposition_action: 'remove_retention', can_owner_extend_retention: false, status: 'retired', are_owners_notified: true, custom_notification_recipients: [] assignment_counts: { enterprise: 0, folder: 1, metadata_template: 0 }, created_by: { type: 'user', id: '11111', name: 'Example User', login: 'user@example.com' }, created_at: '2015-05-01T11:12:54-07:00', modified_at: '2015-06-08T11:11:50-07:00' } */ }); ``` ## Get Enterprise Retention Policies To retrieve all of the retention policies for the given enterprise, call the [`retentionPolicies.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#getAll) method. ``` client.retentionPolicies.getAll({ policy_name: 'Tax' }).then((policies) => { /* policies -> { entries: [ { type: 'retention_policy', id: '123456789', name: 'Tax Documents' } ], limit: 100, next_marker: 'someMarkerString' } */ }); ``` ## Get Retention Policy Assignments To get a list of all retention policy assignments associated with a specified retention policy, call the [`retentionPolicies.getAssignments(policyID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#getAssignments) method. ``` client.retentionPolicies .getAssignments('123456789', { type: 'folder' }) .then((assignments) => { /* assignments -> { entries: [ { type: 'retention_policy_assignment', id: '12345678' } ], limit: 100, next_marker: 'someMarkerString' } */ }); ``` ## Assign Retention Policy To assign a retention policy, call the [`retentionPolicies.assign(policyID, assignType, assignID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#assign) method. If assigning to an `enterprise`, no `assignID` should be provided. ``` client.retentionPolicies .assign('11111', 'folder', '22222') .then((assignment) => { /* assignment -> { type: 'retention_policy_assignment', id: '12345', retention_policy: { type: 'retention_policy', id: '11111', policy_name: 'Tax Documents' }, assigned_to: { type: 'folder', id: '22222' }, assigned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, assigned_at: '2015-07-20T14:28:09-07:00' } */ }); ``` ``` client.retentionPolicies.assign('98726345', 'enterprise', null, callback); ``` You can also assign a retention policy to a metadata template, with optional field filters. This will attach the retention policy to any items that have the specified metadata template applied. If the `filter_fields` option is provided, the retention policy will only apply to items with the specified value in the metadata field. **Note:** Currently, only one filter field can be specified, and only enum metadata fields are supported at this time. ``` var policyID = '1234'; // metadata template is specified by ID var metadataTemplate = 'cff6f515-5a92-4dca-b4b3-e401ef97cf76'; var options = { filter_fields: [ { // fields and enum values are specified by ID field: '7475b170-3d5e-4dec-b617-9cfd35ae1ecd', value: '59157d60-6fec-419c-b0cc-506391ff51b8', }, ], }; client.retentionPolicies .assign( policyID, client.retentionPolicies.assignmentTypes.METADATA, metadataTemplate, options ) .then((assignment) => { /* assignment -> { type: 'retention_policy_assignment', id: '12345', retention_policy: { type: 'retention_policy', id: '11111', policy_name: 'Tax Documents' }, assigned_to: { type: 'metadata_template', id: 'cff6f515-5a92-4dca-b4b3-e401ef97cf76' }, filter_fields: [ { field: '7475b170-3d5e-4dec-b617-9cfd35ae1ecd', value: '59157d60-6fec-419c-b0cc-506391ff51b8' } ] assigned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, assigned_at: '2015-07-20T14:28:09-07:00', start_date_field: 'upload_date' } */ }); ``` ## Get Retention Policy Assignment To retrieve information about a retention policy assignment, call the [`retentionPolicies.getAssignment(assignmentID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#getAssignment) method. ``` client.retentionPolicies.getAssignment('12345').then((assignment) => { /* assignment -> { type: 'retention_policy_assignment', id: '12345', retention_policy: { type: 'retention_policy', id: '11111', policy_name: 'Tax Documents' }, assigned_to: { type: 'folder', id: '22222' }, assigned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, assigned_at: '2015-07-20T14:28:09-07:00' } */ }); ``` ## Delete Retention Policy Assignment To delete a retention policy assignment, call the [`retentionPolicies.deleteAssignment(assignmentID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#deleteAssignment) method. ``` client.retentionPolicies.deleteAssignment('12345') .then(() => { // deletion succeeded — no value returned }); ``` ## Get File Version Retention A file version retention is a record for a retained file version. To get information for a specific file version retention record, call the [`retentionPolicies.getFileVersionRetention(retentionID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#getFileVersionRetention) method. ``` client.retentionPolicies.getFileVersionRetention('55555').then((retention) => { /* retention -> { type: 'file_version_retention', id: '55555', applied_at: '2015-08-06T22:02:24-07:00', disposition_at: '2016-08-06T21:45:28-07:00', winning_retention_policy: { type: 'retention_policy', id: '11111', policy_name: 'Tax Documents' }, file_version: { type: 'file_version', id: '44444', sha1: '4262d6250b0e6f440dca43a2337bd4621bad9136' }, file: { type: 'file', id: '33333', etag: '2' } } */ }); ``` ## Get File Version Retentions To retrieve a list of all file version retentions for the given enterprise or to filter for some category of file version retention records, call the [`retentionPolicies.getAllFileVersionRetentions(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#getAllFileVersionRetentions) method. Optional filters are passed via the `options` parameter. ``` // Get only the retention records set to delete items before a certain date var options = { disposition_action: client.retentionPolicies.dispositionActions.PERMANENTLY_DELETE, disposition_before: '2038-01-01T12:34:56-08:00', }; client.retentionPolicies .getAllFileVersionRetentions(options) .then((retentions) => { /* retentions -> { entries: [ { type: 'file_version_retention', id: '112725' }, { type: 'file_version_retention', id: '112729' }, { type: 'file_version_retention', id: '112733' } ], limit: 100, order: [ { by: 'file_version_id', direction: 'ASC' } ] } */ }); ``` ## Get Files Under Retention For Assignment To retrieve information about files under retention, call the [`retentionPolicies.getFilesUnderRetentionForAssignment(assignmentID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#getFilesUnderRetentionForAssignment) method. ``` client.retentionPolicies .getFilesUnderRetentionForAssignment('12345') .then((files) => { /* files -> { entries: [ { id: 12345, etag: 1, type: 'file', sequence_id: 3, name: 'Contract.pdf', sha1: '85136C79CBF9FE36BB9D05D0639C70C265C18D37', file_version: { id: 123456, type: 'file_version', sha1: '134b65991ed521fcfe4724b7d814ab8ded5185dc', }, applied_at: '2012-12-12T10:53:43-08:00' } ], limit: 1000, marker: 'some marker' } */ }); ``` ## Get File Versions Under Retention For Assignment To retrieve information about files under retention, call the [`retentionPolicies.getFileVersionUnderRetentionForAssignment(assignmentID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/RetentionPolicies.html#getFileVersionUnderRetentionForAssignment) method. ``` client.retentionPolicies .getFilesVersionUnderRetentionForAssignment('12345') .then((fileVersions) => { /* fileVersions -> { entries: [ { id: 123456, etag: 1, type: 'file_version', sequence_id: 3, name: 'Contract.pdf', sha1: '85136C79CBF9FE36BB9D05D0639C70C265C18D37', file_version: { id: 1234567, type: 'file_version', sha1: '134b65991ed521fcfe4724b7d814ab8ded5185dc', }, applied_at: '2012-12-12T10:53:43-08:00' } ], limit: 1000, marker: 'some marker' } */ }); ``` --- ## Untitled *Type: page* Tasks Tasks enable file-centric workflows in Box. User can create tasks on files and assign them to collaborators on Box. Create a Task Get… # Tasks Tasks enable file-centric workflows in Box. User can create tasks on files and assign them to collaborators on Box. - [Create a Task](#create-a-task) - [Get a Task's Information](#get-a-tasks-information) - [Update a Task](#update-a-task) - [Delete a Task](#delete-a-task) - [Get Assignments for a Task](#get-assignments-for-a-task) - [Get Task Assignment](#get-task-assignment) - [Assign Task](#assign-task) - [Update Task Assignment](#update-task-assignment) - [Remove Task Assignment](#remove-task-assignment) - [Get Tasks on a File](#get-tasks-on-a-file) ## Create a Task To create a task call the [`tasks.create(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#create) method. ``` var options = { message: 'Please review for publication!', due_at: '2014-04-03T11:09:43-07:00' }; client.tasks.create('22222', options) .then(task => { /* task -> { type: 'task', id: '11111', item: { type: 'file', id: '22222', sequence_id: '0', etag: '0', sha1: '0bbd79a105c504f99573e3799756debba4c760cd', name: 'box-logo.png' }, due_at: '2014-04-03T11:09:43-07:00', action: 'review', message: 'Please review for publication!', task_assignment_collection: { total_count: 0, entries: [] }, is_completed: false, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2013-04-03T11:12:54-07:00' } */ }); ``` ## Get a Task's Information To get a task information call the [`tasks.get(taskID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#get) method. ``` client.tasks.get('11111') .then(task => { /* task -> { type: 'task', id: '11111', item: { type: 'file', id: '22222', sequence_id: '0', etag: '0', sha1: '0bbd79a105c504f99573e3799756debba4c760cd', name: 'box-logo.png' }, due_at: '2014-04-03T11:09:43-07:00', action: 'review', message: 'Please review for publication!', task_assignment_collection: { total_count: 0, entries: [] }, is_completed: false, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2013-04-03T11:12:54-07:00' } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` client.tasks.get('11111', {fields: 'message,is_completed'}) .then(task => { /* task -> { type: 'task', id: '11111', message: 'Please review for publication!', is_completed: false } */ }); ``` ## Update a Task To update a task call the [`tasks.update(taskID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#update) method with the set of fields to update and their new values. ``` client.tasks.update('11111', { message: 'Could you please review?' }) .then(task => { /* task -> { type: 'task', id: '11111', item: { type: 'file', id: '22222', sequence_id: '0', etag: '0', sha1: '0bbd79a105c504f99573e3799756debba4c760cd', name: 'box-logo.png' }, due_at: '2014-04-03T11:09:43-07:00', action: 'review', message: 'Could you please review?', task_assignment_collection: { total_count: 0, entries: [] }, is_completed: false, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2013-04-03T11:12:54-07:00' } */ }); ``` ## Delete a Task To delete a task, call the [`tasks.delete(taskID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#delete) method with the ID of the task to be deleted. ``` client.tasks.delete('11111') .then(() => { // deletion succeeded — no value returned }); ``` ## Get Assignments for a Task To get a list of assignments for a task, which associate the task to users who must complete it, call the [`tasks.getAssignments(taskID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#getAssignments) method. ``` client.tasks.getAssignments('11111') .then(assignments => { /* assignments -> { total_count: 1, entries: [ { type: 'task_assignment', id: '22222', item: { type: 'file', id: '44444', sequence_id: '0', etag: '0', sha1: '0bbd79a105c504f99573e3799756debba4c760cd', name: 'box-logo.png' }, assigned_to: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } ] } */ }); ``` ## Get Task Assignment To retrieve information about a specific task assignment, call the [`tasks.getAssignment(assignmentID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#getAssignment) method with the ID of the assignment to get. ``` client.tasks.getAssignment('12345') .then(assignment => { /* assignment -> { type: 'task_assignment', id: '12345', item: { type: 'file', id: '33333', sequence_id: '0', etag: '0', sha1: '7840095ee096ee8297676a138d4e316eabb3ec96', name: 'script.js' }, assigned_to: { type: 'user', id: '22222', name: 'Sample Assignee', login: 'assignee@exmaple.com' }, message: null, completed_at: null, assigned_at: '2013-05-10T11:43:41-07:00', reminded_at: null, resolution_state: 'incomplete', assigned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } */ }); ``` ## Assign Task To assign a task to a user, call [`tasks.assignByUserID(taskID, userID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#assignByUserID) or [`tasks.assignByEmail(taskID, email, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#assignByEmail) with the ID of the task to assign and either the ID or login email address of the user to whom the task should be assigned. ``` // Assign task 11111 to user 22222 var taskID = '11111'; var userID = '22222'; client.tasks.assignByUserID(taskID, userID) .then(assignment => { /* assignment -> { type: 'task_assignment', id: '12345', item: { type: 'file', id: '33333', sequence_id: '0', etag: '0', sha1: '7840095ee096ee8297676a138d4e316eabb3ec96', name: 'script.js' }, assigned_to: { type: 'user', id: '22222', name: 'Sample Assignee', login: 'assignee@exmaple.com' }, message: null, completed_at: null, assigned_at: '2013-05-10T11:43:41-07:00', reminded_at: null, resolution_state: 'incomplete', assigned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } */ }); ``` ``` // Assign task 11111 to the user with email address assignee@exmaple.com client.tasks.assignByEmail('11111', 'assignee@example.com') .then(assignment => { // ... }); ``` ## Update Task Assignment To update a task assignment, call the [`tasks.updateAssignment(assignmentID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#updateAssignment) method. This can be used to resolve or complete a task. ``` // Complete a task client.tasks.updateAssignment( '12345', { message: 'Done!', resolution_state: client.tasks.resolutionStates.COMPLETE }) .then(assignment => { /* assignment -> { type: 'task_assignment', id: '12345', item: { type: 'file', id: '33333', sequence_id: '0', etag: '0', sha1: '7840095ee096ee8297676a138d4e316eabb3ec96', name: 'script.js' }, assigned_to: { type: 'user', id: '22222', name: 'Sample Assignee', login: 'assignee@exmaple.com' }, message: 'Done!', completed_at: null, assigned_at: '2013-05-10T11:43:41-07:00', reminded_at: null, resolution_state: 'complete', assigned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } */ }); ``` ``` // Update the task assignment message client.tasks.updateAssignment( '12345', { message: 'This needs some more changes' }) .then(assignment => { // ... }); ``` ## Remove Task Assignment To delete a task assignment, effectively unassigning a user from the task, call the [`tasks.deleteAssignment(assignmentID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Tasks.html#deleteAssignment) method with the ID of the assignment to remove. ``` client.tasks.deleteAssignment('12345') .then(() => { // deletion succeeded — no value returned }); ``` ## Get Tasks on a File Calling the [`files.getTasks(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getTasks) method will retrieve all of the tasks for given file. ``` client.files.getTasks('11111') .then(tasks => { /* tasks -> { total_count: 1, entries: [ { type: 'task', id: '22222', item: { type: 'file', id: '11111', sequence_id: '6', etag: '6', sha1: '81cc829fb8366fcfc108aa6c5a9bde01a6a10c16', name: 'box-logo.png' }, due_at: null } ] } */ }); ``` --- ## Untitled *Type: page* Sign Templates Get sign template by ID List sign templates Get sign template by ID Gets a sign template by ID signTemplates.getById(options… # Sign Templates - [Get sign template by ID](#get-sign-template-by-id) - [List sign templates](#list-sign-templates) ## Get sign template by ID Gets a sign template by ID [`signTemplates.getById(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SignTemplatesManager.html#getById) method. ``` const sr = await client.signTemplates.getById({ template_id: 12345, }); console.log( `Sign template id ${sr.id} contains ${sr.source_files.length} files` ); ``` ## List sign templates Gets sign templates created by a user [`signTemplates.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/SignTemplatesManager.html#getAll) method. ``` const result = await client.signTemplates.getAll(); console.log(`There are ${result.count} sign templates`); ``` --- ## Untitled *Type: page* Users Users represent an individual's account on Box. Get User's Information Get the Current User's Information Get User Avatar Set User… # Users Users represent an individual's account on Box. - [Get User's Information](#get-users-information) - [Get the Current User's Information](#get-the-current-users-information) - [Get User Avatar](#get-user-avatar) - [Set User Avatar](#set-user-avatar) - [Delete User Avatar](#delete-user-avatar) - [Update User](#update-user) - [Delete User](#delete-user) - [Get Email Aliases](#get-email-aliases) - [Add Email Alias](#add-email-alias) - [Delete Email Alias](#delete-email-alias) ## Get User's Information To get a user call the [`users.get(userID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#get) method. ``` client.users.get('33333') .then(user => { /* user -> { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com', created_at: '2012-03-26T15:43:07-07:00', modified_at: '2012-12-12T11:34:29-08:00', language: 'en', space_amount: 5368709120, space_used: 2377016, max_upload_size: 262144000, status: 'active', job_title: 'Employee', phone: '5555555555', address: '555 Office Drive', avatar_url: 'https://app.box.com/api/avatar/deprecated' } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` // Only get information about a few specific fields. client.users.get('123', {fields: 'name,login'}) .then(user => { /* user -> { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } */ }); ``` ## Get the Current User's Information To get the current user call the [`users.get(userID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#get) method with the `CURRENT_USER_ID` constant. ``` client.users.get(client.CURRENT_USER_ID) .then(currentUser => { /* currentUser -> { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com', created_at: '2012-03-26T15:43:07-07:00', modified_at: '2012-12-12T11:34:29-08:00', language: 'en', space_amount: 5368709120, space_used: 2377016, max_upload_size: 262144000, status: 'active', job_title: 'Employee', phone: '5555555555', address: '555 Office Drive', avatar_url: 'https://app.box.com/api/avatar/deprecated' } */ }); ``` ## Get User Avatar Calling [`users.getAvatar(userID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#getAvatar) will yield a `Readable` stream over the bytes of the user's avatar image. ``` client.users.getAvatar('22222') .then(avatarImageStream => { avatarImageStream.on('data', bytes => { // read avatar image bytes }); }); ``` ## Set User Avatar Calling [`users.setAvatar(userID, avatar, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#setAvatar) will set user's avatar with the input file. ``` const fs = require('fs'); var readStream = fs.createReadStream('image.jpg'); client.users.setAvatar('22222', readStream).then(result => { // read avatar urls }); ``` ## Delete User Avatar Calling [`users.deleteAvatar(userID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#deleteAvatar) will delete the user's avatar. ``` client.users.deleteAvatar('22222', () => { console.log('User avatar deleted!'); }); ``` ## Update User To update a user call the [`users.update(userID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#update) method where `updates` contains the fields to update. ``` client.users.update('33333', {name: 'New Name', job_title: 'New Title', phone: '555-1111'}) .then(user => { /* user -> { type: 'user', id: '33333', name: 'New Name', login: 'user@example.com', created_at: '2012-03-26T15:43:07-07:00', modified_at: '2012-12-12T11:34:29-08:00', language: 'en', space_amount: 5368709120, space_used: 2377016, max_upload_size: 262144000, status: 'active', job_title: 'New Title', phone: '555-1111', address: '555 Office Drive', avatar_url: 'https://app.box.com/api/avatar/deprecated' } */ }); ``` To change a user's login email, update the `login` parameter on the user. Note that the new email address must already be added as a verified email alias for the user. ``` client.users.update('33333', { login: 'newemail@example.com' }) .then(user => { /* user -> { type: 'user', id: '33333', name: 'New Name', login: 'newemail@example.com', created_at: '2012-03-26T15:43:07-07:00', modified_at: '2012-12-12T11:34:29-08:00', language: 'en', space_amount: 5368709120, space_used: 2377016, max_upload_size: 262144000, status: 'active', job_title: 'New Title', phone: '555-1111', address: '555 Office Drive', avatar_url: 'https://app.box.com/api/avatar/deprecated' } */ }); ``` ## Delete User To delete a user call the [`users.delete(userID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#delete) method. If the user still has files in their account and the `force` parameter is not sent, an error is returned. ``` client.users.delete('33333') .then(() => { // deletion succeeded — no value returned }); ``` ``` // Delete the user even if they still have files in their account client.users.delete('123', {force: true}) .then(() => { // deletion succeeded — no value returned }); ``` ## Get Email Aliases To get a users email aliases call the [`users.getEmailAliases(userID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#getEmailAliases) method. ``` client.users.getEmailAliases('33333') .then(emailAliases => { /* emailAliases -> { total_count: 2, entries: [ { type: 'email_alias', id: '1234', is_confirmed: true, email: 'user+foo@example.com' }, { type: 'email_alias', id: '1235', is_confirmed: true, email: 'user+bar@example.com' } ] } */ }); ``` ## Add Email Alias To add an email alias for a user call the [`users.addEmailAlias(userID, email, callback`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#addEmailAlias) method. ``` client.users.addEmailAlias('33333', 'user+baz@example.com') .then(alias => { /* alias -> { type: 'email_alias', id: '12345', is_confirmed: false, email: 'user+baz@example.com' } */ }); ``` Enterprise admins can automatically confirm the email alias via the `is_confirmed` option: ``` client.users.addEmailAlias('33333', 'user+quux@example.com', {is_confirmed: true}) .then(alias => { /* alias -> { type: 'email_alias', id: '12346', is_confirmed: true, email: 'user+quux@example.com' } */ }); ``` ## Delete Email Alias To delete a users email alias call the [`users.removeEmailAlias(userID, aliasID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#removeEmailAlias) method. ``` var userID = '33333'; var aliasID = '12345'; client.users.removeEmailAlias(userID, aliasID) .then(() => { // removal successful — no value returned }); ``` ## Terminate users session To terminate user's sessions call the [`users.terminateSession(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Users.html#terminateSession) method. ``` var userIDs = ['33333', '44444']; var userLogins = ['user1@example.com', 'user2@example.com']; client.users.terminateSession({ user_ids: userIDs, user_logins: userLogins }).then((result) => { /* result -> { message: "Request is successful, please check the admin events for the status of the job" } */ }); ``` --- ## Untitled *Type: page* Storage Policies Storage policies allow enterprise administrators to choose where their content is physically stored; different policies can… # Storage Policies Storage policies allow enterprise administrators to choose where their content is physically stored; different policies can be purchased and assigned either as the default policy for the entire enterprise or on a per-user basis. ## Get Available Storage Policies for an Enterprise To get a list of the storage policies that are available for the current user's enterprise, call the [`storagePolicies.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/StoragePolicies.html#getAll) method. ``` client.storagePolicies.getAll() .then(policies => { /* policies -> { next_marker: null, limit: 1000, entries: [ { type: 'storage_policy', id: '42', name: 'Montreal / Dublin' }, { type: 'storage_policy', id: '126', name: 'Frankfurt / Dublin' }, { type: 'storage_policy', id: '162', name: 'US' } ] } */ }); ``` ## Get Information About a Specific Storage Policy Information about a specific storage policy (by its ID) can be retrieved by calling the [`storagePolicies.get(storagePolicyID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/StoragePolicies.html#get) method with the ID of the assignment object. ``` client.storagePolicies.get('6') .then(storagePolicy => { /* storagePolicy -> { type: 'storage_policy', id: '6', name: 'Tokyo & Singapore' } */ }); ``` ## Assign a Storage Policy to a User To assign a storage policy to a user, call the [`storagePolicies.assign(storagePolicyID, userID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/StoragePolicies.html#assign) method with the ID of the storage policy to assign and the ID of the user to which it should be assigned. **Note:** This method will check if an assignment already exists for the user and take appropriate action. It should work regardless of the current status of the user. ``` var storagePolicyID = '7'; var userID = '22222'; client.storagePolicies.assign(storagePolicyID, userID) .then(assignment => { /* assignment -> { type: 'storage_policy_assignment', id: 'dXNlcl8yMjIyMg==', storage_policy: 'storage_policy', id: '7' }, assigned_to: { type: 'user', id: '22222' } } */ }); ``` ## Get Information About a Specific Storage Policy Assignment To get information about a specific storage policy assignment by ID, call the [`storagePolicies.getAssignment(asisgnmentID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/StoragePolicies.html#getAssignment) method with the ID of the storage policy assignment. ``` client.storagePolicies.getAssignment('dXNlcl8yMjIyMg==') .then(assignment => { /* assignment -> { type: 'storage_policy_assignment', id: 'dXNlcl8yMjIyMg==', storage_policy: 'storage_policy', id: '7' }, assigned_to: { type: 'user', id: '22222' } } */ }); ``` ## Get the Storage Policy Assigned to a User To determine which storage policy is assigned to a user, call [`storagePolicies.getAssignmentForTarget(userID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/StoragePolicies.html#getAssignmentForTarget) with the ID of the user. ``` client.storagePolicies.getAssignmentForTarget('22222') .then(assignment => { /* assignment -> { type: 'storage_policy_assignment', id: 'dXNlcl8yMjIyMg==', storage_policy: 'storage_policy', id: '7' }, assigned_to: { type: 'user', id: '22222' } } */ }); ``` ## Create a Storage Policy Assignment To create a new storage policy assignment, call the [`storagePolicies.createAssignment(policyID, userID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/StoragePolicies.html#createAssignment) method with the ID of the storage policy to assign and the ID of the user to assign it to. **Note:** This method only works if the user does not already have an assignment. If the current state of the user is not known, use the [`storagePolicies.assign()`](#assign-a-storage-policy-to-a-user) method instead. ``` client.storagePolicies.createAssignment('7', '22222') .then(assignment => { /* assignment -> { type: 'storage_policy_assignment', id: 'dXNlcl8yMjIyMg==', storage_policy: 'storage_policy', id: '7' }, assigned_to: { type: 'user', id: '22222' } } */ }); ``` ## Update a Storage Policy Assignment To update a storage policy assignment, for example to update which storage policy is asisgned to a user, call the [`storagePolicies.updateAssignment(assignmentID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/StoragePolicies.html#updateAssignment) method with the ID of the assignment to update and an object containing key/value mapping of fields to update on the assignment. ``` // Reassign user 22222 to storage policy 10 var assignmentID = 'dXNlcl8yMjIyMg=='; var updates = { storage_policy: { type: 'storage_policy', id: '10' } }; client.storagePolicies.updateAssignment(assignmentID, updates) .then(updatedAssignment => { /* updatedAssignment -> { type: 'storage_policy_assignment', id: 'dXNlcl8yMjIyMg==', storage_policy: 'storage_policy', id: '10' }, assigned_to: { type: 'user', id: '22222' } } */ }); ``` ## Remove a Storage Policy Assignment To remove a storage policy assignment and return the user it was assigned to to the default storage policy for the enterprise, call [`storagePolicies.removeAssignment(assignmentID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/StoragePolicies.html#removeAssignment) with the ID of the assignment to remove. ``` client.storagePolicies.removeAssignment('dXNlcl8yMjIyMg==') .then(() => { // deletion succeeded — no value returned }); ``` --- ## Untitled *Type: page* Trash Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is moved to the Trash… # Trash Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is moved to the Trash. The Trash allows you to recover files and folders that have been deleted. By default, items in the Trash will be purged after 30 days. - [Get Trashed Items](#get-trashed-items) - [Restore a File From Trash](#restore-a-file-from-trash) - [Delete a File from the Trash](#delete-a-file-from-the-trash) - [Get a Trashed File](#get-a-trashed-file) - [Get a Trashed Folder](#get-a-trashed-folder) - [Restore a Folder from Trash](#restore-a-folder-from-trash) - [Delete a Folder from the Trash](#delete-a-folder-from-the-trash) ## Get Trashed Items To retrieve files and folders that have been moved to the Trash, call the [`trash.get(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Trash.html#get) method. ``` client.trash.get() .then(trashedItems => { /* trashedItems -> { total_count: 2, entries: [ { type: 'file', id: '11111', sequence_id: '1', etag: '1', sha1: '9d976863fc849f6061ecf9736710bd9c2bce488c', name: 'file Tue Jul 24 145436 2012KWPX5S.csv' }, { type: 'file', id: '22222', sequence_id: '1', etag: '1', sha1: '09b0e2e9760caf7448c702db34ea001f356f1197', name: 'file Tue Jul 24 010055 20129Z6GS3.csv' } ], offset: 0, limit: 100 } */ }); ``` ## Restore a File From Trash Calling the [`files.restoreFromTrash(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#restoreFromTrash) will restore an item from the user's trash. Default behavior is to restore the item to the folder it was in before it was moved to the trash. Options are available to handle possible failure cases: if an item with the same name already exists in folder's old location, the restored folder can be given an alternate name with the `name` option. If the folder's old location no longer exists, it can be placed inside a new parent folder with the `parent_id` option. ``` client.files.restoreFromTrash( '11111', { // New name in case of conflict name: 'New Name', // File will be placed in this folder if original location no longer exists parent_id: '0' }) .then(restoredFile => { /* trashedFile -> { type: 'file', id: '11111', sequence_id: '2', etag: '2', sha1: '4bd9e98652799fc57cf9423e13629c151152ce6c', name: 'Screenshot_1_30_13_6_37_PM.png', description: '', size: 163265, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_at: '2013-01-30T18:43:56-08:00', modified_at: '2013-01-30T18:44:00-08:00', trashed_at: null, purged_at: null, content_created_at: '2013-01-30T18:43:56-08:00', content_modified_at: '2013-01-30T18:44:00-08:00', created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, shared_link: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, item_status: 'active' } */ }); ``` ## Delete a File from the Trash Calling the [`files.deletePermanently(fileID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#deletePermanently) method will remove the file permanently from the user's trash. ``` client.files.deletePermanently('11111') .then(() => { // deletion succeeded — no value returned }); ``` If you want to ensure that your deletion does not overwrite any other updates (i.e. to prevent against possible race conditions), you can pass the last known value of the file's `etag` field via the `etag` option; this will generate an error if the file was modified between when you read that `etag` value and when the deletion is processed by the API. ``` client.files.deletePermanently('11111', { etag: '5' }) .then(() => { // File successfully deleted }) .catch(err => { if (err.statusCode === 412) { // Precondition failed — the file was modified before the deletion was processed // Read the file again to ensure it is safe to delete and then retry } }); ``` ## Get a Trashed File Information about a file in the trash can be retrieved with the [`files.getTrashedFile(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getTrashedFile) method. ``` client.files.getTrashedFile('11111') .then(trashedFile => { /* trashedFile -> { type: 'file', id: '11111', sequence_id: '2', etag: '2', sha1: '4bd9e98652799fc57cf9423e13629c151152ce6c', name: 'Screenshot_1_30_13_6_37_PM.png', description: '', size: 163265, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '1', sequence_id: null, etag: null, name: 'Trash' } ] }, created_at: '2013-01-30T18:43:56-08:00', modified_at: '2013-01-30T18:44:00-08:00', trashed_at: '2013-02-07T10:49:34-08:00', purged_at: '2013-03-09T10:49:34-08:00', content_created_at: '2013-01-30T18:43:56-08:00', content_modified_at: '2013-01-30T18:44:00-08:00', created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, shared_link: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, item_status: 'trashed' } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` // Only get information about a few specific fields. client.files.getTrashedFile('11111', {fields: 'size,owned_by'}) .then(trashedFile => { /* trashedFile -> { type: 'file', id: '11111', sequence_id: '2', etag: '2', sha1: '4bd9e98652799fc57cf9423e13629c151152ce6c', size: 163265, owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } */ }); ``` ## Get a Trashed Folder Information about a folder in the trash can be retrieved with the [`folders.getTrashedFolder(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#getTrashedFolder) method. ``` client.folders.getTrashedFolder('22222') .then(trashedFolder => { /* trashedFolder -> { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Old Files', created_at: '2013-05-06T22:37:30-07:00', modified_at: '2013-05-06T22:39:08-07:00', description: '', size: 18482, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '1', sequence_id: null, etag: null, name: 'Trash' } ] }, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, trashed_at: '2013-05-29T09:37:13-07:00', purged_at: null, content_created_at: '2013-05-06T22:37:30-07:00', content_modified_at: '2013-05-06T22:39:08-07:00', owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, shared_link: null, folder_upload_email: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, item_status: 'trashed' } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` client.folders.getTrashedFolder('22222', {fields: 'name,trashed_at,purged_at'}) .then(trashedFolder => { /* trashedFolder -> { type: 'folder', id: '22222', sequence_id: '1', etag: '1', trashed_at: '2013-05-29T09:37:13-07:00', purged_at: null } */ }); ``` ## Restore a Folder from Trash A folder can be restored from the trash with the [`folders.restoreFromTrash(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#restoreFromTrash) method. Default behavior is to restore the item to the folder it was in before it was moved to the trash. Options are available to handle possible failure cases: if an item with the same name already exists in folder's old location, the restored folder can be given an alternate name with the `name` option. If the folder's old location no longer exists, it can be placed inside a new parent folder with the `parent_id` option. ``` client.folders.restoreFromTrash( '22222', { // New name in case of conflict name: 'New Name', // Folder will be placed in this parent folder if the original parent no longer exists parent_id: '0' }) .then(restoredFolder => { /* trashedFolder -> { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Old Files', created_at: '2013-05-06T22:37:30-07:00', modified_at: '2013-05-06T22:39:08-07:00', description: '', size: 18482, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, trashed_at: null, purged_at: null, content_created_at: '2013-05-06T22:37:30-07:00', content_modified_at: '2013-05-06T22:39:08-07:00', owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, shared_link: null, folder_upload_email: null, parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, item_status: 'active' } */ }); ``` ## Delete a Folder from the Trash A folder can be removed permanently from trash by calling [`folders.deletePermanently(folderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#deletePermanently). ``` client.folders.deletePermanently('22222') .then(() => { // deletion succeeded — no value returned }); ``` If you want to ensure that your deletion does not overwrite any other updates (i.e. to prevent against possible race conditions), you can pass the last known value of the folder's `etag` field via the `etag` option; this will generate an error if the folder was modified between when you read that `etag` value and when the deletion is processed by the API. ``` client.folders.deletePermanently('22222', { etag: '5' }) .then(() => { // Folder successfully deleted }) .catch(err => { if (err.statusCode === 412) { // Precondition failed — the folder was modified before the deletion was processed // Read the folder again to ensure it is safe to delete and then retry } }); ``` --- ## Untitled *Type: page* Watermarking Watermarking allows you to place a semi-transparent overlay on an embedded file preview that displays a viewer's email address… # Watermarking Watermarking allows you to place a semi-transparent overlay on an embedded file preview that displays a viewer's email address or user ID and the time of access over a file's content. Once a watermark is applied to a file or folder via the API, the watermark will be displayed on any file preview. - [Get Watermark on a File](#get-watermark-on-a-file) - [Apply Watermark to a File](#apply-watermark-to-a-file) - [Remove Watermark from a File](#remove-watermark-from-a-file) - [Get Watermark on a Folder](#get-watermark-on-a-folder) - [Apply Watermark to a Folder](#apply-watermark-to-a-folder) - [Remove Watermark from a Folder](#remove-watermark-from-a-folder) ## Get Watermark on a File To get watermark information for a file call the [`files.getWatermark(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getWatermark) method. ``` client.files.getWatermark('11111') .then(watermark => { /* watermark -> { watermark: { created_at: '2016-10-31T15:33:33-07:00', modified_at: '2016-10-31T15:33:33-07:00' } } */ }); ``` ## Apply Watermark to a File To apply or update the watermark to a file call the [`files.applyWatermark(fileID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#applyWatermark) method. ``` client.files.applyWatermark('11111') .then(watermark => { /* watermark -> { watermark: { created_at: '2016-10-31T15:33:33-07:00', modified_at: '2016-10-31T15:33:33-07:00' } } */ }); ``` ## Remove Watermark from a File A file's watermark can be removed by calling [`files.removeWatermark(fileID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#removeWatermark). ``` client.files.removeWatermark('11111') .then(() => { // removal succeeded — no value returned }); ``` ## Get Watermark on a Folder To get watermark information for a folder call the [`folders.getWatermark(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#getWatermark) method. ``` client.folders.getWatermark('22222') .then(watermark => { /* watermark -> { watermark: { created_at: '2016-10-31T15:33:33-07:00', modified_at: '2016-10-31T15:33:33-07:00' } } */ }); ``` ## Apply Watermark to a Folder To apply or update the watermark for a folder call the [`folders.applyWatermark(folderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#applyWatermark) method. ``` client.folders.applyWatermark('22222') .then(watermark => { /* watermark -> { watermark: { created_at: '2016-10-31T15:33:33-07:00', modified_at: '2016-10-31T15:33:33-07:00' } } */ }); ``` ## Remove Watermark from a Folder A folder's watermark can be removed by calling [`folders.removeWatermark(folderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Folders.html#removeWatermark). ``` client.folders.removeWatermark('22222') .then(() => { // removal succeeded — no value returned }); ``` --- ## Untitled *Type: page* Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link… # Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, so they will also support shared links, copy, permanent delete, and restore. - [Create a Web Link](#create-a-web-link) - [Get a Web Link's information](#get-a-web-links-information) - [Update a Web Link](#update-a-web-link) - [Delete a Web Link](#delete-a-web-link) - [Copy a Web Link](#copy-a-web-link) - [Move a Web Link](#move-a-web-link) ## Create a Web Link To create a web link call the [`weblinks.create(url, parentID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/WebLinks.html#create) method. ``` client.weblinks.create( 'https://www.box.com', '22222', { name: 'Box Website!', description: 'Cloud Content Management' }) .then(weblink => { /* weblink -> { type: 'web_link', id: '11111', sequence_id: '0', etag: '0', name: 'Box Website!', url: 'https://www.box.com', created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2015-05-07T15:00:01-07:00', modified_at: '2015-05-07T15:00:01-07:00', parent: { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Bookmarks' }, description: 'Enterprise Cloud Content Management', item_status: 'active', trashed_at: null, purged_at: null, shared_link: null, path_collection: { total_count: 2, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Bookmarks' } ] }, modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } */ }); ``` ## Get a Web Link's information You can request a web link object by ID by calling [`weblinks.get(weblinkID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/WebLinks.html#get). ``` client.weblinks.get('11111') .then(weblink => { /* weblink -> { type: 'web_link', id: '11111', sequence_id: '0', etag: '0', name: 'Box Website!', url: 'https://www.box.com', created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2015-05-07T15:00:01-07:00', modified_at: '2015-05-07T15:00:01-07:00', parent: { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Bookmarks' }, description: 'Enterprise Cloud Content Management', item_status: 'active', trashed_at: null, purged_at: null, shared_link: null, path_collection: { total_count: 2, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Bookmarks' } ] }, modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } */ }); ``` Requesting information for only the fields you need with the `fields` option can improve performance and reduce the size of the network request. ``` client.weblinks.get('11111', {fields: 'url,name,description'}) .then(weblink => { /* weblink -> { type: 'web_link', id: '11111', sequence_id: '0', etag: '0', name: 'Box Website!', url: 'https://www.box.com', description: 'Enterprise Cloud Content Management' } */ }); ``` ## Update a Web Link To update a web link call the [`weblinks.update(weblinkID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/WebLinks.html#update) method with the fields to update and their new values. ``` client.weblinks.update( '11111', { name: 'Box Marketing Site', description: 'First page that customers land on' }) .then(weblink => { /* weblink -> { type: 'web_link', id: '11111', sequence_id: '0', etag: '0', name: 'Box Marketing Site', url: 'https://www.box.com', created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2015-05-07T15:00:01-07:00', modified_at: '2017-06-13T12:34:51-07:00', parent: { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Bookmarks' }, description: 'First page that customers land on', item_status: 'active', trashed_at: null, purged_at: null, shared_link: null, path_collection: { total_count: 2, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, { type: 'folder', id: '22222', sequence_id: '1', etag: '1', name: 'Bookmarks' } ] }, modified_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' } } */ }); ``` ## Delete a Web Link To move a web link to the trash call the [`weblinks.delete(weblinkID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/WebLinks.html#delete) method. ``` client.weblinks.delete('11111') .then(() => { // deletion succeeded — no value returned }); ``` ## Copy a Web Link Call the [`weblinks.copy(webLinkID, destinationFolderID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/WebLinks.html#copy) method to copy a web link into another folder. ``` client.weblinks.copy('11111', '0') .then(webLinkCopy => { /* webLinkCopy -> { type: 'web_link', id: '11112', sequence_id: '0', etag: '0', name: 'Renamed web link copy', url: 'http://example.com', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2019-03-26T12:49:06-07:00', modified_at: '2019-03-26T12:49:06-07:00', parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, description: '', item_status: 'active', trashed_at: null, purged_at: null, shared_link: null, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, modified_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' } } */ }); ``` An optional `name` parameter can also be passed to rename the folder on copy. This can be used to avoid a name conflict when there is already an item with the same name in the target folder. ``` client.weblinks.copy('12345', '0', {name: 'Renamed web link'}) .then(webLinkCopy => { // ... }); ``` ## Move a Web Link Call the [`weblinks.move(webLinkID, destinationFolderID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/WebLinks.html#move) method with the destination you want the folder moved to. ``` var webLinkID = '88888'; var destinationFolderID = '0'; client.weblinks.move(webLinkID, destinationFolderID) .then(webLink => { /* webLink -> { type: 'web_link', id: '88888', sequence_id: '0', etag: '0', name: 'Example Web Link', url: 'http://example.com', created_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, created_at: '2019-03-26T12:49:06-07:00', modified_at: '2019-03-26T12:49:06-07:00', parent: { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' }, description: '', item_status: 'active', trashed_at: null, purged_at: null, shared_link: null, path_collection: { total_count: 1, entries: [ { type: 'folder', id: '0', sequence_id: null, etag: null, name: 'All Files' } ] }, modified_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' }, owned_by: { type: 'user', id: '22222', name: 'Example User', login: 'user@example.com' } } */ }); ``` --- ## Untitled *Type: page* Terms of Service Terms of Service are custom objects that the admin of an enterprise can configure. This will prompt the end user to accept… # Terms of Service Terms of Service are custom objects that the admin of an enterprise can configure. This will prompt the end user to accept/re-accept or decline the custom Terms of Service for platform applications built on Box Platform. [Terms of Service](#terms-of-service) - [Get Terms of Service for an Enterprise](#get-terms-of-service-for-an-enterprise) - [Get a Terms of Service By ID](#get-a-terms-of-service-by-id) - [Update a Terms of Service for an Enterprise](#update-a-terms-of-service-for-an-enterprise) - [Create a Terms of Service for an Enterprise](#create-a-terms-of-service-for-an-enterprise) - [Get Terms of Service Status for User](#get-terms-of-service-status-for-user) - [Create User Status on Terms of Service](#create-user-status-on-terms-of-service) - [Update User Status on Terms of Service](#update-user-status-on-terms-of-service) - [Accept or Decline a Terms of Service](#accept-or-decline-a-terms-of-service) ## Get Terms of Service for an Enterprise To get terms of service call the [`termsOfService.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/TermsOfService.html#getAll) method. ``` client.termsOfService.getAll() .then(termsOfService => { /* termsOfService -> { entries: [ total_count: 1, { type: 'terms_of_service', id: '12345', status: 'disabled', enterprise: { type: 'enterprise', id: '55555' }, tos_type: 'managed', text: 'By using this service, you agree to ...', created_at: '2018-04-19T13:55:09-07:00', modified_at: '2018-04-19T13:55:09-07:00' } ] */ }); ``` Alternatively, you can specify the Terms of Service type. You can either specify "managed" or "external". This field specifies the type of user the Terms of Service applies to. ``` client.termsOfService.getAll({ tos_type: 'managed' }) .then(termsOfService => { /* termsOfService -> { entries: [ total_count: 1, { type: 'terms_of_service', id: '12345', status: 'disabled', enterprise: { type: 'enterprise', id: '55555' }, tos_type: 'managed', text: 'By using this service, you agree to ...', created_at: '2018-04-19T13:55:09-07:00', modified_at: '2018-04-19T13:55:09-07:00' } ] */ }); ``` ## Get a Terms of Service By ID To get the terms of service with an ID call the [`termsOfService.get(termsOfServicesID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/TermsOfService.html#get) method. ``` client.termsOfService.get('12345') .then(tos => { /* tos -> { type: 'terms_of_service', id: '12345', status: 'disabled', enterprise: { type: 'enterprise', id: '55555' }, tos_type: 'managed', text: 'By using this service, you agree to ...', created_at: '2018-04-19T13:55:09-07:00', modified_at: '2018-04-19T13:55:09-07:00' } */ }); ``` ## Update a Terms of Service for an Enterprise To update a terms of service call the [`termsOfService.update(termsOfServicesID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/TermsOfService.html#update) method with the fields to update and their new values. ``` client.termsOfService.update('12345', { status: 'disabled' }) .then(tos => { /* tos -> { type: 'terms_of_service', id: '12345', status: 'disabled', enterprise: { type: 'enterprise', id: '55555' }, tos_type: 'managed', text: 'By using this service, you agree to ...', created_at: '2018-04-19T13:55:09-07:00', modified_at: '2018-04-19T13:55:09-07:00' } */ }); ``` The termsOfServicesStatus can be set to 'enabled' or 'disabled'. You can also specify the conditions of the terms of service in the termsOfServicesText parameter. ## Create a Terms of Service for an Enterprise To create a terms of service call the [`termsOfService.create(termsOfServicesType, termsOfServicesStatus, termsOfServicesText, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/TermsOfService.html#create) method. **Note:** Only two terms of service can exist per enterprise: one managed terms of service and one external terms of service. If you wish to have a different terms of service, update one of the existing terms of service. ``` client.termsOfService.create('managed', 'enabled', 'By using this service, you agree to ...') .then(tos => { /* tos -> { type: 'terms_of_service', id: '12345', status: 'enabled', enterprise: { type: 'enterprise', id: '55555' }, tos_type: 'managed', text: 'By using this service, you agree to ...', created_at: '2018-04-19T13:55:09-07:00', modified_at: '2018-04-19T13:55:09-07:00' } */ }); ``` ``` client.termsOfService.create('external', 'disabled', 'This is a new terms of service but disabled') .then(tos => { /* tos -> { type: 'terms_of_service', id: '12346', status: 'disabled', enterprise: { type: 'enterprise', id: '55555' }, tos_type: 'external', text: 'This is a new terms of service but disabled', created_at: '2018-04-19T13:55:09-07:00', modified_at: '2018-04-19T13:55:09-07:00' } */ }); ``` ## Get Terms of Service Status for User To get user status on a terms of service call the [`termsOfService.getUserStatus(termsOfStatusID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/TermsOfService.html#getUserStatus) method. If no `user_id` option is specified, this will default to current user. ``` client.termsOfService.getUserStatus('11111', { user_id: '22222' }) .then(tosStatus => { /* tosStatus -> { type: 'terms_of_service_user_status', id: '12345', tos: { type: 'terms_of_service', id: '11111' }, user: { type: 'user', id: '22222' }, is_accepted: true, created_at: '2018-04-11T15:33:49-07:00', modified_at: '2018-04-11T15:33:49-07:00' } */ }); ``` ## Create User Status on Terms of Service To accept or decline a terms of service for a user who has never accepted/decline this terms of service before call the [`termsOfService.createUserStatus(termsOfServicesID, isAccepted, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/TermsOfService.html#createUserStatus) method. ``` client.termsOfService.createUserStatus('11111', true, {user_id: '22222'}) .then(tosStatus => { /* tosStatus -> { type: 'terms_of_service_user_status', id: '12345', tos: { type: 'terms_of_service', id: '11111' }, user: { type: 'user', id: '22222' }, is_accepted: true, created_at: '2018-04-11T15:33:49-07:00', modified_at: '2018-04-11T15:33:49-07:00' } */ }); ``` It is important to note that this will accept or decline a custom terms of service for a user that has never taken action on this terms of service before. For a user that has, this will return a 409 Conflict Error. If no user is specified, this will default to current user. ## Update User Status on Terms of Service To update user status on a terms of service call the [`termsOfService.updateUserStatus(termsOfServiceUserStatusID, isAccepted, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/TermsOfService.html#updateUserStatus) method. ``` client.termsOfService.updateUserStatus('5678', false) .then(tosStatus => { /* tosStatus -> { type: 'terms_of_service_user_status', id: '12345', tos: { type: 'terms_of_service', id: '11111' }, user: { type: 'user', id: '22222' }, is_accepted: false, created_at: '2018-04-11T15:33:49-07:00', modified_at: '2018-04-11T15:33:49-07:00' } */ }); ``` It is important to note that this will accept or decline a custom terms of service for a user. For a user that has taken action in this terms of service, this will update their status. If the user has never taken action on this terms of service then this will return a 404 Not Found Error. ## Accept or Decline a Terms of Service To create user/terms of service association and accept/decline call the [`termsOfService.setUserStatus(termsOfServicesID, isAccepted, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/TermsOfService.html#setUserStatus)) method. ``` client.termsOfService.setUserStatus('1234', true, { user_id: '5678' }, callback); ) ``` It is important to note that regardless of whether the user has taken action on this terms of service. This will create and update the user status on the terms of service. --- ## Untitled *Type: page* Webhooks A webhook object enables you to attach events triggers to Box files and folders. These event triggers monitor events on Box objects… # Webhooks A webhook object enables you to attach events triggers to Box files and folders. These event triggers monitor events on Box objects and notify your application, via HTTP requests to a URL of your choosing, when they occur. - [Create a Webhook](#create-a-webhook) - [Get a Webhook's Information](#get-a-webhooks-information) - [Get all Webhooks Information](#get-all-webhooks-information) - [Update a Webhook](#update-a-webhook) - [Delete a Webhook](#delete-a-webhook) - [Validate a Webhook Message](#validate-a-webhook-message) ## Create a Webhook To attach a webhook to an item, call the [`webhooks.create(fileID, targetType, notificationURL, triggerTypes, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Webhooks.html#create) method with the type and ID of the item, a URL to send notifications to, and a list of triggers. The notification URL must be a valid HTTPS URL that you specify when you create a webhook. The triggerTypes param is an array of strings. Available options are documented here: [https://developer.box.com/guides/webhooks/triggers/](https://developer.box.com/guides/webhooks/triggers/) ``` // Attach a webhook that sends a notification to https://example.com/webhook when // file 11111 is renamed or downloaded. client.webhooks.create( '11111', client.itemTypes.FILE, 'https://example.com/webhook', [ client.webhooks.triggerTypes.FILE.RENAMED, client.webhooks.triggerTypes.FILE.DOWNLOADED ]) .then(webhook => { /* webhook -> { id: '12345', type: 'webhook', target: { id: '11111', type: 'file' }, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2016-05-09T17:41:27-07:00', address: 'https://example.com/webhook', triggers: [ 'FILE.RENAMED', 'FILE.UPLOADED' ] } */ }); ``` ``` // Attach a webhook that sends a notification to https://example.com/webhook when // files are uploaded or downloaded within folder 22222. client.webhooks.create( '22222', client.itemTypes.FOLDER, 'https://example.com/webhook', [ client.webhooks.triggerTypes.FILE.UPLOADED, client.webhooks.triggerTypes.FILE.DOWNLOADED ]) .then(webhook => { /* webhook -> { id: '1234', type: 'webhook', target: { id: '22222', type: 'folder' }, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2016-05-09T17:41:27-07:00', address: 'https://example.com/webhook', triggers: [ 'FILE.DOWNLOADED', 'FILE.UPLOADED' ] } */ }); ``` ## Get a Webhook's Information Retrieve information about a specific webhook by calling [`webhooks.get(webhookID, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Webhooks.html#get) to retrieve a webhook by ID. ``` client.webhooks.get('1234') .then(webhook => { /* webhook -> { id: '1234', type: 'webhook', target: { id: '22222', type: 'folder' }, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2016-05-09T17:41:27-07:00', address: 'https://example.com/webhook', triggers: [ 'FILE.DOWNLOADED', 'FILE.UPLOADED' ] } */ }); ``` ## Get all Webhooks Information Get a list of all webhooks for the requesting application and user by calling the [`webhooks.getAll(options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Webhooks.html#getAll) method. The maximum limit per page of results is 200, Box uses the default limit of 100. ``` client.webhooks.getAll() .then(webhooks => { /* webhooks -> { next_marker: 'ZmlQZS0xLTE%3D', entries: [ { id: '1234', type: 'webhook', target: { id: '22222', type: 'folder' } }, { id: '5678', type: 'webhook', target: { id: '11111', type: 'file' } } ], limit: 2 } */ }); ``` ## Update a Webhook Update a file or folder's webhook by calling [`webhooks.update(webhookID, updates, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Webhooks.html#update) with the field you want to update as `updates.address` or `updates.trigger`. ``` client.webhooks.update('678901', {address: "https://example.com/webhooks/fileActions"}) .then(webhook => { /* webhook -> { id: '1234', type: 'webhook', target: { id: '22222', type: 'folder' }, created_by: { type: 'user', id: '33333', name: 'Example User', login: 'user@example.com' }, created_at: '2016-05-09T17:41:27-07:00', address: 'https://example.com/webhooks/fileActions', triggers: [ 'FILE.DOWNLOADED', 'FILE.UPLOADED' ] } */ }); ``` ## Delete a Webhook A file or folder's webhook can be removed by calling [`webhooks.delete(webhookID, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Webhooks.html#delete). ``` client.webhooks.delete('1234') .then(() => { // deletion succeeded — no value returned }); ``` ## Validate a Webhook Message When you receive a webhook message from Box, you should validate it by calling [`BoxSDK.validateWebhookMessage(body, headers, primarySignatureKey, secondarySignatureKey, maxMessageAge)`](http://opensource.box.com/box-node-sdk/jsdoc/Webhooks.html#.validateMessage), also available as `webhooks.validateMessage(body, headers, primarySignatureKey, secondarySignatureKey, maxMessageAge)`. ``` const BoxSDK = require('box-node-sdk'); let body = '{"type":"webhook_event","webhook":{"id":"1234567890"},"trigger":"FILE.UPLOADED","source":{"id":"1234567890","type":"file","name":"Test.txt"}}', headers = { 'box-delivery-id': 'f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f', 'box-delivery-timestamp': '2020-01-01T00:00:00-07:00', 'box-signature-algorithm': 'HmacSHA256', 'box-signature-primary': '6TfeAW3A1PASkgboxxA5yqHNKOwFyMWuEXny/FPD5hI=', 'box-signature-secondary': 'v+1CD1Jdo3muIcbpv5lxxgPglOqMfsNHPV899xWYydo=', 'box-signature-version': '1' }, primaryKey = 'SamplePrimaryKey', secondaryKey = 'SampleSecondaryKey'; let isValid = BoxSDK.validateWebhookMessage(body, headers, primaryKey, secondaryKey); if (isValid) { // message is valid, accept } else { // message is NOT valid, reject } ``` --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - if you want to contribute code. Please be sure to file an issue first. ## Pull request best practices We want to accept your pull requests. Please follow these steps: ### Step 1: File an issue Before writing any code, please file an issue stating the problem you want to solve or the feature you want to implement. This allows us to give you feedback before you spend any time writing code. There may be a known limitation that can't be addressed, or a bug that has already been fixed in a different way. The issue allows us to communicate and figure out if it's worth your time to write a bunch of code for the project. ### Step 2: Fork this repository in GitHub This will create your own copy of our repository. ### Step 3: Add the upstream source The upstream source is the project under the Box organization on GitHub. To add an upstream source for this project, type: ``` git remote add upstream git@github.com:box/box-node-sdk.git ``` This will come in useful later. ### Step 4: Create a feature branch Create a branch with a descriptive name, such as `add-search`. ### Step 5: Push your feature branch to your fork We use [semantic-versioning](https://semver.org/) and the [conventional commit message format](https://www.conventionalcommits.org/en/v1.0.0/). Keep a separate feature branch for each issue you want to address. As you develop code, continue to push code to your remote feature branch. Example: ``` tag: short description longer description here if necessary. ``` The message summary should be a one-sentence description of the change, and it must be 72 characters in length or shorter. For a list of tags, please [click here](https://github.com/commitizen/conventional-commit-types/blob/master/index.json). Note that you must include the `!` for breaking changes (e.g. `feat!: removed old apis`). Shown below are examples of the release type that will be done based on a commit message. #### Commit Types "Semantic versioning" means that changes to the version number of the package (e.g. `3.42.11` to `3.43.0`) are done according to rules that indicate how the change will affect consumers. Read more on the [semver page](https://semver.org/). The version number is broken into 3 positions — `Major.Minor.Patch`. In semantic release terms, changes to the numbers follow `Breaking.Feature.Fix`. The `release` script parses commit messages and decides what type of release to make based on the types of commits detected since the last release. The rules for commit types are: - Anything that changes or removes an API, option, or output format is a breaking change denoted by `!`. - Anything that adds new functionality in a backwards-compatible way is a feature (`feat`). Consumers have to upgrade to the new version to use the feature, but nothing will break if they do so. - Bugfixes (`fix`) for existing behavior are a patch. Consumers don't have to do anything but upgrade. - Other prefixes, such as `docs` or `chore`, don't trigger releases and don't appear in the changelog. These tags signal that there are **no external changes to *any* APIs** (including non-breaking ones). In most cases, commits will be a `feat` or `fix`. Make sure to include the `!` in the title if there are non-backwards-compatible changes in the commit. | Commit message | Release type | New version | | --- | --- | --- | | feat!: remove old files endpoints | Major ("breaking") | X+1.0.0 | | feat: add new file upload endpoint | Minor ("feature") | X.Y+1.0 | | fix: file streaming during download | Patch ("fix") | X.Y.Z+1 | | docs: document files api | No release | X.Y.Z | | chore: remove commented code from file upload | No release | X.Y.Z | | refactor: rename a variable (invisible change) | No release | X.Y.Z | ### Step 6: Rebase Before sending a pull request, rebase against upstream, such as: ``` git fetch upstream git rebase upstream/main ``` This will add your changes on top of what's already in upstream, minimizing merge issues. ### Step 7: Run the tests Make sure that all tests are passing before submitting a pull request. ### Step 8: Send the pull request Send the pull request from your feature branch to us. Be sure to include a description that lets us know what work you did. Keep in mind that we like to see one issue addressed per pull request, as this helps keep our git history clean and we can more easily track down issues. --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 3.8.2 (2025-07-2… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### 3.8.2 (2025-07-29) ### Bug Fixes - Bump `cypress/request` to resolve `CVE-2025-7783` in `form-data` ([#904](https://github.com/box/box-node-sdk/issues/904)) ([8e8d2da](https://github.com/box/box-node-sdk/commit/8e8d2da58ab42bdfb9e5a49ca25e9b9fc50e0d61)) ### 3.8.1 (2025-06-11) ### Bug Fixes - Use constant-time comparison for HMAC signatures ([#893](https://github.com/box/box-node-sdk/issues/893)) ([d819efe](https://github.com/box/box-node-sdk/commit/d819efe663a59fce53412fbe153a76dd346d4536)) ## 3.8.0 (2025-04-09) ### New Features and Enhancements - Support AI agent ([#887](https://github.com/box/box-node-sdk/issues/887)) ([5b109ad](https://github.com/box/box-node-sdk/commit/5b109adbd506510fc83b1c90af13b063ddefab37)) ### 3.7.1 (2024-08-06) ### Bug Fixes - add version to copy file options annotation ([#885](https://github.com/box/box-node-sdk/issues/885)) ([4f9312c](https://github.com/box/box-node-sdk/commit/4f9312c63138f8cf8e0a9e46a9e1345172dbdc6b)) ## 3.7.0 (2024-07-16) ### New Features and Enhancements - Support AI APIs ([#883](https://github.com/box/box-node-sdk/issues/883)) ([bb81e07](https://github.com/box/box-node-sdk/commit/bb81e074eb1017bd742c90159e6cf4e6ce9d9776)) ## 3.6.0 (2024-05-20) ### New Features and Enhancements - Transition to stable status ([#880](https://github.com/box/box-node-sdk/issues/880)) ([ae996ea](https://github.com/box/box-node-sdk/commit/ae996eafd9e34de99119a7780384b90758908313)) ### 3.5.1 (2024-05-02) ### Bug Fixes - Fix `options` parameter in metadata query method ([#878](https://github.com/box/box-node-sdk/issues/878)) ([7943420](https://github.com/box/box-node-sdk/commit/79434209c572cd77c329d6008cda9837a9dba411)) ## 3.5.0 (2024-02-19) ### New Features and Enhancements - Sign request group ([#870](https://github.com/box/box-node-sdk/issues/870)) ([11bf5d2](https://github.com/box/box-node-sdk/commit/11bf5d2db7e0cefc669aab99c8b65c632289ac46)) ### Bug Fixes - Bumped proxy-agent to 6.4.0 ([#874](https://github.com/box/box-node-sdk/issues/874)) ([55a8a0b](https://github.com/box/box-node-sdk/commit/55a8a0baebe151f4107fdbec0a1022e9534f88a4)) - Remove delete classification ([#869](https://github.com/box/box-node-sdk/issues/869)) ([22384ab](https://github.com/box/box-node-sdk/commit/22384abc3abbc35800cbcdea7c7eb9a452cc4859)) ### 3.4.2 (2023-11-08) ### Bug Fixes - Fix `proxy-agent` ([#867](https://github.com/box/box-node-sdk/issues/867)) ([3de7586](https://github.com/box/box-node-sdk/commit/3de7586e44dbb7c8e1bff8f34471964805c810f5)) ### 3.4.1 (2023-11-03) ### Bug Fixes - Update `proxy-agent` usage, drop support Node 12 ([#865](https://github.com/box/box-node-sdk/issues/865)) ([e229d3f](https://github.com/box/box-node-sdk/commit/e229d3f93de350c00768528a1c0d3a6ecfc697a9)) ## 3.4.0 (2023-11-03) ### New Features and Enhancements - Add request option to skip `PassThrough` ([#863](https://github.com/box/box-node-sdk/issues/863)) ([726db45](https://github.com/box/box-node-sdk/commit/726db45cfbb992e545fe2865283df63c898656ac)) ## 3.3.0 (2023-10-26) ### New Features and Enhancements - Replace `request` library with `@cypress/request` ([#860](https://github.com/box/box-node-sdk/issues/860)) ([d365ae8](https://github.com/box/box-node-sdk/commit/d365ae8368c549ecdceb7dd5b928904fd3c58978)) ### Bug Fixes - mark auth funs callbacks as optional ([#858](https://github.com/box/box-node-sdk/issues/858)) ([55f22fe](https://github.com/box/box-node-sdk/commit/55f22fec7d7d35e487f3fb51bc9bbd3e848842ab)) ### 3.2.1 (2023-10-06) ### Bug Fixes - Overrides tough-cookie dependency ([#852](https://github.com/box/box-node-sdk/issues/852)) ([99df873](https://github.com/box/box-node-sdk/commit/99df873e1a1dad4a0073d53b4ed57c0eeb859401)) ## 3.2.0 (2023-09-07) ### New Features and Enhancements - Support sign template ([#848](https://github.com/box/box-node-sdk/issues/848)) ([18d3413](https://github.com/box/box-node-sdk/commit/18d3413afeddf43c62dfd0caf1279e61c99b6b83)) ### 3.1.1 (2023-07-19) ## 3.1.0 (2023-06-01) ### New Features and Enhancements - Added support for integration mappings API ([#831](https://github.com/box/box-node-sdk/issues/831)) ([a525327](https://github.com/box/box-node-sdk/commit/a525327c1362628a0ffdb36cb4bf3346ca0e0153)) ### Bug Fixes - Correct types of `userId` and `groupId` for creating collaboration ([#833](https://github.com/box/box-node-sdk/issues/833)) ([f803ff8](https://github.com/box/box-node-sdk/commit/f803ff82330fd78a8dc4875452a21aab54686b2e)), closes [#832](https://github.com/box/box-node-sdk/issues/832) ## 3.0.0 (2023-05-23) The most important change in this release is **dropping support for Node versions below 12** and changing the **support environments from Node 12 to Node 16**. ### Breaking Changes - Removed `use_index` usage. ([#812](https://github.com/box/box-node-sdk/pull/812)) ([d56799a](https://github.com/box/box-node-sdk/commit/d56799a61f42265d7785f99e92a449c58d125aef)) - Removed deprecated `BoxClient.batch()` and `BoxClient.batchExec()` method. - Removed deprecated `CollaborationWhitelist` class, use `CollaborationAllowlist` instead. - Removed deprecated `CollaborationAllowlist.getWhitelistedDomain()` method, use `CollaborationAllowlist.getAllowlistedDomain()` instead. - Removed deprecated `CollaborationAllowlist.getAllWhitelistedDomains()` method, use `CollaborationAllowlist.getAllAllowlistedDomains()` instead. - Remove deprecated `Files.getThumbnail(fileID: string, options?: Record<string, any>, callback?: Function)` method, use `Files.getRepresentationContent( fileID, representationType, options, callback)` instead. Migration details can be found [here](https://github.com/box/box-node-sdk/blob/v3.0.0/docs/upgrade/2.x.x%20to%203.x.x.md) ### Dependency Upgrades - Bumped `jsonwebtoken` from 8.5.1 to 9.0.0. ([#802](https://github.com/box/box-node-sdk/pull/802)) ([5b1d4e9](https://github.com/box/box-node-sdk/pull/828/commits/5b1d4e9ec557c14c1d27695733cc0bcae49061cb)) - Bumped `vm2` from 3.9.11 to 3.9.19 ([#826](https://github.com/box/box-node-sdk/pull/826)) ([220df76](https://github.com/box/box-node-sdk/commit/220df765080bc27c91daed51ac46620f6bc8b9ed)) ## 2.10.0 (2023-05-11) ### New Features and Enhancements - Added support for ethical wall API ([#822](https://github.com/box/box-node-sdk/issues/822)) ([4814af3](https://github.com/box/box-node-sdk/commit/4814af35c1741fbfe3fa03f8f0412ade8b38dfcc)) - Added `name` and `signature_color` fields to `SignRequest` and `SignRequestCreateRequest` types and `login_required` field to `SignRequestCreateSigner` type ([#822](https://github.com/box/box-node-sdk/issues/822)) ([4814af3](https://github.com/box/box-node-sdk/commit/4814af35c1741fbfe3fa03f8f0412ade8b38dfcc)) ## 2.9.0 (2023-04-19) ### New Features and Enhancements - New fields in `retention-policy` and `retention-policy-assignment` ([#803](https://github.com/box/box-node-sdk/issues/803)) ([f14ba84](https://github.com/box/box-node-sdk/commit/f14ba84013985513854ad396581d085d1d4f0255)) ### Bug Fixes - return empty object when `tos` status is not present ([#797](https://github.com/box/box-node-sdk/issues/797)) ([12fd9b0](https://github.com/box/box-node-sdk/commit/12fd9b053707471722f53cd1760c8cf59451fe8d)) ### 2.8.1 (2023-01-05) ### Bug Fixes - Fix `getReadStream` delay reading ([#790](https://github.com/box/box-node-sdk/issues/790)) ([6bfc1ee](https://github.com/box/box-node-sdk/commit/6bfc1eebeb9a31606ff96127eeb1ad03d2f13d9c)) ## 2.8.0 (2022-12-21) ### New Features and Enhancements - Session termination ([#782](https://github.com/box/box-node-sdk/issues/782)) ([7fb56c6](https://github.com/box/box-node-sdk/commit/7fb56c625f8eb03e6a5354b67a0debfd9e4ad7c8)) ### 2.7.2 (2022-11-10) ### Bug Fixes - Add `fields` query parameter to file and folder update ([#776](https://github.com/box/box-node-sdk/issues/776)) ([a327deb](https://github.com/box/box-node-sdk/commit/a327debc83d98a4190a5a16cf848417ea5714db9)) ### 2.7.1 (2022-10-28) ### Bug Fixes - Export missing `RetentionType` ([#774](https://github.com/box/box-node-sdk/issues/774)) ([7e6b244](https://github.com/box/box-node-sdk/commit/7e6b244ba63d363ecc921be570140c9e1ed1d032)) ## 2.7.0 (2022-10-27) ### New Features and Enhancements - Add support for modifiable retention policies & enable deleting retention policy assignment ([#769](https://github.com/box/box-node-sdk/issues/769)) ([5e8c776](https://github.com/box/box-node-sdk/commit/5e8c776fc94e9dcf313cc15c96e42fbffaf36b74)) ## 2.6.0 (2022-09-23) ### New Features and Enhancements - Add `content_type`, `redirect_url` field to Sign Request ([#758](https://github.com/box/box-node-sdk/issues/758)) ([8abb9b6](https://github.com/box/box-node-sdk/commit/8abb9b602b13cd72c6c8de549d19756ae147b403)) - Add sign request webhook ([#760](https://github.com/box/box-node-sdk/issues/760)) ([e92d1ab](https://github.com/box/box-node-sdk/commit/e92d1abee5faf58166f4892d7b2e6bc3c6480ac6)) - Added support for Access Only Collaboration ([#759](https://github.com/box/box-node-sdk/issues/759)) ([dd8261f](https://github.com/box/box-node-sdk/commit/dd8261f970c207854058c3ed86ccabf9bec05ea8)) ## 2.5.0 (2022-08-09) ### New Features and Enhancements - Added support update and remove user avatar ([#744](https://github.com/box/box-node-sdk/issues/744)) ([aaf6175](https://github.com/box/box-node-sdk/commit/aaf617528de5c61e19cfb25e28fe77c01532b9fa)) ### Bug Fixes - Fix error while generate token using oauth ([#750](https://github.com/box/box-node-sdk/issues/750)) ([f826291](https://github.com/box/box-node-sdk/commit/f82629108a1af6c4d160de1976fd01fdf0d8dde3)), closes [#286](https://github.com/box/box-node-sdk/issues/286) - Fix lint error in test file ([#747](https://github.com/box/box-node-sdk/issues/747)) ([3b1e10d](https://github.com/box/box-node-sdk/commit/3b1e10d206aa88a8bf99989bb7ff85776a9864a4)) ## 2.4.0 (2022-07-13) ### New Features and Enhancements - Added support for file requests ([#742](https://github.com/box/box-node-sdk/issues/742)) ([30b2e76](https://github.com/box/box-node-sdk/commit/30b2e767c6c3af68e1463cc801914f9889dc593c)) - Added support of `admin_logs_streaming` stream type ([#740](https://github.com/box/box-node-sdk/issues/740)) ([406950a](https://github.com/box/box-node-sdk/commit/406950a03af54a022427e0532e889a61e0d25152)) ### Bug Fixes - properly handle client errors in streams ([#736](https://github.com/box/box-node-sdk/issues/736)) ([12378d6](https://github.com/box/box-node-sdk/commit/12378d6755c2e3cddcb79439cdcbbe8e1e61df13)) ## 2.3.0 (2022-04-28) ### New Features and Enhancements - Add `description` parameter to `uploadFile` methods ([#730](https://github.com/box/box-node-sdk/issues/730)) ([2596584](https://github.com/box/box-node-sdk/commit/2596584dffb44c1995c8b6b3faa67564f4d32499)) ### Bug Fixes - added missing `js-docs` on shared links ([#731](https://github.com/box/box-node-sdk/issues/731)) ([3554d41](https://github.com/box/box-node-sdk/commit/3554d41d9050e7a81224c35e3e2e257604a0b41b)) ## 2.2.0 (2022-04-20) ### New Features and Enhancements - editable shared links ([#722](https://github.com/box/box-node-sdk/issues/722)) ([f0c0135](https://github.com/box/box-node-sdk/commit/f0c0135511fde46144e6c496432104321af443f6)) ## 2.1.0 (2022-03-28) ### New Features and Enhancements - Client Credentials Grant authentication method ([#709](https://github.com/box/box-node-sdk/issues/709)) ([fbf4e80](https://github.com/box/box-node-sdk/commit/fbf4e80648821e38479b24bf489e7d222ae6c18f)) - Deprecating `index_name` when executing metadata query ([#686](https://github.com/box/box-node-sdk/issues/686)) ([e01cc65](https://github.com/box/box-node-sdk/commit/e01cc650e4e793955be543e93928ad82a3254492)) - **test:** add support for testing with Jest ([#676](https://github.com/box/box-node-sdk/issues/676)) ([1a11759](https://github.com/box/box-node-sdk/commit/1a11759db999510c69d6a27f7becd565620bb000)) ### Bug Fixes - Client Credentials Grant authentication method supports token down-scoping ([#710](https://github.com/box/box-node-sdk/issues/710)) ([730368f](https://github.com/box/box-node-sdk/commit/730368f410ff56e9a8c90feea2192b29c08df198)) - Fix JWT expiration field being float instead of integer ([#715](https://github.com/box/box-node-sdk/issues/715)) ([7e950f1](https://github.com/box/box-node-sdk/commit/7e950f1265a52ce251c42a186c8196089a9ed858)), closes [#713](https://github.com/box/box-node-sdk/issues/713) ## 2.0.0 (2021-09-29) ### ⚠ BREAKING CHANGES - Drop support for Node 6,7 ([#670](https://github.com/box/box-node-sdk/pull/670)) ### New Features and Enhancements: - Add support for is_external_collab_restricted User property ([#668](https://github.com/box/box-node-sdk/pull/668)) - Bump proxy-agent from 4.0.0 to 5.0.0 ([#664](https://github.com/box/box-node-sdk/pull/664)) ## 1.39.0 (2021-08-30) ### New Features and Enhancements: - Add support for Box Sign API ([#658](https://github.com/box/box-node-sdk/pull/658)) - Enhance TS Imports ([#656](https://github.com/box/box-node-sdk/pull/656)) ## 1.38.0 (2021-08-05) ### New Features and Enhancements: - Add sensitive-language event types for admin invites ([#648](https://github.com/box/box-node-sdk/pull/648)) - Use BetterDocs to adapt JSDocs to TypeScript ([#646](https://github.com/box/box-node-sdk/pull/646)) - Change ProxyAgent import to be dynamic ([#641](https://github.com/box/box-node-sdk/pull/641)) - New API for get files and file versions under retention ([#585](https://github.com/box/box-node-sdk/pull/585)) ### Bug Fixes: - Deeply freeze Config except Buffers and Readable streams ([#651](https://github.com/box/box-node-sdk/pull/651)) - Fix a typo in docs of src/managers/search.ts ([#649](https://github.com/box/box-node-sdk/pull/649)) - Update broken documentation link ([#647](https://github.com/box/box-node-sdk/pull/647)) - fix type annotations for exchangeToken functions ([#645](https://github.com/box/box-node-sdk/pull/645)) - Deprecate files getThumbnail API in favor of getRepresentationContent ([#627](https://github.com/box/box-node-sdk/pull/627)) ## 1.37.2 (2021-05-20) ### Bug Fixes: - Fix backwards compatibility issue by moving some TypeScript @types as direct dependencies ([#630](https://github.com/box/box-node-sdk/pull/630)) ## 1.37.1 (2021-05-19) ### Bug Fixes: - Insensitive language: replace whitelist with allowlist ([#625](https://github.com/box/box-node-sdk/pull/625)) ## 1.37.0 (2021-04-16) ### New Features and Enhancements: - Add support for copyInstanceOnItemCopy field for metadata templates ([#572](https://github.com/box/box-node-sdk/pull/572)) ### Bug Fixes: - Fix webhook signature validation ([#568](https://github.com/box/box-node-sdk/pull/568)) - Update dependencies to patch security vulnerabilities ([#578](https://github.com/box/box-node-sdk/pull/578)) ## 1.36.0 (2021-01-27) ### New Features and Enhancements: - Add folder lock functionality ([#560](https://github.com/box/box-node-sdk/pull/560)) - Add support for filtering groups by name ([#561](https://github.com/box/box-node-sdk/pull/561)) ### Bug Fixes: - Update proxy-agent to patch proxy support issue ([#563](https://github.com/box/box-node-sdk/pull/563)) - Update dependencies to patch security vulnerabilities ([#566](https://github.com/box/box-node-sdk/pull/566)) ## 1.35.0 (2020-11-02) ### New Features and Enhancements: - Add support for search param to get shared link items ([#547](https://github.com/box/box-node-sdk/pull/547)) ## 1.34.3 (2020-10-02) ### Bug Fixes: - Upgrade ajv dependency ([#545](https://github.com/box/box-node-sdk/pull/545)) ## 1.34.2 (2020-08-20) - Make iterator bug fix for uploading files non breaking ([#534](https://github.com/box/box-node-sdk/pull/534)) ## 1.34.1 (2020-08-17) - Fix iterator bug for uploading new file versions ([#531](https://github.com/box/box-node-sdk/pull/531)) ## 1.34.0 (2020-08-04) - Add zip functionality ([#525](https://github.com/box/box-node-sdk/pull/525)) - Add proxy support for `http`, `https`, `socks` and `pac` protocols ([#529](https://github.com/box/box-node-sdk/pull/529)) ## 1.33.0 (2020-06-25) - Add path parameter sanitization ([#505](https://github.com/box/box-node-sdk/pull/505)) - Add support for all streams for uploading files ([#519](https://github.com/box/box-node-sdk/pull/519)) ## 1.32.0 (2020-04-01) - Temporarily removed Node 4 and Node 5 builds from Travis, due to tests not passing. Will investigate, going forward ([#495](https://github.com/box/box-node-sdk/pull/495)). - Fixed an issue where an error is thrown during a retry when a response is not returned by the previous call ([#477](https://github.com/box/box-node-sdk/pull/477)). - Added the ability to [query](./docs/metadata.md#query) Box items based on their metadata ([#487](https://github.com/box/box-node-sdk/pull/487)). ## 1.31.0 (2020-02-13) - Fixed Authentication Request Retries - Added marker-based paging for users endpoints - Added `getNextMarker()` to PagingIterator to get the next marker ## 1.30.0 (2019-11-21) - Deprecated Batch API methods - Added support for [token exchange](./lib/box-client.js#L495) using shared links ## 1.29.1 (2019-08-22) - Fixed an issue where JWT authentication requests could fail after being rate limited ## 1.29.0 (2019-04-25) Added convenience methods for setting metadata on [files](./docs/metadata.md#set-metadata-on-a-file) and [folders](./docs/metadata.md#set-metadata-on-a-folder) ([#376](https://github.com/box/box-node-sdk/pull/376)) ## 1.28.0 (2019-03-28) Added methods for [moving](./docs/web-links.md#move-a-web-link) and [copying](./docs/web-links.md#move-a-web-link) weblinks, as well as [adding or removing from a collection](./docs/web-links.md#add-web-link-to-a-collection) ## 1.27.0 (2019-02-28) - Added the trace ID from API response headers to error messages for easier debugging - Added more safety checks in the error flow to protect against throwing when handling a malformed request - Added support for [retrieving a user's avatar image](./docs/users.md#get-user-avatar) ## 1.26.2 (2019-02-22) Fixed an error where under high request rates, code in the error handling logic could throw when handling a malformed request ## 1.26.1 (2019-02-12) - Fixed an error where some methods could throw an error when constructing an iterator ## 1.26.0 (2019-02-12) - Added support for [replying to a comment](./docs/comments.md#reply-to-a-comment) (thanks @jpan-box!) Fixed an issue where calling `client.events.get()` could return an iterator that would only iterate over the first chunk of events. This method will now always return the raw JSON data in order to enable manual paging. For automatic paging through events, `client.events.getEventStream()` or `client.events.getEnterpriseEventStream()` should be used instead. ## 1.25.0 (2019-01-24) - Added the `retryStrategy` config parameter to allow customizing how the SDK retries failing requests ## 1.24.1 (2019-01-11) - Fixed an issue where token expiration was not being correctly handled ## 1.24.0 (2018-12-10) - Added a configuration option for populating the first-party client analytics header information ## 1.23.0 (2018-11-21) Added an `etag` option to common file and folder methods to allow handling race conditions - [`client.files.update()`](./docs/files.md#update-a-files-information) - [`client.files.delete()`](./docs/files.md#delete-a-file) - [`client.files.deletePermanently()`](./docs/trash.md#delete-a-file-from-the-trash) - [`client.files.deleteVersion()`](./docs/files.md#delete-a-previous-file-version) - [`client.folders.update()`](./docs/folders.md#update-a-folders-information) - [`client.folders.delete()`](./docs/folders.md#delete-a-folder) - [`client.folders.deletePermanently()`](./docs/trash.md#delete-a-folder-from-the-trash) ## 1.22.1 (2018-11-15) - Fixed an issue where retrying JWT auth token requests would sometimes fail due to a non-unique `jti` claim ## 1.22.0 (2018-09-17) - Chunked Uploader methods now return promises for [simpler handling of chunked uploads](./docs/files.md#automatic-uploader) - File attributes to set on the newly-uploaded file can now be [passed via `options.fileAttributes`](./docs/files.md#automatic-uploader) when creating a Chunked Uploader ## 1.21.0 (2018-09-13) - Added the ability to close an Event Stream by calling `eventStream.destroy()` (thanks @boneskull!) - Improved error messages related to certain authentication failure cases ## 1.20.0 (2018-08-09) - Added missing values to the `client.webhooks.triggerTypes` enum (thanks @MathersMax!) - Added support for [Metadata Cascade Policies](./docs/metadata.md#create-cascade-policy) ## 1.19.0 (2018-06-14) - Added `generateRepresentations` option to [`files.getRepresentationContent()`](./docs/files.md#get-representation-content) ## 1.18.0 (2018-05-24) Updated dependencies to resolve potential security issues: - `request@2.87.0` - Transitive dependencies of `jsonwebtoken@8.2.1` Added a static `BoxSDK.getBasicClient()` method to enable creating a client without needing to specify a client ID and secret (thanks to @cbetta) ## 1.17.0 (2018-05-10) - Updated dependencies: `request@2.85.0`, `jsonwebtoken@8.2.1` - Added support for [Storage Policies](https://developer.box.com/127ef6eef52e4e56f73da7cb35736016/storage-policies.md) - Added the option to use a Token Store for caching tokens with App Auth using JWT ## 1.16.1 (2018-04-26) - Fixed a bug where metadata template deletion would not properly return results via callback ## 1.16.0 (2018-04-10) - Added support for [assigning Retention Policies to Metadata Templates](https://github.com/box/box-node-sdk/blob/main/docs/retention-policies.md#assign-retention-policy) ## 1.15.0 (2018-03-29) - Fixed [`client.webhooks.validateMessage() and `sdk.validateWebhookMessage()`](https://github.com/box/box-node-sdk/blob/main/docs/webhooks.md#validate-a-webhook-message) to accept the request body as an `Object` - Fixed `sdk.configure()` to correct reconfigure all options - Improved error messages for API errors and added the request object as `error.request` for easier debugging ## 1.14.1 (2018-03-13) - Fixed a bug when `files.getReadStream()` was called with null options ## 1.14.0 (2018-03-12) - Added support for [getting a metadata template by ID](./docs/metadata.md#get-by-id) - Added a `byteRange` option to [file download](./docs/files.md#download-a-file) to support partial file download - Improved error messages when using promises and in authentication flows ## 1.13.0 (2018-03-01) - Added support for getting a [stream of file representation contents](./docs/files.md#get-representation-content) - Switched to using exponential backoff for request retries ## 1.12.1 (2018-01-25) - Fixed an issue where chunked uploader would not work with response streams from the request library (0e7014561f9cd0f7f38f98536b3f0c3946231d2e) ## 1.12.0 (2018-01-11) - Added support for [metadata template deletion](./docs/metadata.md#delete-metadata-template) ## 1.11.0 (2017-12-12) - Added options to preserve file timestamps on [file upload](./docs/files.md#upload-a-file) and to rename a file or preserve modification timestamp on [new version upload](./docs/files.md#upload-a-new-version-of-a-file) - Added [Collaboration Whitelist](./docs/collaboration-whitelist.md) functionality to allow enterprise admins to control which external users can collaborate on their content - Added an option to Token Exchange to generate [annotator tokens](./docs/authentication.md#annotator-tokens) for use with Box View ## 1.10.1 (2017-11-28) - Updated to [jsonwebtoken@8.1.0](mailto:jsonwebtoken@8.1.0) to fix an issue where some users were getting an error when using App Auth ## 1.10.0 (2017-01-14) - Added support for [Terms of Service](https://developer.box.com/932f3810fb86d1a28be4edb39d4c82da/terms-of-service.md) endpoints - Fixed a bug where receiving a collection without paging parameters from the API would cause the SDK to throw an exception when using the `iterators` SDK option. Now, this will return an iterator over the items returned by the API. - Fixed a bug in Token Exchange where passing multiple scopes would result in an error - Added support for [getting Representations info on a file](./docs/files.md#get-representation-info) ## 1.9.0 (2017-09-12) - Fixed token methods to return bluebird Promises instead of native Promises - Added support for the `notify` and `can_view_path` options on Collaborations ## 1.8.0 (2017-08-21) - Added support for [Batch API](./docs/client.md#batch-api) - Fixed a bug where the Event Stream would make more API calls than necessary, potentially hitting Box API rate limits - Added Promise support to methods on the SDK object - Added Node.js version to the User-Agent header that the SDK sends - Fixed a bug where using multiple Persistent Clients instances could cause some clients to end up with expired tokens ## 1.7.0 (2017-07-19) - Add support for passing IP to all token methods, and fixed a bug where a client's IP was not being correctly reported on token refreshes ## 1.6.0 (2017-06-23) - Added [Recent Items](https://developer.box.com/4d81cc8152b9a29d4fa3be3b89640b0c/recent-items.md) support - Updated app auth expiration time default value and validation ## 1.5.1 (2017-06-15) - Revert deep-freezing Config properties, since it was causing errors ## 1.5.0 (2017-06-15) - Added support for [Token Exchange](./docs/authentication.md#token-exchange), which allows a client to get downscoped tokens suitable for passing to a browser app or worker process. - Ensured deeply-nested Config properties are immutable ## 1.4.2 (2017-05-22) - Fixed `BoxSDK.getPreconfiguredInstance()` to configure webhook keys ## 1.4.1 (2017-05-22) - Fixed `BoxSDK.getPreconfiguredInstance()` when app auth setttings are not populated ## 1.4.0 (2017-05-19) - Added support for [file collaborations](./docs/collaborations.md#add-a-collaboration). Users can now invite others to collaborate on single files. See [the blog post](https://blog.box.com/blog/file-collaboration-api/) for more information. - Fixed an issue where users were unable to use JWT Server Auth when their computers' clocks were not synchronized with the Box API servers. - All asynchronous client methods now return Promises in addition to taking a (now-optional) callback parameter, so you can write more modern JS with the SDK. - The SDK can now be preconfigured using a JSON blob that can be downloaded in the Box Dev Console for JWT Server Authentication apps, making it easier to get started developing! - Added support for [chunked upload](./docs/files.md#chunked-upload), where a large file can be uploaded one piece at a time. This makes large file uploads much faster and more reliable, since parts can be uploaded in parallel and failed parts can be retried in isolation. - Added an `is_confirmed` option to [email alias creation](./docs/users.md#add-email-alias) for admins to auto-confirm the alias. - Added support for the [Enterprise Events stream](./docs/events.md#enterprise-events). - Added an option to have collections methods (e.g. `folders.getItems()`, `enterprise.getUsers()`, etc) return [async iterators](./README.md#iterators) that will automatically page through the collection. This conforms to the [proposed async iteration spec](https://github.com/tc39/proposal-async-iteration), which will eventually allow them to be used in ergonomic for-await-of loop syntax. ## 1.3.0 (2017-01-24) - Added `BoxSDK.validateWebhookMessage()` and `client.webhooks.validateMessage()` for validating webhook messages from Box ## 1.2.0 (2016-12-12) - Added methods for all API endpoints; we now have full API coverage :tada: - Added support for renaming a file or folder on copy - Added `client.asUser(userID)` and `client.asSelf()` to support making calls on behalf of managed users - Fixed event streams so they don't go into an infinite error loop when auth expires - Fixed an error where App Auth clients would not be able to authorize due to clock skew - Fixed the `mdfilters` parameter in `client.search.query()` to support metadata search - Cloned options objects to prevent modification of passed-in objects by the SDK - Added better error messaging to the sample app ## 1.1.0 (2016-09-27) - Added endpoint to get a file's tasks - Fixed issues with stream uploads - Improved performance of file uploads - Added endpoints to delete files and folders from trash - Added endpoint to get a trashed folder - Upgraded request dependency to fix ReDoS vulnerability ## [1.0.0] (2016-07-13) Initial release. --- ## Untitled *Type: page* App Auth Sample App To get started: Clone the SDK repo Edit examples/app-auth/index.js with your app credentials Run the sample app: # App Auth Sample App To get started: 1. Clone the SDK repo 2. Edit `examples/app-auth/index.js` with your app credentials 3. Run the sample app: ``` cd examples/app-auth/ npm install npm start ``` --- ## Untitled *Type: page* Deprecation notice This version of the Box Node SDK is under maintenance mode, and will be deprecated soon, only critical security updates… # Deprecation notice This version of the Box Node SDK is under maintenance mode, and will be deprecated soon, only critical security updates and bug fixes will be provided. We recommend using the new version Box Typescript SDK, which can be found at [box/box-typescript-sdk-gen](https://github.com/box/box-typescript-sdk-gen) You can find the migration guide [here](https://github.com/box/box-typescript-sdk-gen/blob/main/migration-guide.md) for transitioning from Box Node SDK to the new `box-typescript-sdk-gen` package. If you have any questions, please create an issue in the new repository or reach out to [Box Developer Support](https://developer.box.com/support/). # Box Node.js SDK [](https://snyk.io/test/github/box/box-node-sdk) [](http://opensource.box.com/badges) [](https://coveralls.io/github/box/box-node-sdk?branch=main) A Node.js interface to the [Box Content API](https://developer.box.com/reference/). - [Deprecation notice](#deprecation-notice) [Box Node.js SDK](#box-nodejs-sdk) - [Installation](#installation) - [Getting Started](#getting-started) [Creating API Clients](#creating-api-clients) - [Basic Client](#basic-client) - [Persistent Client](#persistent-client) - [App Auth Client](#app-auth-client) [Using the Client to Make API Calls](#using-the-client-to-make-api-calls) - [Constructing API Calls Manually](#constructing-api-calls-manually) [FIPS 140-2 Compliance](#fips-140-2-compliance) [Versions](#versions) - [Supported Version](#supported-version) - [Version schedule](#version-schedule) [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) [Contributing to the Box Node.js SDK](#contributing-to-the-box-nodejs-sdk) [Changelog](#changelog) [Upgrades](#upgrades) [Documentation](#documentation) [Copyright and License](#copyright-and-license) ## Installation Node SDK Installation [details](https://developer.box.com/guides/tooling/sdks/node/). ``` npm install --save box-node-sdk ``` ## Getting Started To get started with the SDK, get a Developer Token from the Configuration page of your platform app in the [Box Developer Console](https://app.box.com/developers/console). You can use this token to make test calls for your own Box account. ``` var BoxSDK = require('box-node-sdk'); // Initialize the SDK with your app credentials var sdk = new BoxSDK({ clientID: 'CLIENT_ID', clientSecret: 'CLIENT_SECRET', }); // Create a basic API client, which does not automatically refresh the access token var client = sdk.getBasicClient('DEVELOPER_TOKEN'); // Get your own user object from the Box API // All client methods return a promise that resolves to the results of the API call, // or rejects when an error occurs client.users .get(client.CURRENT_USER_ID) .then((user) => console.log('Hello', user.name, '!')) .catch((err) => console.log('Got an error!', err)); ``` ## Creating API Clients Clients are used to communicate with the API on behalf of a user. Box supports three different types of client: - **Basic Client:** Simple, makes calls via the given access token until the access token expires - **Persistent Client:** For use with traditional OAuth2 apps, can refresh its tokens automatically and persist them via a token store - **App Auth Client:** Uses the app auth JWT grant to act on behalf of app/managed users and create new tokens automatically ### Basic Client Returns a Box Client with a Basic API Session. The client is able to make requests on behalf of a user. A basic session has no access to a user's refresh token. Because of this, once the session's tokens expire the client cannot recover and a new session will need to be generated. ``` var client = BoxSDK.getBasicClient('ACCESS_TOKEN'); ``` ### Persistent Client Returns a Box Client with a persistent API session. A persistent API session helps manage the user's tokens, and can refresh them automatically if the access token expires. If a central data-store is given, the session can read & write tokens to it. NOTE: If tokenInfo or tokenStore are formatted incorrectly, this method will throw an error. If you haven't explicitly created either of these objects or are otherwise not completely confident in their validity, you should wrap your call to getPersistentClient in a try-catch to handle any potential errors. If you do not provide a token store object, the SDK will continue refreshing tokens locally as long as the Node.js process lives, but will not able to restore the user's authentication on process restart or share that authentication state between different processes. ``` var client = sdk.getPersistentClient(tokenInfo, null); ``` Providing a token store will allow the SDK to persist the user's authentication state so that you can resume making API calls as a user if the Node.js process needs to restart, or share the authentication state between multiple different processes. ``` var client = sdk.getPersistentClient(tokenInfo, tokenStore); ``` The token store is the interface used by persistent clients to interact with the consumer app's central storage layer. For a token store to be valid, it must have the following three methods: ``` store.read(function (err, data) {}); // read TokenInfo from app central store. store.write(tokenInfo, function (err, data) {}); // write TokenInfo to the app's central store. store.clear(function (err, data) {}); // delete TokenInfo from the app's central store. ``` Note that these methods don't pass in identifying information as arguments. You'll most likely need to create them on-demand for each client. ### App Auth Client App Auth allows an platform app to fully manage the Box accounts of its users; they do not have direct login credentials to Box and all operations are performed through the API using a JWT grant. If you have a JSON configuration file from the [Box Developer Console](https://app.box.com/developers/console) that includes your private key information, you can import that directly to create an SDK instance: ``` var sdkConfig = require('/path/to/config.json'); var sdk = BoxSDK.getPreconfiguredInstance(sdkConfig); // Get the service account client, used to create and manage app user accounts // The enterprise ID is pre-populated by the JSON configuration, // so you don't need to specify it here var serviceAccountClient = sdk.getAppAuthClient('enterprise'); // Get an app user or managed user client var appUserClient = sdk.getAppAuthClient('user', 'YOUR-APP-USER-ID'); ``` Otherwise, you can manually pass the necessary configuration parameters to the SDK: ``` var sdk = new BoxSDK({ clientID: 'CLIENT_ID', clientSecret: 'CLIENT_SECRET', appAuth: { keyID: 'PUBLIC_KEY_ID', privateKey: 'PRIVATE_KEY', passphrase: 'PRIVATE_KEY_PASSPHRASE', }, }); // Get the service account client, used to create and manage app user accounts var serviceAccountClient = sdk.getAppAuthClient( 'enterprise', 'APP_ENTERPRISE_ID' ); // Get an app user or managed user client var appUserClient = sdk.getAppAuthClient('user', 'YOUR-APP-USER-ID'); ``` ## Using the Client to Make API Calls The different API endpoints you can call are represented as methods, grouped into managers by the type of object they interact with. For example: ``` // Get the user object for the current user client.users .get(client.CURRENT_USER_ID) .then((currentUser) => { /* ... */ }) .catch((error) => { /* handle any errors */ }); // Update the name for folder with ID 123 client.folders .update('123', { name: 'New Folder Name' }) .then((folderInfo) => { /* ... */ }) .catch((error) => { /* handle any errors */ }); // Upload a new file to folder 123 client.files .uploadFile('123', 'bicycle.png', fileContents) .then((fileObject) => { /* ... */ }) .catch((error) => { /* handle any errors */ }); // Delete the comment with ID 456 client.comments .delete('456') .then(() => { /* ... */ }) .catch((error) => { /* handle any errors */ }); ``` For complete documentation about the available operations, please see the [SDK documentation pages](./docs) and the auto-generated [JSDocs](https://rawgit.com/box/box-node-sdk/main/docs/jsdoc/index.html). These contain detailed information about which methods are available and how to use them. ### Constructing API Calls Manually The SDK also exposes low-level request methods for constructing your own API calls. These can be useful for adding your own API calls that aren't yet explicitly supported by the SDK. The low-level methods always return a response object that contains the raw API response, and do not turn non-2xx status codes into errors like the normal client methods do. ``` // GET /files/123?fields=id,name client.get('/files/123', {qs: {fields: 'id,name'}}) .then(response => { /* ... */ }) .catch(error => { /* handle any errors */ }); // PUT /files/123 // { // "name": "New File Name" // } client.put('/files/123', {body: {name: 'New File Name'}}); .then(response => { /* ... */ }) .catch(error => { /* handle any errors */ }); // DELETE /files/123 client.del('/files/123'); .then(response => { /* ... */ }) .catch(error => { /* handle any errors */ }); ``` ## FIPS 140-2 Compliance The Box Node SDK allows the use of FIPS 140-2 validated SSL libraries, such as OpenSSL 3.0. However, some actions are required to enable this functionality. By default, the version of OpenSSL Node.js includes is not FIPS enabled. Therefore, if you want to use OpenSSL 3.0 with FIPS, you need to [build OpenSSL 3.0 with FIPS enabled](https://github.com/openssl/openssl/blob/master/README-FIPS.md) and then build Node.js use the shared OpenSSL 3.0 library. According to [Node.js OpenSSL Strategy](https://github.com/nodejs/TSC/blob/main/OpenSSL-Strategy.md) document, you can use the OpenSSL 3.0 from Node.js v16 or later. ## Versions We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. See [version strategy](https://developer.box.com/8249b54722608e671700c4582b0da591/VERSIONS.md) for details which is effective from 30 July 2022. ### Supported Version Only the current MAJOR version of SDK is supported. New features, functionality, bug fixes, and security updates will only be added to the current MAJOR version. A current release is on the leading edge of our SDK development, and is intended for customers who are in active development and want the latest and greatest features. Instead of stating a release date for a new feature, we set a fixed minor or patch release cadence of maximum 2-3 months (while we may release more often). At the same time, there is no schedule for major or breaking release. Instead, we will communicate one quarter in advance the upcoming breaking change to allow customers to plan for the upgrade. We always recommend that all users run the latest available minor release for whatever major version is in use. We highly recommend upgrading to the latest SDK major release at the earliest convenient time and before the EOL date. ### Version schedule | Version | Supported Environments | State | First Release | EOL/Terminated | | --- | --- | --- | --- | --- | | 3 | Node.js >= 14 and <= 20 | Supported | 23 May 2023 | TBD | | 2 | Node.js >= 8 and <= 14 | Maintained | 29 Sep 2021 | 23 Jul 2023 | | 1 | | EOL | 28 Mar 2019 | 29 Sep 2021 | ## Questions, Bugs, and Feature Requests? [Browse the issues tickets](https://github.com/box/box-node-sdk/issues)! Or, if that doesn't work, [file a new one](https://github.com/box/box-node-sdk/issues/new) and someone will get back to you. If you have general questions about the Box API, you can post to the [Box Developer Forum](https://community.box.com/t5/Developer-Forum/bd-p/DeveloperForum). ## Contributing to the Box Node.js SDK 1. Clone this repo. 2. Run `npm install`. 3. Run `npm test` to ensure everything is working. Make the changes you want in the `lib/` directory. Be sure to add corresponding tests in the `tests/` directory! 4. Run the unit tests by command `npm run test` and integration test as instructed [here](https://developer.box.com/f7109e04501d1e9338129a54b95bd487/README.md). 5. Create a pull request with your changes — we'll review it and help you get it merged. Currently, the **Sign Request** module is generated automatically from OpenAPI specs. To re-generate this module, download the latest version of Box OpenAPI specs [here](https://raw.githubusercontent.com/box/box-openapi/en/openapi.json), save it to the root directory and run `npm run codegen`. For more information, please see [the Contribution guidelines](https://developer.box.com/c36870c09fe3c52df7afbcb304196baf/CONTRIBUTING.md). ## Changelog See [CHANGELOG.md](https://developer.box.com/64ac35fa5d9a1316c1c1e819c1da7b1d/CHANGELOG.md). ## Upgrades You can read about how to migrate to the new version [here](./docs/upgrade/). ## Documentation You can find guides and tutorials in the `docs` directory. - [Configuration](https://developer.box.com/72e1f486598c9052135a57b2d613a50b/configuration.md) ## Copyright and License Copyright 2018 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- ## Untitled *Type: page* Integration Tests Running integration tests locally Create Platform Application To run integration tests locally you will need a Custom App… # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created at [https://cloud.app.box.com/developers/console](https://cloud.app.box.com/developers/console) with `Server Authentication (with JWT)` selected as authentication method. Once created you can edit properties of the application: - In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. - In section `Advanced Features` enable `Make API calls using the as-user header` and `Generate user access tokens`. Now select `Authorization` and submit application to be reviewed by account admin. ### Export configuration There are two ways to set up JWT configuration: 1. First method: Select `Configuration` tab and in the bottom in the section `App Settings` download your app configuration settings as JSON. - Specify the path to the JWT config file in `test-config.json`, e.g. `"jwt_file_path": "/Users/me/jwt-config.json"` - Specify id of admin user account in `test-config.json`, e.g. `"admin_user_id": "13855142101"` 1. Alternatively: Select `Configuration` tab and in the bottom in the section `App Settings` download your app configuration settings as JSON. - Encode configuration file to Base64, e.g. using command: `base64 -i path_to_json_file` - Set environment variable: `JWT_CONFIG` with base64 encoded jwt configuration file - Set environment variable: `ADMIN_USER_ID` with id of admin user account ### Running integration tests To run integration tests, you can run command: ``` npm run jest ``` --- ## Untitled *Type: page* Migration guide for versions 2.x.x -> 3.x.x Runtime requirements Dependencies jsonwebtoken Removed deprecated methods and classes… # Migration guide for versions 2.x.x -> 3.x.x - [Runtime requirements](#runtime-requirements) [Dependencies](#dependencies) - [`jsonwebtoken`](#jsonwebtoken) [Removed deprecated methods and classes](#removed-deprecated-methods-and-classes) - [Collaboration Whitelist](#collaboration-whitelist) - [Collaboration Allowlist](#collaboration-allowlist) - [Files](#files) This release contains a number of changes. The most notable are: - Drop support for Node versions below 12. - Bump `jsonwebtoken` to version 9.0.0. # Runtime requirements From this version, we will only support Node versions 12 and above. This is due to the fact that `jsonwebtoken` version 9.0.0 dropped support for Node versions below 12. If you are using an older version of Node, you will need to upgrade to a newer version. # Dependencies ## jsonwebtoken We have bumped the version of `jsonwebtoken` to 9.0.0 to fix a security vulnerability. If you are using `jsonwebtoken` directly, you will need to upgrade to version 9.0.0 to avoid conflicts. # Removed deprecated methods and classes ## Box Client The deprecated `BoxClient.batch()` and `BoxClient.batchExec()` methods have been removed, please make calls in parallel instead. Attribute `staleBufferMS` in [`UserConfigurationOptions`](http://opensource.box.com/box-node-sdk/jsdoc/global.html#UserConfigurationOptions) class has been removed, you can use `expiredBufferMS` attribute to set the time before we consider the token expired. ## Collaboration Whitelist The deprecated `CollaborationWhitelist` class has been removed, please use [`CollaborationAllowlist`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html) class instead. ## Collaboration Allowlist Method `CollaborationAllowlist.getWhitelistedDomain()` has been removed, now to get the allow listed domain, use [`CollaborationAllowlist.getAllowlistedDomain()`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#getAllowlistedDomain) instead. Method `CollaborationAllowlist.getAllWhitelistedDomains()` has been removed, now to get all allow listed domains, use [`CollaborationAllowlist.getAllAllowlistedDomains()`](http://opensource.box.com/box-node-sdk/jsdoc/CollaborationAllowlist.html#getAllAllowlistedDomains) instead. ## Files Method `Files.getThumbnail( fileID: string, options?: Record<string, any>, callback?: Function )` has been removed, use [`Files.getRepresentationContent( fileID, representationType, options, callback)`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getRepresentationContent) instead. With this method, you can generate a representation of a file. A representation is an alternative asset for a file stored in Box. These assets can be PDFs, thumbnails, or text extractions. Representations are automatically generated for the supported file types, either when uploading to Box or when requesting the asset. **Useful links** - [Get Thumbnail Representation](https://developer.box.com/guides/representations/thumbnail-representation/) - [Supported File Types and Representations](https://developer.box.com/guides/representations/supported-file-types/) **Example** To get the thumbnail for a file has the extension in this list of [supported file types](https://developer.box.com/guides/representations/thumbnail-representation/#supported-file-types), you can use the following code: ``` const thumbnail = await client.files.getRepresentationContent('123', client.files.representations.THUMBNAIL); thumbnail.pipe(fs.createWriteStream('thumbnail.jpg')); ``` For others file types, you can get the list of representations available for a file using the [`Files.getRepresentationInfo()`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getRepresentationInfo) method, then use the [`Files.getRepresentationContent()`](http://opensource.box.com/box-node-sdk/jsdoc/Files.html#getRepresentationContent) method to get the content of the representation. ``` const representations = await client.files.getRepresentationInfo(fileId); const representation = representations.entries.find((entry) => entry.representation === 'png'); if (!representation) { console.log('No png representation'); return; } const png = await client.files.getRepresentationContent(fileId, `[${representation.representation}?dimensions=${representation.properties.dimensions}]`); png.pipe(fs.createWriteStream('file.png')); ``` --- ## Untitled *Type: page* Authentication The Box API uses OAuth2 for authentication, which can be difficult to implement. The SDK makes it easier by providing classes… # Authentication The Box API uses OAuth2 for authentication, which can be difficult to implement. The SDK makes it easier by providing classes that handle obtaining tokens and automatically refreshing them. [Ways to Authenticate](#ways-to-authenticate) - [Developer Token](#developer-token) - [Server Authentication with JWT](#server-authentication-with-jwt) - [Standard 3-Legged Oauth 2.0](#standard-3-legged-oauth-20) - [Box View Authentication with App Token](#box-view-authentication-with-app-token) - [Client Credentials Grant](#client-credentials-grant) [Manual Token Creation](#manual-token-creation) [As User](#as-user) [Token Exchange](#token-exchange) [Revoke Token](#revoke-token) ## Ways to Authenticate ### Developer Token The fastest way to get started using the API is with developer tokens. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's developer console. The following example creates an API connection with a developer token: ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); ``` ### Server Authentication with JWT App Users allows your application to provision and control Box accounts that do not have an associated login and can only be accessed through the Content API by the controlling application. An App User is a Box account that belongs to your Box Platform application and not an end-user of Box, like a [managed user](https://developer.box.com/v2.0/reference#user-object) It is important to emphasize that unlike typical Box accounts, these accounts do not have an associated login and can only be accessed through the Box API. You may authenticate as the service account to provision and manage users, or as an individual app user to make calls as that user. See the [API documentation](https://github.com/box/box-node-sdk/blob/main/docs/authentication.md#app-user-authentication) for detailed instruction on how to use app auth. The Java SDK also has a convenient helper function `BoxConfig.readFrom()` to assist in constructing an API connection. The `readFrom()` method takes in a stream constructed by the JSON config downloaded from the Developer Console seen [here](https://developer.box.com/docs/setting-up-a-jwt-app#section-use-an-application-config-file). Once a `BoxConfig` object has been created you can use that to create an API connection. ``` Reader reader = new FileReader("src/example/config/config.json"); BoxConfig boxConfig = BoxConfig.readFrom(reader); IAccessTokenCache tokenCache = new InMemoryLRUAccessTokenCache(100); BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, tokenCache); ``` It is also possible to get an API connection for an app user or managed user: ``` Reader reader = new FileReader("src/example/config/config.json"); BoxConfig boxConfig = BoxConfig.readFrom(reader); IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(100); BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getUserConnection(userId, boxConfig, accessTokenCache); ``` However, if you would like to do a manual set up then that is also possible with the below options. App User example: ``` JWTEncryptionPreferences jwtPreferences = new JWTEncryptionPreferences(); jwtPreferences.setPublicKeyID("PUBLIC-KEY-ID"); jwtPreferences.setPrivateKeyPassword("PRIVATE-KEY-PASSWORD"); jwtPreferences.setPrivateKey("PRIVATE-KEY"); jwtPreferences.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256); IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(100); BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection .getUserConnection("USER-ID", "CLIENT-ID","CLIENT-SECRET", jwtPreferences, accessTokenCache); BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); ``` Server authentication allows your application to authenticate itself with the Box API for a given enterprise. A [Service Account](https://developer.box.com/v2.0/docs/service-account) always exists for a Box application. It is important to note that a Service Account is separate from the Box accounts of the applicaton developer and the enterprise admin of any enterprise that has authorized the app, meaning files stored in that account are not accessible in any other account by default. Service Account example: ``` JWTEncryptionPreferences jwtPreferences = new JWTEncryptionPreferences(); jwtPreferences.setPublicKeyID("PUBLIC-KEY-ID"); jwtPreferences.setPrivateKeyPassword("PRIVATE-KEY-PASSWORD"); jwtPreferences.setPrivateKey("PRIVATE-KEY"); jwtPreferences.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256); BoxConfig boxConfig = new BoxConfig("YOUR-CLIENT-ID", "YOUR-CLIENT-SECRET", "ENTERPRISE-ID", jwtPreferences); IAccessTokenCache tokenCache = new InMemoryLRUAccessTokenCache(10); BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, tokenCache); ``` ### Standard 3-Legged Oauth 2.0 Using an auth code is the most common way of authenticating with the Box API. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code. After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirect_uri` which will contain an auth code. This auth code can then be used along with your client ID and client secret to establish an API connection. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-CLIENT-ID", "YOUR-CLIENT-SECRET", "YOUR-AUTH-CODE"); ``` ### Box View Authentication with App Token Allows applications that do not own content stored in Box (e.g. app-owned content) to be able to use Box as a service provider rather than a content store. This is currently mostly used for previewing items. For scopes you can choose between "item_preview", "item_upload", or "item_delete". See the [Getting Started with the New Box View](https://developer.box.com/docs/getting-started-with-new-box-view) for detailed instruction. ``` BoxTransactionalAPIConnection api = new BoxTransactionalAPIConnection("YOUR-ACCESS-TOKEN"); ``` You can also request a specific scope of the transaction token by passing in: "item_preview", "item_upload", or "item_delete". ``` BoxAPIConnection api = BoxTransactionalAPIConnection.getTransactionConnection("YOUR-ACCESS-TOKEN", "item_preview"); ``` Lastly, you can choose to specify a resource to generate a token for with. If you're passing a token down to your client this is a great way to restrict access on that token in turn locking down what the token has access to. ``` BoxAPIConnection api = BoxTransactionalAPIConnection.getTransactionConnection("YOUR-ACCESS-TOKEN", "item_preview", "https://api.box.com/2.0/files/YOUR-FILE-ID"); ``` ### Client Credentials Grant Allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account. The `BoxCCGAPIConnection` works the same way as the `BoxAPIConnection` so for example to get root folder you can do: ``` BoxCCGAPIConnection api = BoxCCGAPIConnection.userConnection( "client_id", "client_secret", "user_id" ); BoxFolder root = BoxFolder.getRootFolder(api); ``` Obtained token is valid for specified ammount of time and it will be refreshed automatically by default. #### Obtaining Service Account token The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID with client id and secret: ``` BoxCCGAPIConnection api = BoxCCGAPIConnection.applicationServiceAccountConnection( "client_id", "client_secret", "enterprise_id" ); ``` #### Obtaining User token To obtain user account you will have to provide user ID with client id and secret ``` BoxCCGAPIConnection api = BoxCCGAPIConnection.userConnection( "client_id", "client_secret", "user_id" ); ``` In order to enable generating user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/console). In`Configuration` tab, in section `Advanced Features` select `Generate user access tokens`. Do not forget to re-authorize application if it was already authorized. ## Manual Token Creation In certain advanced scenarios, you may want to obtain an access and refresh token yourself through manual calls to the API. In this case, you can create an API connection with the tokens directly. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-CLIENT-ID", "YOUR-CLIENT-SECRET", "YOUR-ACCESS-TOKEN", "YOUR-REFRESH-TOKEN"); ``` ## As User The purpose of as user is to be used by enterprise administrators to make API calls on behalf of their managed users. This can also be used by a Service Account to make API calls for managed users or app users. This is only meant to be used for `BoxAPIConnection`s and not `BoxDeveloperEditionAPIConnection`s. In order to invoke as user calls you can use ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); api.asUser("USER-ID"); ``` Once you are done making calls on behalf of a managed user or app user you can switch back to the admin or service account with ``` api.asSelf(); ``` ## Token Exchange You can exchange a API connection's access token for one with a lower scope, in order to restrict the permissions or to pass to a less secure location (e.g. a browser-based app). This is useful if you want to use the [Box UI Kits](https://developer.box.com/docs/box-ui-elements), since they generally do not need full read/write permissions to run. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); String resource = "https://api.box.com/2.0/files/RESOURCE-ID"; List<String> scopes = new ArrayList<String>(); scopes.add("item_preview"); scopes.add("item_content_upload"); ScopedToken token = api.getLowerScopedToken(scopes, resource); ``` The above example will downscope an access token to only allow for previewing an item and uploading an item. ## Revoke Token At any point if you wish to revoke your tokens you can do so by calling the following. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); api.revokeToken(); ``` --- ## Untitled *Type: page* Classifications Classfications are a type of metadata that allows users and applications to define and assign a content classification to… # Classifications Classfications are a type of metadata that allows users and applications to define and assign a content classification to files and folders. Classifications use the metadata APIs to add and remove classifications, and assign them to files. For more details on metadata templates please see the [metadata documentation](./metadata.md). [Classifications](#classifications) - [Add initial classifications](#add-initial-classifications) - [List all classifications](#list-all-classifications) - [Add another classification](#add-another-classification) - [Update a classification](#update-a-classification) - [Delete a classification](#delete-a-classification) - [Delete all classifications](#delete-all-classifications) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Get classification on file](#get-classification-on-file) - [Remove classification from file](#remove-classification-from-file) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Get classification on folder](#get-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Add initial classifications If an enterprise does not already have a classification defined, the first classification(s) can be added with the [`createMetadataTemplate`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#createMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String-boolean-java.util.List-) method. ``` MetadataTemplate.Field classification = new MetadataTemplate.Field(); classification.setType("enum"); classification.setKey(Metadata.CLASSIFICATION_KEY); classification.setDisplayName("Classification"); classification.setHidden("false"); List<String> options = new ArrayList<String>(); options.add("Top Secret"); classification.setOptions(topSecret) List<MetadataTemplate.Field> fields = new ArrayList<MetadataTemplate.Field>(); fields.add(classification); MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, "Classification", false, fields); ``` ## List all classifications To retrieve a list of all the classifications in an enterprise call the [`getMetadataTemplate`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection-) method to get the classifciations template, which will contain a list of all the classifications ``` MetadataTemplate template = MetadataTemplate.getMetadataTemplate(api, Metadata.CLASSIFICATION_TEMPLATE_KEY); ``` ## Add another classification To add another classification, call the [`updateMetadataTemplate`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#updateMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.List-) method with the an operation to add a new classification to the template. ``` List<MetadataTemplate.FieldOperation> updates = new ArrayList<MetadataTemplate.FieldOperation>(); String update = "{\n op: \"addEnumOption\",\n fieldKey: \"Box__Security__Classification__Key\",\n data: {\n key: \"Sensitive\"\n }\n}"; updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); MetadataTemplate.updateMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); ``` ## Update a classification To update an existing classification, call the [`updateMetadataTemplate`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#updateMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.List-) method with the an operation to update the existing classification already present on the template. ``` List<MetadataTemplate.FieldOperation> updates = new ArrayList<MetadataTemplate.FieldOperation>(); String update = "{\n op: \"editEnumOption\",\n fieldKey: \"Box__Security__Classification__Key\",\n enumOptionKey: \"Sensitive\",\n data: {\n key: \"Very Sensitive\"\n }\n}"; updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); MetadataTemplate.updateMetadataTemplate(api, Metadata.ENTERPRISE_METADATA_SCOPE, Metadata.CLASSIFICATION_TEMPLATE_KEY, updates); ``` ## Add classification to file To add a classification to a file, call [`setMetadata(String templateKey, String templateScope, Metadata properties)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata-) with the name of the classification template, as well as the details of the classification to add to the file. ``` BoxFile file = new BoxFile(api, "id"); Metadata metadata = new Metadata() metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") file.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); ``` ## Update classification on file To update a classification on a file, call [`setMetadata(String templateKey, String templateScope, Metadata properties)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata-) with the name of the classification template, as well as the details of the classification to add to the file. ``` BoxFile file = new BoxFile(api, "id"); Metadata metadata = new Metadata() metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") file.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); ``` ## Get classification on file Retrieve the classification on a file by calling [`getMetadata(String templateKey)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String-) with the ID of the file. ``` BoxFile file = new BoxFile(api, "id"); Metadata metadata = file.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); ``` ## Remove classification from file A classification can be removed from a file by calling [`deleteMetadata`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata--). ``` BoxFile file = new BoxFile(api, "id"); file.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); ``` ## Add classification to folder To add a classification to a folder, call [`setMetadata(String templateKey, String templateScope, Metadata properties)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata-) with the name of the classification template, as well as the details of the classification to add to the folder. ``` BoxFolder folder = new BoxFolder(api, "id"); Metadata metadata = new Metadata() metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") folder.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); ``` ## Update classification on folder To update a classification on a folder, call [`setMetadata(String templateKey, String templateScope, Metadata properties)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata-) with the name of the classification template, as well as the details of the classification to add to the folder. ``` BoxFolder folder = new BoxFolder(api, "id"); Metadata metadata = new Metadata() metadata.add(Metadata.CLASSIFICATION_KEY, "Sensitive") folder.setMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, Metadata.ENTERPRISE_METADATA_SCOPE, metadata); ``` ## Get classification on folder Retrieve the classification on a folder by calling [`getMetadata(String templateKey)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String-) with the ID of the folder. ``` BoxFolder folder = new BoxFolder(api, "id"); Metadata metadata = folder.getMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); ``` ## Remove classification from folder A classification can be removed from a folder by calling [`deleteMetadata`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata--). ``` BoxFolder folder = new BoxFolder(api, "id"); folder.deleteMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY); ``` --- ## Untitled *Type: page* Collaboration Allowlists Collaboration Allowlists are used to manage a set of approved domains or Box users that an enterprise can… # Collaboration Allowlists Collaboration Allowlists are used to manage a set of approved domains or Box users that an enterprise can collaborate with. - [Add a Collaboration Allowlist For a Domain](#add-a-collaboration-allowlist-for-a-domain) - [Get a Collaboration Allowlist's Information for a Domain](#get-a-collaboration-allowlists-information-for-a-domain) - [Get all Collaboration Allowlist's Information for Domain](#get-all-collaboration-allowlists-information-for-domain) - [Remove a Collaboration Allowlist for a Domain](#remove-a-collaboration-allowlist-for-a-domain) - [Add a Collaboration Allowlist for a User](#add-a-collaboration-allowlist-for-a-user) - [Get a Collaboration Allowlist's Information for a User](#get-a-collaboration-allowlists-information-for-a-user) - [Get all Collaboration Allowlist's Information for a User](#get-all-collaboration-allowlists-information-for-a-user) - [Remove a Collaboration Allowlist for a User](#remove-a-collaboration-allowlist-for-a-user) ## Add a Collaboration Allowlist For a Domain A collaboration allowlist can be created for a domain with [`create(BoxAPIConnection api, String domain, AllowlistDirection direction)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.BoxCollaborationAllowlist.AllowlistDirection-). The `AllowlistDirection` parameter determines which way the allowlisting applies. You can set the value to inbound, outbound, or both. ``` BoxCollaborationAllowlist.create(api, "test.com", BoxCollaborationAllowlist.AllowlistDirection.BOTH); ``` ## Get a Collaboration Allowlist's Information for a Domain A specific collaboration allowlist for a domain can be retrieved with [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getInfo--) ``` BoxCollaborationAllowlist domainAllowlist = new BoxCollaborationAllowlist(api, "id"); domainAllowlist.getInfo(); ``` ## Get all Collaboration Allowlist's Information for Domain All domain collaboration allowlists associated with an enterprise can be retrieved with [`getAll(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...-) ``` BoxCollaborationAllowlist.getAll(api); ``` To specify the number of allowlists to retrieve you can pass a limit on how many allowlists to return to [`getAll(BoxAPIConnection api, int limit)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#getAll-com.box.sdk.BoxAPIConnection-int-java.lang.String...-). ``` BoxCollaborationAllowlist.getAll(api, 10); ``` ## Remove a Collaboration Allowlist for a Domain To remove a collaboration allowlist you can call [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlist.html#delete--) ``` BoxCollaborationAllowlist domainToBeDeleted = new BoxCollaborationAllowlist(api, "allowlist-id"); domainToBeDeleted.delete(); ``` ## Add a Collaboration Allowlist for a User A collaboration allowlist can be created for a user with [`create(BoxAPIConnection api, String userID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-) ``` String userID = "12345"; BoxCollaborationAllowlistExemptTarget.create(api, userID); ``` ## Get a Collaboration Allowlist's Information for a User To retrieve information regarding a specific user collaboration allowlist use [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getInfo--) ``` BoxCollaborationAllowlistExemptTarget userAllowlist = new BoxCollaborationAllowlistExemptTarget(api, "allowlistID"); userAllowlist.getInfo(); ``` ## Get all Collaboration Allowlist's Information for a User To retrieve information regarding all user allowlists associated with an enterprise use [`getAll(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...-) ``` BoxCollaborationAllowlistExemptTarget.getAll(api); ``` Alternatively you can specify the number of user allowlists to return with one request by passing a the maximum number of records to return to [`getAll(BoxApiConnection api, int limit)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#getAll-com.box.sdk.BoxAPIConnection-int-java.lang.String...-) ``` BoxCollaborationAllowlistExemptTarget.getAll(api, 5); ``` ## Remove a Collaboration Allowlist for a User To remove a user collaboration allowlist entry from an enterprise use [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaborationAllowlistExemptTarget.html#delete--) ``` BoxCollaborationAllowlistExemptTarget userAllowlist = new BoxCollaborationAllowlistExemptTarget(api, "allowlist_id"); userAllowlist.delete(); ``` --- ## Untitled *Type: page* Android The Java SDK should be compatible with modern Android applications written in both Java and Kotlin. To use the Java SDK in an… # Android The Java SDK should be compatible with modern Android applications written in both Java and Kotlin. To use the Java SDK in an android application add it to the project's gradle file in the `dependencies` block. For Groovy ``` // build.gradle dependencies { implementation "com.box:box-java-sdk:3.8.0" } ``` For Kotlin ``` // build.gradle.kts dependencies { implementation("com.box:box-java-sdk:3.8.0") } ``` ## Kotlin The Java SDK can also be used in Kotlin Android applications through interoperability thanks to the Kotlin design. You can read more about Kotlin and Java interoperability [here](https://kotlinlang.org/docs/java-interop.html) The following example creates an API connection with a developer token: ``` val api = BoxAPIConnection("myToken") ``` The following example shows how to get current user ``` val userID = "33333" val api = BoxAPIConnection("myToken") val user = BoxUser(api, userID) val userInfo = user.getInfo() ``` If you are using an IntelliJ-based IDE, you can copy our samples located in the [docs](https://developer.box.com/doc/) directory and paste them into your file. The IDE should ask you to convert the pasted Java sample to Kotlin. Most samples still work after conversion using this approach. Note that the current Java SDK does not support Kotlin coroutines. By default, you cannot run network calls on the main thread in an Android application. There are various ways to overcome this. For example, if you are in a viewModel context, you can run the SDK method as a coroutine using viewModelScope. ``` viewModelScope.launch { val result = withContext(Dispatchers.IO) { /* SDK code goes here */ } // here you can access the result and load it to the viewModel } ``` The following example shows how to get the current items in the root folder, sorted by name in ascending order with additional "created_by" and "name" fields returned from the API. The items are then loaded to the custom data class defined earlier. ``` // data class definition used in viewModel data class Item( val isFolder: Boolean, val name: String, val createdBy: String ) // viewModel init code viewModelScope.launch { val result = withContext(Dispatchers.IO) { val res = BoxFolder(BoxAPIConnection("myToken"), "0") val iterator: Iterator<BoxItem.Info> = res.getChildren("name", BoxFolder.SortDirection.ASC, "created_by", "name") .iterator() val items = mutableListOf<Item>() when (val itemInfo = iterator.next()) { is BoxFile.Info -> items.add(Item(false, "File " + itemInfo.name, itemInfo.createdBy.name)) is BoxFolder.Info -> items.add(Item(true, "Folder " + itemInfo.name, itemInfo.createdBy.name)) } items } } ``` If you are familiar with Kotlin syntax, you might have noticed that we could have used the `.map` function (or a similar function) to map the API result to a list of items. Due to current limitations, using `.map` and similar operations on collections is not always possible and may lead to unexpected results. The preferred way is to use an explicit iterator to iterate over the collections returned by the SDK. If you find any problem related to the Java SDK in Kotlin-based app feel free to open an issue. --- ## Untitled *Type: page* Collaborations Collaborations are used to share folders between users or groups. They also define what permissions a user has for a folder… # Collaborations Collaborations are used to share folders between users or groups. They also define what permissions a user has for a folder. - [Add a Collaboration](#add-a-collaboration) - [Edit a Collaboration](#edit-a-collaboration) - [Remove a Collaboration](#remove-a-collaboration) - [Get a Collaboration's Information](#get-a-collaborations-information) - [Get the Collaborations on a Folder](#get-the-collaborations-on-a-folder) - [Get the Collaborations on a File](#get-the-collaborations-on-a-file) - [Get Pending Collaborations](#get-pending-collaborations) - [Accept or Decline a Pending Collaboration](#accept-or-decline-a-pending-collaboration) ## Add a Collaboration A collaboration can be added for an existing user or group with [`collaborate(BoxCollaborator collaborator, BoxCollaboration.Role role)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role-). The `role` parameter determines what permissions the collaborator will have on the folder. ``` BoxCollaborator user = new BoxUser(api, "user-id") BoxFolder folder = new BoxFolder(api, "folder-id"); folder.collaborate(user, BoxCollaboration.Role.EDITOR); ``` You can also add a collaboration by providing an email address with [`collaborate(String emailAddress, BoxCollaboration.Role role)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-java.lang.String-com.box.sdk.BoxCollaboration.Role-). If the recipient doesn't have a Box account, they will be asked create one. ``` BoxFolder folder = new BoxFile(api, "id"); folder.collaborate("gcurtis@box.com", BoxCollaboration.Role.EDITOR); ``` If you need to create a collaboration with a group, provide a group id. ``` BoxCollaborator group = new BoxGroup(api, "group-id"); BoxFolder folder = new BoxFolder(api, "folder-id"); folder.collaborate(group, BoxCollaboration.Role.EDITOR); ``` ## Edit a Collaboration A collaboration can be edited by creating a new [`BoxCollaboration.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.Info.html) object or updating an existing one, and then passing it to [`updateInfo(BoxCollaboration.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#updateInfo-com.box.sdk.BoxCollaboration.Info-) ``` BoxCollaboration collaboration = new BoxCollaboration(api, "id"); BoxCollaboration.Info info = collaboration.new Info(); info.setStatus(BoxCollaboration.Status.ACCEPTED); collaboration.updateInfo(info); ``` ## Remove a Collaboration A collaboration can be removed by calling [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#delete--). ``` BoxCollaboration collaboration = new BoxCollaboration(api, "id"); collaboration.delete(); ``` ## Get a Collaboration's Information Calling [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#getInfo-java.lang.String...-) on a collaboration returns a snapshot of the collaboration's info. ``` BoxCollaboration collaboration = new BoxCollaboration(api, "id"); BoxCollaboration.Info info = collaboration.getInfo(); ``` You can also choose to retrieve only specific fields of the collaboration by calling [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#getInfo-java.lang.String...-) with a list of field names. ``` BoxCollaboration collaboration = new BoxCollaboration(api, "id"); BoxCollaboration.Info info = collaboration.getInfo(BoxCollaboration.ALL_FIELDS); ``` ## Get the Collaborations on a Folder You can get all of the collaborations on a folder by calling [`getCollaborations()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getCollaborations--) on the folder. ``` BoxFolder folder = new BoxFolder(api, "id"); Collection<BoxCollaboration.Info> collaborations = folder.getCollaborations(); ``` ## Get the Collaborations on a File You can get an iterator over all of the collaborations on a file by calling [`BoxFile#getAllFileCollaborations(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getAllFileCollaborations-java.lang.String...-) on the file. ``` BoxFile file = new BoxFile(api, "id"); Iterable<BoxCollaboration.Info> collaborations = file.getAllFileCollaborations(); ``` ## Get Pending Collaborations A collection of all the user's pending collaborations can be retrieved with [`getPendingCollaborations(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollaboration.html#getPendingCollaborations-com.box.sdk.BoxAPIConnection-). ``` Collection<BoxCollaboration.Info> pendingCollaborations = BoxCollaboration.getPendingCollaborations(api); ``` ## Accept or Decline a Pending Collaboration To accept or decline a pending collaboration, update the info of the pending collaboration object with the desired status. ``` // Accept all pending collaborations Collection<BoxCollaboration.Info> pendingCollaborations = BoxCollaboration.getPendingCollaborations(api); for (BoxCollaboration.Info collabInfo : pendingCollaborations) { collabInfo.setStatus(BoxCollaboration.Status.ACCEPTED); collabInfo.getResource().updateInfo(collabInfo); } ``` --- ## Untitled *Type: page* Comments Comment objects represent a user-created comment on a file. They can be added directly to a file or they can be a reply to another… # Comments Comment objects represent a user-created comment on a file. They can be added directly to a file or they can be a reply to another comment. - [Get a Comment's Information](#get-a-comments-information) - [Get the Comments on a File](#get-the-comments-on-a-file) - [Add a Comment to a File](#add-a-comment-to-a-file) - [Reply to a Comment](#reply-to-a-comment) - [Change a Comment's Message](#change-a-comments-message) - [Delete a Comment](#delete-a-comment) ## Get a Comment's Information Calling [`getInfo()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxComment.html#getInfo--) on a comment returns a snapshot of the comment's info. ``` BoxComment comment = new BoxComment(api, "id"); BoxComment.Info info = comment.getInfo(); ``` ## Get the Comments on a File You can get all of the comments on a file by calling the [`getComments()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getComments--) method. ``` BoxFile file = new BoxFile(api, "id"); List<BoxComment.Info> comments = file.getComments(); ``` ## Add a Comment to a File A comment can be added to a file with the [`addComment(String message)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#addComment-java.lang.String-) method. ``` BoxFile file = new BoxFile(api, "id"); file.addComment("This file is pretty cool."); ``` The comment's message can also contain @mentions by using the string @[userid:username] anywhere within the message, where userid and username are the ID and username of the person being mentioned. [See the documentation] ([https://developers.box.com/docs/#comments-comment-object](https://developers.box.com/docs/#comments-comment-object)) on the `tagged_message` field for more information on @mentions. ``` BoxFile file = new BoxFile(api, "id"); file.addComment("Message mentioning @[1234:user@box.com]."); ``` ## Reply to a Comment You can reply to a comment with the [`reply(String message)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxComment.html#reply-java.lang.String-) method. ``` BoxComment comment = new BoxComment(api, "id"); comment.reply("I agree with this!"); ``` The comment's message can also contain @mentions by using the string @[userid:username] anywhere within the message, where userid and username are the ID and username of the person being mentioned. [See the documentation] ([https://developers.box.com/docs/#comments-comment-object](https://developers.box.com/docs/#comments-comment-object)) on the `tagged_message` field for more information on @mentions. ``` BoxComment comment = new BoxComment(api, "id"); comment.reply("@[1234:user@box.com] I agree with this!"); ``` ## Change a Comment's Message The message of a comment can be changed with the [`changeMessage(String message)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxComment.html#changeMessage-java.lang.String-) method. ``` BoxComment comment = new BoxComment(api, "id"); comment.changeMessage("An edited message."); ``` ## Delete a Comment A comment can be deleted with the [`delete()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxComment.html#delete--) method. ``` BoxComment comment = new BoxComment(api, "id"); comment.delete(); ``` --- ## Untitled *Type: page* Devices Device pinning is a feature that allows enterprise admins to pin their user’s corporate-managed Box account to a particular mobile… # Devices Device pinning is a feature that allows enterprise admins to pin their user’s corporate-managed Box account to a particular mobile device or Box Sync client. - [Get Enterprise Device Pins](#get-enterprise-device-pins) - [Get Device Pin](#get-device-pin) - [Delete Device Pin](#delete-device-pin) ## Get Enterprise Device Pins Calling the static [`getEnterpriceDevicePins(BoxAPIConnection api, String enterpriseID, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getEnterpriceDevicePins-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...-) will return an iterable that will page through all of the device pins belongs to enterprise with given ID. It is possible to specify maximum number of retrieved items per single response by passing the maxiumum number of records to retrieve to [`getEnterpriceDevicePins(BoxAPIConnection api, String enterpriseID, int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getEnterpriceDevicePins-com.box.sdk.BoxAPIConnection-java.lang.String-int-java.lang.String...-) ``` Iterable<BoxDevicePin.Info> enterpriseDevicePins = BoxDevicePin.getEnterpriceDevicePins(api, id); for (BoxDevicePin.Info devicePin : enterpriseDevicePins) { // Do something with the device pin. } ``` ## Get Device Pin Existing collections can be retrieved by calling the [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#getInfo-java.lang.String...-) method. Optional parameters can be used to retrieve specific fields of the Device Pin object. ``` BoxDevicePin devicePin = new BoxDevicePin(api, id); BoxDevicePin.Info devicePinInfo = devicePin.getInfo(); ``` ## Delete Device Pin A device pin can be deleted by calling the [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxDevicePin.html#delete--) method. ``` BoxDevicePin devicePin = new BoxDevicePin(api, id); devicePin.delete(); ``` --- ## Untitled *Type: page* Configuration Proxy configuration Custom proxy authenticator Example: NTLM authenticator Configure retries of calls and timeouts Maximum… # Configuration [Proxy configuration](#proxy-configuration) [Custom proxy authenticator](#custom-proxy-authenticator) - [Example: NTLM authenticator](#example-ntlm-authenticator) [Configure retries of calls and timeouts](#configure-retries-of-calls-and-timeouts) - [Maximum retries](#maximum-retries) - [Connection timeout](#connection-timeout) - [Read timeout](#read-timeout) [URLs configuration](#urls-configuration) - [Base URL](#base-url) - [Base Upload URL](#base-upload-url) - [Base App URL](#base-app-url) - [Token URL](#token-url-deprecated) - [Revoke URL](#revoke-url-deprecated) [SSL configuration](#ssl-configuration) [Instrumenation of OpenTelemetry](#instrumenation-of-opentelemetry) # Proxy configuration To set up proxy use [BoxApiConnection.setProxy](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxy-java.net.Proxy-) to set proxy address and [BoxApiConnection.setProxyBasicAuthentication](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxyBasicAuthentication-java.lang.String-java.lang.String-) to set username and password required by proxy: ``` BoxAPIConnection api=new BoxAPIConnection("access_token"); Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); // You can use any subclass of BoxAPIConnection api.setProxy(proxy); api.setProxyBasicAuthentication("proxyUsername", "proxyPassword"); ``` Proxy username and password will be used only if provided `SocketAddress` is an instance of `InetSocketAddress`. If you would like to use a custom `SocketAddress` you can provide your own `okhttp3.Authenticator` using [BoxApiConnection.setProxyAuthenticator(Authenticator)](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxyAuthenticator-okhttp3.Authenticator-) ## Custom proxy authenticator By using [BoxApiConnection.setProxyBasicAuthentication](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxyBasicAuthentication-java.lang.String-java.lang.String-) you can enable default proxy authenticator that handles only Basic authentication. But you can provide your own authenticator by using [BoxApiConnection.setProxyAuthenticator(Authenticator)](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setProxyAuthenticator-okhttp3.Authenticator-). To do that you will need to add a dependency to your project: ``` "com.squareup.okhttp3:okhttp:XXX" ``` Please match the version with what SDK is using by checking `build.gradle` and looking for entry `implementation "com.squareup.okhttp3:okhttp:"`. Now you can add an authenticator. by calling ``` BoxAPIConnection api = new BoxAPIConnection("access_token"); Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); api.setProxy(proxy); api.setProxyAuthenticator((route, response) -> response .request() .newBuilder() .addHeader("Proxy-Authorization", "My custom authenticator") .build() ); ``` ### Example: NTLM authenticator For example, you can add NTLM authorization. This is example NTLM authenticator that is using parts from Apache Http Client 5. ``` import okhttp3.Authenticator; import okhttp3.Request; import okhttp3.Response; import okhttp3.Route; import org.apache.hc.client5.http.impl.auth.NTLMEngineException; public class NTLMAuthenticator implements Authenticator { final NTLMEngineImpl engine = new NTLMEngineImpl(); private final String domain; private final String username; private final String password; private final String ntlmMsg1; public NTLMAuthenticator(String username, String password, String domain) { this.domain = domain; this.username = username; this.password = password; String localNtlmMsg1 = null; try { localNtlmMsg1 = engine.generateType1Msg(null, null); } catch (Exception e) { e.printStackTrace(); } ntlmMsg1 = localNtlmMsg1; } @Override public Request authenticate(Route route, Response response) { if(response.code() == 407 && "Proxy authorization required".equals(response.message())) { String ntlmChallenge = response.headers("Proxy-Authenticate") .stream() .filter(h -> h.startsWith("NTLM ")) .findFirst().orElse(""); if(ntlmChallenge.length() > 5) { try { String ntlmMsg3 = engine.generateType3Msg(username, password.toCharArray(), domain, "ok-http-example-ntlm", ntlmChallenge.substring(5)); return response.request().newBuilder().header("proxy-Authorization", "NTLM " + ntlmMsg3).build(); } catch (NTLMEngineException e) { throw new RuntimeException(e); } } return response.request().newBuilder().header("proxy-Authorization", "NTLM " + ntlmMsg1).build(); } return response.request(); } } ``` The `NTLMEngineImpl` could be created by using Apache implementation that can be found [here](https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/NTLMEngineImpl.java). You can add a dependency to `org.apache.httpcomponents.client5:httpclient5:5.1.3`. Copy the `NTLMEngineImpl` class and add it to your source. Now you can use custom NTML Authenticator in your `BoxAPIConnection`: ``` BoxAPIConnection api = new BoxAPIConnection("access_token"); Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy_url",8888)); api.setProxy(proxy); api.setProxyAuthenticator(new NTLMAuthenticator("some proxy username", "some proxy password", "proxy workgroup")); ``` # Configure retries of calls and timeouts SDK can retry failed calls when: - failed writting request body when recieved HTTP response code: - 429 - rate limit exceeded - 5XX - internal server error - 400 error with error that `exp` claim has expired. This usially means there is a clock skew. SDK is using exponnetial strategy to calculate time between retries. If response contains `Retry-After` header its value will be used as a wait time between calls. You can check details in `com.box.sdk.BoxAPIRequest.send(com.box.sdk.ProgressListener)` method. ## Maximum retries To configure how many times API will retry calls use [BoxApiConnection.setMaxRetryAttempts](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setMaxRetryAttempts-int-): ``` // You can use any subclass of BoxAPIConnection api.setMaxRetryAttempts(10); ``` default value for retry attempts is `5`. ## Connection timeout To set up how log (in milliseconds) API waits to establish connection use [BoxApiConnection.setConnectTimeout](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setConnectTimeout-int-): ``` // You can use any subclass of BoxAPIConnection int connectionTimeout = 100; // timeout in milliseconds api.setConnectTimeout(connectionTimeout); ``` default value is `0` which mean API waits forever to establish connection. ## Read timeout To set up how log (in milliseconds) API waits to read data from connection use [BoxApiConnection.setReadTimeout](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setReadTimeout-int-): ``` // You can use any subclass of BoxAPIConnection int readTimeout = 100; // timeout in milliseconds api.setReadTimeout(readTimeout); ``` default value is `0` which mean API waits forever to read data from connection. # URLs configuration ### Base URL The default base URL used for making API calls to Box can be changed by calling `BoxAPIConnection#setBaseURL(String)` method on `BoxApiConnection`. Default value is `https://api.box.com/`. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); api.setBaseURL("https://example.com"); String baseUrl = api.getBaseURL(); // will produce "https://example.com/2.0/" ``` Setting Base URL changes the Token and Revoke URL as well: ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); api.setBaseURL("https://example.com"); String baseUrl = api.getBaseURL(); // will produce "https://example.com/2.0/" String tokenUrl = api.getRevokeURL(); // will produce "https://example.com/oauth2/revoke" String revokeUrl = api.getTokenURL(); // will produce "https://example.com/oauth2/token" ``` ### Base Upload URL The default URL used for uploads can be changed by calling `BoxAPIConnection#setBaseUploadURL(String)` method on `BoxApiConnection`. Default value is `https://upload.box.com/api/`. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); api.setBaseUploadURL("https://upload.example.com"); api.getBaseUploadURL(); // will produce "https://upload.example.com/2.0/" ``` ### Base App URL The default base app URL can be changed by calling `BoxAPIConnection#setBaseAppUrl()` method on `BoxApiConnection`. Default value is [https://app.box.com](https://app.box.com). ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); api.setBaseAppUrl("https://example.app.com"); api.getBaseAppUrl(); // will produce "https://app.example.com" ``` ### Token URL (deprecated) The default URL used for getting token can be changed by calling `setTokenURL()` method on `BoxApiConnection`. Default value is [https://api.box.com/oauth2/token](https://api.box.com/oauth2/token). This method is deprecated. Use `BoxAPIConnection#setBaseURL(String)` instead. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); api.setTokenURL("https://example.com/token"); ``` If you use `setTokenUrl` this URL will be used over the one coming from `setBaseUrl` when doing authentication. ### Revoke URL (deprecated) The default URL used for invalidating token can be changed by calling `setRevokeURL()` method on `BoxApiConnection`. Default value is [https://api.box.com/oauth2/revoke](https://api.box.com/oauth2/revoke). This method is deprecated. Use `BoxAPIConnection#setBaseURL(String)` instead. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); api.setRevokeURL("https://example.com/revoke"); ``` If you use `setRevokeUrl` this URL will be used over the one coming from`setBaseUrl` when doing authentication. # SSL configuration You can override default settings used to verify SSL certificates. This can be used to allow using self-signed certificates. For example: ``` BoxAPIConnection api = new BoxAPIConnection(...); // to allow self-signed certificates X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } }; // to allow self-signed certificates created for localhost HostnameVerifier hostnameVerifier = (hostname, session) -> true; api.configureSslCertificatesValidation(trustManager, hostnameVerifier); ``` If you just need to provide trust manager use `BoxAPIConnection.DEFAULT_HOSTNAME_VERIFIER` as a hostname verifier. The same goes for hostname verifier. If you need just to provide it use `BoxAPIConnection.DEFAULT_TRUST_MANAGER` as a trust manager. Example: ``` BoxAPIConnection api = new BoxAPIConnection(...); X509TrustManager trustManager = ... api.configureSslCertificatesValidation(trustManager, BoxAPIConnection.DEFAULT_HOSTNAME_VERIFIER); ``` # Instrumenation of OpenTelemetry OpenTelemetry is an observability framework and toolkit for creating and managing telemetry data, such as traces, metrics, and logs. The Box Java SDK can be instrumented with OpenTelemetry to collect telemetry data about the requests made by the SDK. To start, add the [opentelemetry-okhttp-3.0](https://mvnrepository.com/artifact/io.opentelemetry.instrumentation/opentelemetry-okhttp-3.0) dependency to your project. Next, create a custom class that extends BoxAPIConnection and integrates telemetry in the overridden `createNewCall` method. Here's an example implementation: ``` public class BoxAPIConnectionWithTelemetry extends BoxAPIConnection { private OkHttpTelemetry telemetry; public BoxAPIConnectionWithTelemetry(String accessToken) { super(accessToken); } /** * Add required constructors */ public void setTelemetry(OpenTelemetry openTelemetry) { this.telemetry = OkHttpTelemetry.builder(openTelemetry).build(); } protected Call createNewCall(OkHttpClient httpClient, Request request) { return this.telemetry.newCallFactory(httpClient).newCall(request); } } ``` Please note that you should not modify either `httpClient` or `request` parameters in the createNewCall method. Altering these parameters can discard the BoxAPIConnection configuration and lead to unexpected behavior. --- ## Untitled *Type: page* File Requests File request objects represent a file request associated with a folder. Get a File Request's Information Copy a File Request's… # File Requests File request objects represent a file request associated with a folder. - [Get a File Request's Information](#get-a-file-requests-information) - [Copy a File Request's Information](#copy-a-file-requests-information) - [Update a File Request's Information](#update-a-file-requests-information) - [Delete a File Request](#delete-a-file-request) ## Get a File Request's Information Calling [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#getInfo) returns information on a file request. ``` BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); BoxFileRequest.Info fileRequestInfo = fileRequest.getInfo(); ``` ## Copy a File Request's Information Calling [`copyInfo(String folderId)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#copyInfo) copies an existing file request that is already present on one folder, and applies it to another folder. If you want to set certain fields of the newly copied file request when it is created, set those fields in the `BoxFileRequest.Info` that you pass into this method [`copyInfo(BoxFileRequest.Info info, String folderId)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#copyInfo). ``` BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); BoxFileRequest.Info fileRequestInfo = fileRequest.new Info(); fileRequestInfo.setDescription("Following documents are requested for your process"); fileRequestInfo.setIsDescriptionRequired(true); fileRequestInfo.setStatus(BoxFileRequest.Status.ACTIVE); fileRequestInfo = fileRequest.copyInfo(fileRequestInfo, "folderId"); ``` ## Update a File Request's Information Calling [`updateInfo(BoxFileRequest.Info info)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#updateInfo) updates a file request. This can be used to activate or deactivate a file request. ``` BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); BoxFileRequest.Info fileRequestInfo = fileRequest.new Info(); fileRequestInfo.setDescription("Following documents are requested for your process"); fileRequestInfo.setIsDescriptionRequired(true); fileRequestInfo.setStatus(BoxFileRequest.Status.ACTIVE); fileRequestInfo = fileRequest.updateInfo(fileRequestInfo); ``` ## Delete a File Request Calling [`delete()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFileRequest.html#delete) deletes a file request permanently. ``` BoxFileRequest fileRequest = new BoxFileRequest(api, "id"); fileRequest.delete(); ``` --- ## Untitled *Type: page* Events The Box API provides an events endpoint that utilizes long-polling to send user events in real-time. The SDK provides an EventStream… # Events The Box API provides an events endpoint that utilizes long-polling to send user events in real-time. The SDK provides an `EventStream` class that automatically handles long-polling and deduplicating events. [User Events](#user-events) - [Deduplicating Events](#deduplicating-events) [Enterprise (Admin) Events](#enterprise-admin-events) - [Historical Querying](#historical-querying) - [Live Monitoring](#live-monitoring) ## User Events Subscribing to user events works by creating an `EventStream` and attaching listeners for the events that are fetched in near-real time from the API. When the `EventStream` is started, it will begin long-polling on a separate thread. Events received from the API are then forwarded to any listeners as a [`BoxEvent`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxEvent.html) object. To create an `EventStream` starting from the current point in time, use the [`EventStream(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/EventStream.html#EventStream-com.box.sdk.BoxAPIConnection-) constructor. To start from a known stream position, pass the stream position to the [`EventStream(BoxAPIConnection api, long streamPosition)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/EventStream.html#EventStream-com.box.sdk.BoxAPIConnection-long-) constructor. ``` EventStream stream = new EventStream(api); stream.addListener(new EventListener() { public void onEvent(BoxEvent event) { // Handle the event. } }); stream.start(); ``` Keep in mind that events are received on a separate thread, so things like UI operations may need to be explicitly delegated back to the UI thread. When you're done listening for events, be sure to call `stream.stop()` to stop long-polling. ### Deduplicating Events Since the Box API [may send duplicate events](https://developers.box.com/docs/#events), the `EventStream` will remember the last 512 received events and automatically ignore them. ## Enterprise (Admin) Events ### Historical Querying The Box API provides an `EventLog` class and a `getEnterpriseEvents(BoxAPIConnection api, EnterpriseEventsRequest enterpriseEventsRequest)` method that reads from the `admin-logs` stream and returns an `Iterable<BoxEvent>` over Enterprise [`BoxEvent`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxEvent.html) records. The emphasis for this stream is on completeness over latency, which means that Box will deliver admin events in chronological order and without duplicates, but with higher latency. You can specify start and end time/dates. This method will only work with an API connection for an enterprise admin account or service account with a manage enterprise properties. ``` // get the last two hours of unfiltered enterprise events Date startDate = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 2)); Date endDate = new Date(System.currentTimeMillis()); EnterpriseEventsRequest request = new EnterpriseEventsRequest() .after(startDate) .before(endDate); EventLog eventLog = EventLog.getEnterpriseEvents(api, request); for (BoxEvent event : eventLog) { System.out.println("Enterprise Event Created by User: " + event.getCreatedBy().getName() + " Login: " + event.getCreatedBy().getLogin() + " Event Type: " + event.getEventType() + " Created at: " + event.getCreatedAt().toString() ); }; ``` Additionally, you can set a limit of the number of enterprise events to be retrieved per response by specifying the limit field. ``` // get first 20 events EnterpriseEventsRequest request = new EnterpriseEventsRequest() .limit(20); EventLog eventLog = EventLog.getEnterpriseEvents(api, request); for (BoxEvent event : eventLog) { System.out.println("Enterprise Event Created by User: " + event.getCreatedBy().getName() + " Login: " + event.getCreatedBy().getLogin() + " Event Type: " + event.getEventType() + " Created at: " + event.getCreatedAt().toString() ); }; ``` You can also filter events by type. ``` // filter events by type EnterpriseEventsRequest request = new EnterpriseEventsRequest() .types(EventType.ITEM_CREATE, EventType.ITEM_OPEN); EventLog eventLog = EventLog.getEnterpriseEvents(api, request); for (BoxEvent event : eventLog){ System.out.println("Enterprise Event Created by User: " + event.getCreatedBy().getName() + " Login: " + event.getCreatedBy().getLogin() + " Event Type: " + event.getEventType() + " Created at: " + event.getCreatedAt().toString() ); }; ``` You can also filter events by type name. This is usefull if a new event type is introduced and is not mapped to `BoxEvent.EventType`. ``` // filter events by type name EnterpriseEventsRequest request = new EnterpriseEventsRequest() .typeNames("ITEM_CREATE", "ITEM_OPEN"); EventLog eventLog = EventLog.getEnterpriseEvents(api, request); for (BoxEvent event : eventLog){ System.out.println("Enterprise Event Created by User: " + event.getCreatedBy().getName() + " Login: " + event.getCreatedBy().getLogin() + " Event Type: " + event.getEventType() + " Event Type Name: " + event.getTypeName() + " Created at: " + event.getCreatedAt().toString() ); }; ``` Bear in mind that if an event type is not mapped to `BoxEvent.EventType` the value of `BoxEvent#getEventType()` will be `BoxEvent.EventType.UNKNOWN` but `BoxEvent#getTypeName()` will return its name. If you want to progress within a stream you can use position parameter: ``` EnterpriseEventsRequest request1 = new EnterpriseEventsRequest().limit(20); EventLog eventLog1 = EventLog.getEnterpriseEvents(api, request1); // process revieved events EnterpriseEventsRequest request2 = new EnterpriseEventsRequest().limit(20) .position(eventLog1.getNextStreamPosition()); // get events from the next position EventLog eventLog2 = EventLog.getEnterpriseEvents(api, request2); // process revieved events ``` ### Live Monitoring To monitor recent events that have been generated within Box across the enterprise use `EventLog#getEnterpriseEventsStream(BoxAPIConnection api, EnterpriseEventsStreamRequest enterpriseEventsStreamRequest)`, method that reads from the `admin-logs-streaming` stream and returns an `Iterable<BoxEvent>` over Enterprise [`BoxEvent`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxEvent.html) records. The emphasis for this feed is on low latency rather than chronological accuracy, which means that Box may return events more than once and out of chronological order. Events are returned via the API around 12 seconds after they are processed by Box (the 12 seconds buffer ensures that new events are not written after your cursor position). Only two weeks of events are available via this feed, and you cannot set start and end time/dates. This method will only work with an API connection for an enterprise admin account or service account with a manage enterprise properties. ``` EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); for (BoxEvent event : eventLog) { System.out.println("Enterprise Event Created by User: " + event.getCreatedBy().getName() + " Login: " + event.getCreatedBy().getLogin() + " Event Type: " + event.getEventType() + " Created at: " + event.getCreatedAt().toString() ); }; ``` You can limit number of events returned. ``` // get first 20 events EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() .limit(20) EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); ``` You can also filter events by type. ``` // filter events by type EnterpriseEventsStreamRequest request = new EnterpriseEventsStreamRequest() .types(EventType.ITEM_CREATE, EventType.ITEM_OPEN); EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); for (BoxEvent event : eventLog){ System.out.println("Enterprise Event Created by User: " + event.getCreatedBy().getName() + " Login: " + event.getCreatedBy().getLogin() + " Event Type: " + event.getEventType() + " Created at: " + event.getCreatedAt().toString() ); }; ``` You can also filter events by type name. This is usefull if a new event type is introduced and is not mapped to `BoxEvent.EventType`. ``` // filter events by type name EnterpriseEventsRequest request = new EnterpriseEventsStreamRequest() .typeNames("ITEM_CREATE", "ITEM_OPEN"); EventLog eventLog = EventLog.getEnterpriseEventsStream(api, request); for (BoxEvent event : eventLog){ System.out.println("Enterprise Event Created by User: " + event.getCreatedBy().getName() + " Login: " + event.getCreatedBy().getLogin() + " Event Type: " + event.getEventType() + " Event Type Name: " + event.getTypeName() + " Created at: " + event.getCreatedAt().toString() ); }; ``` Bear in mind that if an event type is not mapped to `BoxEvent.EventType` the value of `BoxEvent#getEventType()` will be `BoxEvent.EventType.UNKNOWN` but `BoxEvent#getTypeName()` will return its name. If you want to progress within a stream you can use position parameter: ``` EnterpriseEventsStreamRequest request1 = new EnterpriseEventsStreamRequest().limit(20); EventLog eventLog1 = EventLog.getEnterpriseEventsStream(api, request1); // process revieved events EnterpriseEventsStreamRequest request2 = new EnterpriseEventsStreamRequest().limit(20) .position(eventLog1.getNextStreamPosition()); // get events from the next position EventLog eventLog2 = EventLog.getEnterpriseEventsStream(api, request2); // process revieved events ``` If you have the next stream position, and make a subsequent call, the API will return immediately even when there are no events, the next stream position will be returned. If you have a stream position that is older than two weeks than API will return no events and next stream position. --- ## Untitled *Type: page* Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a… # Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a folder with another user or group, and perform other common folder operations (move, copy, delete, etc.). - [Get the User's Root Folder](#get-the-users-root-folder) [Get a Folder's Items](#get-a-folders-items) - [SortParameters and Using PagingParameters](#sortparameters-and-using-pagingparameters) [Get a Folder's Information](#get-a-folders-information) [Update a Folder's Information](#update-a-folders-information) [Create a Folder](#create-a-folder) [Copy a Folder](#copy-a-folder) [Move a Folder](#move-a-folder) [Rename a Folder](#rename-a-folder) [Delete a Folder](#delete-a-folder) [Find Folder for Shared Link](#find-folder-for-shared-link) [Create a Shared Link](#create-a-shared-link) [Get a Shared Link](#get-a-shared-link) [Update a Shared Link](#update-a-shared-link) [Remove a Shared Link](#remove-a-shared-link) [Share a Folder](#share-a-folder) [Get All Collaborations for a Folder](#get-all-collaborations-for-a-folder) [Create Metadata](#create-metadata) [Set Metadata](#set-metadata) [Get Metadata](#get-metadata) [Update Metadata](#update-metadata) [Delete Metadata](#delete-metadata) [Get All Metadata on Folder](#get-all-metadata-on-folder) [Get Metadata for Multiple Files](#get-metadata-for-multiple-files) [Set Classification on Folder](#set-classification-on-folder) [Get Classification on Folder](#get-classification-on-folder) [Remove Classification on Folder](#remove-classification-on-folder) [Create Cascade Policy On Folder](#create-cascade-policy-on-folder) [Get a Cascade Policy's Information](#get-a-cascade-policys-information) [Get All Cascade Policies on Folder](#get-all-cascade-policies-on-folder) [Force Apply Cascade Policy on Folder](#force-apply-cascade-policy-on-folder) [Delete Cascade Policy](#delete-cascade-policy) [Lock a Folder](#lock-a-folder) [Get All Locks on a Folder](#get-all-locks-on-a-folder) [Delete a Lock on a Folder](#delete-a-lock-on-a-folder) ## Get the User's Root Folder The user's root folder can be accessed with the static [`getRootFolder(BoxAPIConnection api)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getRootFolder-com.box.sdk.BoxAPIConnection-) method. ``` BoxFolder rootFolder = BoxFolder.getRootFolder(api); ``` ## Get a Folder's Items Every `BoxFolder` implements [`Iterable<BoxItem>`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#iterator--) which allows you to iterate over the folder's contents. The iterator automatically handles paging and will make additional API calls to load more data when necessary. ``` BoxFolder folder = new BoxFolder(api, "id"); for (BoxItem.Info itemInfo : folder) { if (itemInfo instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; // Do something with the file. } else if (itemInfo instanceof BoxFolder.Info) { BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; // Do something with the folder. } } ``` `BoxFolder` purposely doesn't provide a way of getting a collection of `BoxItems`. Getting the entire contents of a folder is usually unnecessary and can be extremely inefficient for folders with a large number of items. If you really require a collection instead of an iterable, you can create the collection manually. ``` Collection<BoxItem> folderItems = new ArrayList<BoxItem>(); BoxFolder folder = new BoxFolder(api, "id"); for (BoxItem.Info itemInfo : folder) { folderItems.add(itemInfo.getResource()); } ``` We also allow users to sort the results of the folder items by `name`, `id`, or `date`. This will maintain the integrity of the ordering when you retrieve the items for a folder. You can do this by calling the [`getChildren(String sortField, BoxFolder.SortDirection sortDirection, String... fields)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getChildren-java.lang.String-com.box.sdk.BoxFolder.SortDirection-java.lang.String...-) method. ``` BoxFolder folder = new BoxFolder(this.api, "12345"); Iterator<BoxItem.Info> itemIterator = folder.getChildren("name", BoxFolder.SortDirection.ASC).iterator(); while (itemIterator.hasNext()) { BoxItem.Info itemInfo = itemIterator.next(); // Do something } ``` ### SortParameters and Using PagingParameters `SortParameters` is an abstraction hiding way that SDK is doing sorting. `PagingParameters` is an abstraction hiding way that SDK is doing pagination. If you want to start offset based pagination: ``` BoxFolder folder = new BoxFolder(this.api, "12345"); // setup ascending sorting by name SortParameters sorting = SortParameters.ascending("name"); // setup paging with offset 0 and limit 100 long offset = 0; long limit = 100; PagingParameters paging = PagingParameters.offset(offset, limit) Iterable<BoxItem.Info> itemIterator = childFolder.getChildren(sorting, paging); while (itemIterator.hasNext()) { BoxItem.Info itemInfo=itemIterator.next(); // Do something } ``` With offset pagination you cannot set offset larger than 300000. With marker based pagination you can iterate over folders containing more than 300000 elements. With marker based pagination you cannot use sorting. Use `SortParameters.none()` to turn off sort. If you want to use PagingParameters to start marker based pagination do: ``` BoxFolder folder = new BoxFolder(this.api, "12345"); // disable sorting SortParameters sorting = SortParameters.none(); // setup paging with makred based pagination and limit 100 long limit = 100; PagingParameters paging = PagingParameters.marker(limit) Iterable<BoxItem.Info> itemIterator = childFolder.getChildren(sorting, paging); while (itemIterator.hasNext()) { BoxItem.Info itemInfo=itemIterator.next(); // Do something } ``` ## Get a Folder's Information Calling [`getInfo()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getInfo-java.lang.String...-) on a folder returns a snapshot of the folder's info. ``` BoxFolder folder = new BoxFolder(api, "id"); BoxFolder.Info info = folder.getInfo(); ``` Requesting information for only the fields you need can improve performance and reduce the size of the network request. The [`getInfo(String... fields)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getInfo-java.lang.String...-) method lets you specify which fields are retrieved. ``` BoxFolder folder = new BoxFolder(api, "id"); // Only get information about a few specific fields. BoxFolder.Info info = folder.getInfo("size", "owned_by"); ``` ## Update a Folder's Information Updating a folder's information is done by creating a new `BoxFolder.Info` object or updating an existing one, and then calling [`updateInfo(BoxFolder.Info fieldsToUpdate)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateInfo-com.box.sdk.BoxFolder.Info-). ``` BoxFolder folder = new BoxFolder(api, "id"); BoxFolder.Info info = folder.new Info(); info.setName("New Name"); folder.updateInfo(info); ``` ## Create a Folder Create a child folder by calling [`createFolder(String folderName)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createFolder-java.lang.String-) on the parent folder. ``` BoxFolder parentFolder = new BoxFolder(api, "id"); BoxFolder.Info childFolderInfo = parentFolder.createFolder("Child Folder Name"); ``` ## Copy a Folder Call the [`copy(BoxFolder destination)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#copy-com.box.sdk.BoxFolder-) method to copy a folder to another folder. ``` BoxFolder folder = new BoxFolder(api, "id1"); BoxFolder destination = new BoxFolder(api, "id2"); folder.copy(destination); ``` You can also use the [`copy(BoxFolder destination, String newName)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#copy-com.box.sdk.BoxFolder-java.lang.String-) method to rename the folder while copying it. This allows you to make a copy of the folder in the same parent folder, but with a different name. ``` BoxFolder folder = new BoxFolder(api, "id1"); BoxFolder.Info parentFolderInfo = folder.getInfo().getParent(); BoxFolder parentFolder = parentFolderInfo.getResource(); folder.copy(parentFolder, "New Name"); ``` ## Move a Folder Call the [`move(BoxFolder destination)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#move-com.box.sdk.BoxFolder-) method with the destination you want the folder moved to. ``` BoxFolder folder = new BoxFolder(api, "id1"); BoxFolder destination = new BoxFolder(api, "id2"); folder.move(destination); ``` ## Rename a Folder Call the [`rename(String newName)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#rename-java.lang.String-) method with a new name for the folder. ``` BoxFolder folder = new BoxFolder(api, "id"); folder.rename("New Name"); ``` A folder can also be renamed by updating the folder's information. This is useful if you want to perform more than one change to the folder in a single API request. ``` BoxFolder folder = new BoxFolder(api, "id"); BoxFolder.Info info = folder.new Info(); info.setName("New Name"); folder.updateInfo(info); ``` ## Delete a Folder A folder can be deleted with the [`delete(boolean recursive)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#delete-boolean-) method. Passing `true` to this method indicates that the folder and its contents should be recursively deleted. ``` // Delete the folder and all its contents BoxFolder folder = new BoxFolder(api, "id"); folder.delete(true); ``` ## Find Folder for Shared Link To get the folder information for a shared link, you can call [`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-) with the shared link to get information about the folder behind it. ``` String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); ``` If the shared link is password-protected, call [`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-) with the shared link and password. ``` String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; String password = "letmein"; BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); ``` ## Create a Shared Link A shared link for a folder can be generated by calling [`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkRequest-). ``` // Optionally we can calculate and set the date when shared link will automatically be disabled final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; Date unsharedDate = new Date(unsharedTimestamp); BoxFolder folder = new BoxFolder(api, "id"); BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() .access(OPEN) .permissions(true, true) .unsharedDate(unsharedDate); BoxSharedLink sharedLink = folder.createSharedLink(sharedLinkRequest); ``` A set of shared link access level constants are available through the SDK for convenience: - `BoxSharedLink.Access.OPEN` - `BoxSharedLink.Access.COLLABORATORS` - `BoxSharedLink.Access.COMPANY` - `BoxSharedLink.Access.DEFAULT` ## Get a Shared Link Retrieve the shared link for a folder by calling [`getSharedLink()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.Info.html#getSharedLink--). ``` BoxFolder folder = new BoxFolder(api, "id"); BoxFolder.Info info = folder.getInfo() BoxSharedLink link = info.getSharedLink() String url = link.getUrl() ``` ## Update a Shared Link A shared link for a folder can be updated by calling the same method as used when creating a shared link, [`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkRequest-). ``` BoxFolder folder = new BoxFolder(api, "id"); BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() .access(OPEN) .permissions(true, true); BoxSharedLink sharedLink = folder.createSharedLink(sharedLinkRequest); ``` ## Remove a Shared Link A shared link for a folder can be removed by calling [`removeSharedLink()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#removeSharedLink--). ``` BoxFolder folder = new BoxFolder(api, "12345"); BoxFolder.Info info = folder.getInfo(); info.removeSharedLink(); folder.updateInfo(info); ``` ## Share a Folder You can invite another person to collaborate on a folder with the [`collaborate(String emailAddress, BoxCollaboration.Role role)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-java.lang.String-com.box.sdk.BoxCollaboration.Role-) method. ``` BoxFolder folder = new BoxFolder(api, "id"); BoxCollaboration.Info collabInfo = folder.collaborate("gcurtis@box.com", BoxCollaboration.Role.EDITOR); ``` If you already know the user's ID, you can invite them directly without needing to know their email address with the [`collaborate(BoxCollaborator user, BoxCollaboration.Role role)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role-) method. ``` BoxUser collaborator = new User(api, "user-id"); BoxFolder folder = new BoxFolder(api, "folder-id"); BoxCollaboration.Info collabInfo = folder.collaborate(collaborator, BoxCollaboration.Role.EDITOR); ``` You can also create a collaboration with all properties set at once by using the [`collaborate(BoxCollaborator user, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.util.Date-java.lang.Boolean-) method. The `notify` parameter will determine if the user or group will receive an email notification when being added as a collaborator. This option is only available to enterprise administrators. The `canViewPath` parameter allows the invitee to see the entire list of ancestor folders of the associated file. The user will not gain privileges in any ancestor folder, but will be able to see the whole path to that file in the owner's account. The `expiresAt` parameter allows the owner to set a date-time in the future when the collaboration should expire. The `isAccessOnly` parameter allows the owner to set the collaboration to be access only collaboration. The `notify`, `canViewPath`, `expiresAt` and `isAccessOnly` parameters can be left as `null`. ## Get All Collaborations for a Folder The [`getCollaborations()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getCollaborations--) method will return a collection of `BoxCollaboration.Info` objects for a folder. ``` BoxFolder folder = new BoxFolder(api, "id"); Collection<BoxCollaboration.Info> collaborations = folder.getCollaborations(); ``` ## Create Metadata Metadata can be created on a folder by calling [`createMetadata(Metadata metadata)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-com.box.sdk.Metadata-), [`createMetadata(String templateName, Metadata metadata)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-java.lang.String-com.box.sdk.Metadata-), or [`createMetadata(String templateName, String scope, Metadata metadata)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata-) ``` BoxFolder folder = new BoxFolder(api, "id"); folder.createMetadata(new Metadata().add("/foo", "bar")); ``` Note: This method will only succeed if the provided metadata template is not currently applied to the folder, otherwise it will fail with a Conflict error. To get to know how to edit existing metadata please go to [set metadata](#set-metadata) and [update metadata](#update-metadata) sections. ## Set Metadata To set metadata on a folder, call [`setMetadata(String templateName, String scope, Metadata metadata)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata-). This method will try to create provided metadata on a folder. However, if metadata has already been applied to this folder, it will overwrite values of metadata keys specified in the `metadata` parameter. The metadata keys not specified in the `metadata` parameter will remain unchanged. ``` BoxFolder folder = new BoxFolder(api, "id"); folder.setMetadata("test_template", "enterprise", new Metadata().add("/foo", "bar")); ``` Note: If you want to set new metadata on a folder including hard reset of the current metadata (also removing keys not specified in the `metadata` param): first delete metadata as specified in [delete metadata](#delete-metadata) section and then set new metadata again. ## Get Metadata Retrieve a folder's metadata by calling [`getMetadata()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata--), [`getMetadata(String templateName)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String-), or [`getMetadata(String templateName, String scope)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadata-java.lang.String-java.lang.String-). These methods return a [`Metadata`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html) object, which allows access to metadata values. ``` BoxFolder folder = new BoxFolder(api, "id"); Metadata metadata = folder.getMetadata(); // Unknown type metadata field, you can test for type or try to get as any type JsonValue unknownValue = metadata.getValue("/someField"); // String or Enum metadata fields String stringValue = metadata.getString("/author"); // Float metadata fields can be interpreted as any numeric type float floatValue = metadata.getFloat("/price"); // Date metadata fields Date dateValue = metadata.getDate("/deadline"); ``` ## Update Metadata Update a folder's metadata by calling [`updateMetadata(Metadata properties)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateMetadata-com.box.sdk.Metadata-). Note: This method will only succeed if the provided metadata template has already been applied to the folder. If the folder does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know the folder will already have metadata applied, since it will save an API call compared to `setMetadata()`. ``` BoxFolder folder = new BoxFolder(api, "id"); folder.updateMetadata(new Metadata().add("/foo", "bar")); ``` Also, it is possible to add multi-select fields for your folder metadata by calling [`updateMetadata(Metadata properties)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateMetadata-com.box.sdk.Metadata-) with a list of values. ``` BoxFolder folder = new BoxFolder(api, "id"); List<String> valueList = new ArrayList<String>(); valueList.add("bar"); valueList.add("qux"); folder.updateMetadata(new Metadata().add("/foo", valueList)); ``` If you wanted to replace all selected fields for a specified key you can use the [`replace(String key, List<String> values)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#replace-java.lang.String-java.util.List-). ``` BoxFolder folder = new BoxFolder(api, "id"); List<String> valueList = new ArrayList<String>(); valueList.add("bar"); valueList.add("qux"); folder.updateMetadata(new Metadata().replace("/foo", valueList)); ``` ## Delete Metadata A folder's metadata can be deleted by calling [`deleteMetadata()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata--), [`deleteMetadata(String templateName)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata-java.lang.String-), or [`deleteMetadata(String templateName, String scope)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteMetadata-java.lang.String-java.lang.String-). ``` BoxFolder folder = new BoxFolder(api, "id"); folder.deleteMetadata("myMetadataTemplate"); ``` ## Get All Metadata on Folder [`getAllMetadata()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getAllMetadata-java.lang.String...-) method will return an iterable that will page through all of the metadata associated with the folder. ``` BoxFolder file = new BoxFolder(api, "id"); Iterable<Metadata> metadataList = folder.getAllMetadata(); for (Metadata metadata : metadataList) { // Do something with the metadata. } ``` ## Get Metadata for Multiple Files When fetching a large number of items, for example the items in a folder, it would often be impractical to fetch the metadata for each of those items individually. Instead, you can get the metadata for all of the items in a single API call by requesting the `metadata` field on those items: **Note:** The field name should have the form `metadata.<templateScope>.<templateKey>` ``` BoxFolder root = BoxFolder.getRootFolder(); Iterable<BoxItem.Info> itemsInFolder = root.getChildren("metadata.global.properties") for (BoxItem.Info itemInfo : itemsInFolder) { if (itemInfo instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; Metadata itemMetadata = fileInfo.getMetadata("properties", "global"); } else if (itemInfo instanceof BoxFolder.Info) { BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; Metadata itemMetadata = folderInfo.getMetadata("properties", "global"); } } ``` ## Set Classification on Folder Calling the [`setClassification(String classificationType)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setClassification-java.lang.String...-) method on a folder will add a classification template on the folder. This method will return the classification type applied on the folder. The classification types include `Public`, `Internal`, and `Confidential`. `Public` being the most available permission, `Internal` which restricts the specified file to company and collaborators only, and finally, `Confidential`, which is for collaborators only. ``` BoxFolder folder = new BoxFolder(api, "id"); String classificationType = folder.setClassification("Public"); ``` It is important to note that this call will attempt to create a classification on the folder first, if one already exists then it will do the update. If you already know that a classification exists on the folder and would like to save an API call, we encourage you to use the [`updateClassification(String classificationType)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#updateClassification-java.lang.String...-) method. ``` BoxFolder folder = new BoxFolder(api, "id"); String classificationType = folder.updateClassification("Public"); ``` ## Get Classification on Folder To retrieve the classification assigned on the folder, use the [`getClassification()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getClassification-java.lang.String...-) method. This will return the classification type on the folder. ``` BoxFolder folder = new BoxFolder(api, "id"); String classificationType = folder.getClassification(); ``` ## Remove Classification on Folder To remove classification from the folder, use the [`deleteClassification()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#deleteClassification--) method. ``` BoxFolder folder = new BoxFolder(api, "id"); folder.deleteClassification(); ``` ## Create Cascade Policy On Folder To set a metadata policy, which applies metadata values on a folder to new items in the folder, call [`BoxFolder.addMetadataCascadePolicy(String scope, String template)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#addMetadataCascadePolicy-java.lang.String-java.lang.String-). ``` String scope = "global"; String templateKey = "template"; String folderId = "12345"; BoxFolder folder = new BoxFolder(api, folderId); BoxMetadataCascadePolicy.Info cascadePolicyInfo = folder.addMetadataCascadePolicy(scope, template); ``` ## Get a Cascade Policy's Information To retrieve information about a specific metadata cascade policy, call [`getInfo()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getInfo-java.lang.String...-) ``` String cascadePolicyID = "1234"; BoxMetadataCascadePolicy metadataCascadePolicy = new BoxMetadataCascadePolicy(api, cascadePolicyID); BoxMetadataCascadePolicy.Info metadataCascadePolicyInfo = metadataCascadePolicy.getInfo(); ``` ## Get All Cascade Policies on Folder To get a list of all cascade policies on a folder, which show the metadata templates that are being applied to all items in the folder, call [`getMetadataCascadePolicies()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadataCascadePolicies--) on that folder. ``` String folderID = "2222"; BoxFolder folder = new BoxFolder(api, folderID); Iterable<BoxMetadataCascadePolicy.Info> metadataCascadePolicies = folder.getMetadataCascadePolicies(); for (BoxMetadataCascadePolicy.Info policyInfo : metadataCascadePolicies) { // take action on policy here } ``` You can also call [`getMetadataCascadePolicies(String enterpriseID, int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getMetadataCascadePolicies-java.lang.String-int-) and set the `enterpriseID` option to retrieve metadata cascade policies from another enterprise. ``` String folderID = "2222"; String enterpriseID = "3333"; int limit = 50; BoxFolder folder = new BoxFolder(api, folderID); Iterable<BoxMetadataCascadePolicy.Info> metadataCascadePolicies = folder.getMetadataCascadePolicies(enterpriseID, limit); for (BoxMetadataCascadePolicy.Info policyInfo : metadataCascadePolicies) { // take action on policy here } ``` ## Force Apply Cascade Policy on Folder To force apply a metadata template policy and apply metadata values to all existing items in an affected folder, call [`forceApply(String conflictResolution)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxMetadataCascadePolicy.html#forceApply-java.lang.String-) with the conflict resolution method for dealing with items that already have a metadata value that conflicts with the folder. Specifying a resolution value of `none` will preserve the existing values on items, and specifying `overwrite` will overwrite values on items in the folder with the metadata value from the folder. ``` String cascadePolicyID = "e4392a41-7de5-4232-bdf7-15e0d6bba067"; BoxMetadataCascadePolicy policy = new BoxMetadataCascadePolicy(api, cascadePolicyID); policy.forceApply("none"); ``` ## Delete Cascade Policy To remove a cascade policy and stop applying metadata from a folder to items in the folder, call [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxMetadataCascadePolicy.html#delete--). ``` String cascadePolicyID = "e4392a41-7de5-4232-bdf7-15e0d6bba067"; BoxMetadataCascadePolicy policyToDelete = new BoxMetadataCascadePolicy(api, cascadePolicyID); policyToDelete.delete(); ``` ## Lock a Folder To lock a folder and prevent it from being moved and/or deleted, call [`lock()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#lock--) on a folder. ``` BoxFolder folder = new BoxFolder(api, "id"); FolderLock.Info folderLock = folder.lock(); ``` ## Get All Locks on a Folder To get all locks on a folder, call [`getlock()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getLocks--) on folder. ``` BoxFolder folder = new BoxFolder(this.api, "id"); Iterable<BoxFolderLock.Info> locks = folder.getLocks(); for (BoxFolderLock.Info lockInfo : locks) { // Do something with each lockInfo here } ``` ## Delete a Lock on a Folder To delete a lock on a folder, call [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolderLock.html#delete--) on a BoxFolderLock object. This cannot be called on a BoxFolder object. ``` BoxFolderLock folderLock = new BoxFolderLock(this.api, "folderLockID"); folderLock.delete(); ``` --- ## Untitled *Type: page* Groups Groups are sets of users that can be used in collaborations. Get All Groups Create a Group Get Information About a Group Update a… # Groups Groups are sets of users that can be used in collaborations. - [Get All Groups](#get-all-groups) - [Create a Group](#create-a-group) - [Get Information About a Group](#get-information-about-a-group) - [Update a Group](#update-a-group) - [Delete a Group](#delete-a-group) - [Get first page of a Group's Collaborations](#get-a-groups-collaborations) - [Get all of a Group's Collaborations](#get-all-a-groups-collaborations) - [Create Membership](#create-membership) - [Get Membership](#get-membership) - [Update Membership](#update-membership) - [Delete Membership](#delete-membership) - [Get Memberships for Group](#get-memberships-for-group) - [Get Memberships for User](#get-memberships-for-user) ## Get All Groups Calling the static [`getAllGroups(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getAllGroups-com.box.sdk.BoxAPIConnection-) will return an iterable that will page through all of the user's groups. ``` Iterable<BoxGroup.Info> groups = BoxGroup.getAllGroups(api); for (BoxGroup.Info groupInfo : groups) { // Do something with the group. } ``` ## Create a Group The static [`createGroup(BoxAPIConnection api, String name)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#createGroup-com.box.sdk.BoxAPIConnection-java.lang.String-) method will let you create a new group with a specified name. ``` BoxGroup.Info groupInfo = BoxGroup.createGroup(api, "My Group"); ``` ## Get Information About a Group To look up the information about a group by the group's ID, instantiate the [`BoxGroup`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html) object with the group ID and then call [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getInfo-java.lang.String...-) on the group. You can optionally call [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getInfo-java.lang.String...-) to specify the list of fields to retrieve for the group, which can result in reduced payload size. ``` String groupID = "92875"; BoxGroup.Info groupInfo = new BoxGroup(api, groupID).getInfo(); ``` ## Update a Group To update a group, call [`updateInfo(BoxGroup.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#updateInfo-com.box.sdk.BoxGroup.Info-) method. ``` BoxGroup group = new BoxGroup(api, id); BoxGroup.Info groupInfo = group.getInfo(); groupInfo.setName("New name for My Group"); group.updateInfo(groupInfo); ``` ## Delete a Group A group can be deleted by calling the [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#delete--) method. ``` BoxGroup group = new BoxGroup(api, "id"); group.delete(); ``` ## Get first page of a Group's Collaborations The first page of a group's collaborations can be retrieved by calling the [`getCollaborations()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getCollaborations--) method. ``` BoxGroup group = new BoxGroup(api, "id"); Collection<BoxCollaboration.Info> collaborations = group.getCollaborations(); ``` ## Get all of a Group's Collaborations All of a group's collaborations can be retrieved by calling the [`getAllCollaborations(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getAllCollaborations--) method. An iterable is returned to allow a user to iterate until the last collaboration. ``` BoxGroup group = new BoxGroup(api, "id"); Iterable<BoxCollaboration.Info> collaborations = group.getAllCollaborations(); ``` ## Create Membership Membership for the group can be created by calling the [`addMembership(BoxUser user)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#addMembership-com.box.sdk.BoxUser-) and [`addMembership(BoxUser user, BoxGroupMembership.GroupRole role)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#addMembership-com.box.sdk.BoxUser-com.box.sdk.BoxGroupMembership.GroupRole-) methods. ``` BoxGroup group = new BoxGroup(api, "groupID"); BoxUser user = new BoxUser(api, "userID"); BoxGroupMembership.Info groupMembershipInfo = group.addMembership(user); ``` ## Get Membership A groups membership can be retrieved by calling the [`BoxGroupMembership.getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#getInfo--) method. ``` BoxGroupMembership membership = new BoxGroupMembership(api, id); BoxGroupMembership.Info groupMembershipInfo = membership.getInfo(); ``` ## Update Membership A groups membership can be updated by calling the [`BoxGroupMembership.updateInfo(BoxGroupMembership.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#updateInfo-com.box.sdk.BoxGroupMembership.Info-) method. ``` BoxGroupMembership membership = new BoxGroupMembership(api, id); BoxGroupMembership.Info info = membership.new Info(); info.setGroupRole(BoxGroupMembership.GroupRole.MEMBER); membership.updateInfo(info); ``` ## Delete Membership A group can be deleted by calling the [`BoxGroupMembership.delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroupMembership.html#delete--) method. ``` BoxGroupMembership membership = new BoxGroupMembership(api, id); membership.delete(); ``` ## Get Memberships for Group Calling the [`getAllMemberships(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGroup.html#getAllMemberships-java.lang.String...-) will return an iterable that will page through all of the group's memberships. Optional parameters can be used to retrieve specific fields of the Group Membership object. ``` BoxGroup group = new BoxGroup(api, id); Iterable<BoxGroupMembership.Info> memberships = group.getAllMemberships(); for (BoxGroupMembership.Info membershipInfo : memberships) { // Do something with the membership. } ``` ## Get Memberships for User Calling the [`BoxUser.getAllMemberships(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllMemberships-java.lang.String...-) will return an iterable that will page through all of the user's memberships. Optional parameters can be used to retrieve specific fields of the Group Membership object. ``` BoxUser user = new BoxUser(api, id); Iterable<BoxGroupMembership.Info> memberships = user.getAllMemberships(); for (BoxGroupMembership.Info membershipInfo : memberships) { // Do something with the membership. } ``` --- ## Untitled *Type: page* Legal Holds Policy Legal Hold Policy information describes the basic characteristics of the Policy, such as name, description, and filter… # Legal Holds Policy Legal Hold Policy information describes the basic characteristics of the Policy, such as name, description, and filter dates. - [Get Legal Hold Policy](#get-legal-hold-policy) - [Get List of Legal Hold Policies](#get-list-of-legal-hold-policies) - [Create New Legal Hold Policy](#create-new-legal-hold-policy) - [Update Existing Legal Hold Policy](#update-existing-legal-hold-policy) - [Delete Legal Hold Policy](#delete-legal-hold-policy) - [Get Assignment](#get-assignment) - [Get List of Assignments](#get-list-of-assignments) - [Create New Assignment](#create-new-assignment) - [Delete Assignment](#delete-assignment) - [Get File Version Legal Hold](#get-file-version-legal-hold) - [Get List of File Version Legal Holds](#get-list-of-file-version-legal-holds) ## Get Legal Hold Policy Calling [`getInfo(String...)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getInfo-java.lang.String...-) will return a BoxLegalHoldPolicy.Info object containing information about the legal hold policy. If necessary to retrieve limited set of fields, it is possible to specify them using param. ``` BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); BoxLegalHoldPolicy.Info policyInfo = policy.getInfo(); ``` ## Get List of Legal Hold Policies Calling the static [`getAll(BoxAPIConnection)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAll-com.box.sdk.BoxAPIConnection-) will return an iterable that will page through all of the legal hold policies. It is possible to specify name of legal hold policy, maximum number of items per response and fields to retrieve by calling the static [`getAll(BoxAPIConnection, String, int, String...)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String-int-java.lang.String...-) method. ``` Iterable<BoxLegalHoldPolicy.Info> policies = BoxLegalHoldPolicy.getAll(api); for (BoxLegalHoldPolicy.Info policyInfo : policies) { // Do something with the legal hold policy. } ``` ## Create New Legal Hold Policy The static [`create(BoxAPIConnection api, String name, String description, Date startDate, Date endDate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.Date-java.util.Date-) method will let you create a new legal hold policy with a specified name, description, start and end dates. ``` BoxLegalHoldPolicy.Info policyInfo = BoxLegalHoldPolicy.create(api, name, description, startedAt, endedAt); ``` If you wish to create an ongoing Legal Hold Policy with no end date and a description, call [`createOngoing(BoxAPIConnection api, String name, String description)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#createOngoing-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-). ``` BoxLegalHoldPolicy.Info policyInfo = BoxLegalHoldPolicy.createOngoing(api, name, description); ``` ## Update Existing Legal Hold Policy Updating a legal hold policy's information is done by calling [`updateInfo(BoxLegalHoldPolicy.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#updateInfo-com.box.sdk.BoxLegalHoldPolicy.Info-). ``` BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); BoxLegalHoldPolicy.Info policyInfo = policy.new Info(); info.setDescription("new description"); info.setPolicyName("new policy name"); policy.updateInfo(info); ``` ## Delete Legal Hold Policy A legal hold policy can be deleted by calling the [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#delete--) method. ``` BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); policy.delete(); ``` ## Get Assignment Calling [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldAssignment.html#getInfo-java.lang.String...-) will return a BoxLegalHoldAssignment.Info object containing information about the legal hold policy assignment. ``` BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(api, id); BoxLegalHoldAssignment.Info info = assignment.getInfo("assigned_by"); ``` ## Get List of Assignments Calling the static [`getAssignments(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAssignments-java.lang.String...-) will return an iterable that will page through all of the assignments of the legal hold policy. It is possible to specify filters for type and id, maximum number of items per single response and fields to retrieve by calling [`getAssignments(String type, String id, int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getAssignments-java.lang.String-java.lang.String-int-java.lang.String...-). ``` BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); Iterable<BoxLegalHoldAssignment.Info> assignments = policy.getAssignments(BoxResource.getResourceType(BoxFolder.class), null, 50, "assigned_at"); for (BoxLegalHoldAssignment.Info assignmentInfo : assignments) { // Do something with the legal hold policy assignment. } ``` ## Create New Assignment To create new legal hold policy assignment call [`assignTo(BoxResource target)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#assignTo-com.box.sdk.BoxResource-) method. Currently only BoxFile, BoxFileVersion, BoxFolder and BoxUser objects are supported as a parameter. ``` BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, policyID); BoxFolder folder = new BoxFolder(api, folderID); policy.assignTo(folder); ``` ## Delete Assignment A legal hold policy assignment can be deleted by calling the [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldAssignment.html#delete--) method of BoxLegalHoldAssignment object. ``` BoxLegalHoldAssignment assignment = new BoxLegalHoldAssignment(api, id); assignment.delete(); ``` ## Get File Version Legal Hold Calling [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionLegalHold.html#getInfo-java.lang.String...-) will return a BoxFileVersionLegalHold.Info object containing information about the file version legal hold policy. ``` BoxFileVersionLegalHold hold = new BoxFileVersionLegalHold(api, id); hold.getInfo("file"); ``` ## Get List of File Version Legal Holds To get an iterable with all non-deleted file version legal holds for current legal hold policy, call [`getFileVersionHolds(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getFileVersionHolds-java.lang.String...-). It is possible to specify maximum number of items per single response by calling [`getFileVersionHolds(int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#getFileVersionHolds-int-java.lang.String...-). ``` BoxLegalHoldPolicy policy = new BoxLegalHoldPolicy(api, id); Iterable<BoxFileVersionLegalHold.Info> fileVersionHolds = policy.getFileVersionHolds(); for (BoxFileVersionLegalHold.Info fileVersionHold : fileVersionHolds) { // Do something with the file version legal hold. } ``` --- ## Untitled *Type: page* AI AI allows to send an intelligence request to supported large language models and returns an answer based on the provided prompt and items… # AI AI allows to send an intelligence request to supported large language models and returns an answer based on the provided prompt and items. [AI](#ai) - [Send AI request](#send-ai-request) - [Send AI text generation request](#send-ai-text-generation-request) - [Get AI Agent default configuration](#get-ai-agent-default-configuration) - [Extract metadata freeform](#extract-metadata-freeform) - [Extract metadata structured](#extract-metadata-structured) ## Send AI request To send an AI request, call static [`sendAIRequest(String prompt, List<BoxAIItem> items, Mode mode)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#sendAIRequest-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List-com.box.sdk.BoxAI.Mode-) method. In the request you have to provide a prompt, a list of items that your prompt refers to and a mode of the request. There are two modes available: `SINGLE_ITEM_QA` and `MULTI_ITEM_QA`, which specifies if this request refers to for a single or multiple items. ``` BoxAIResponse response = BoxAI.sendAIRequest( api, "What is the content of the file?", Collections.singletonList("123456", BoxAIItem.Type.FILE), BoxAI.Mode.SINGLE_ITEM_QA ); ``` You can also provide a list of dialogue history entries to provide additional context to the LLM in generating the response, AI Agent configuration and flag to indicate whether citations should be returned. NOTE: The AI endpoint may return a 412 status code if you use for your request a file which has just been updated to the box. It usually takes a few seconds for the file to be indexed and available for the AI endpoint. ## Send AI text generation request To send an AI request specifically focused on the creation of new text, call static [`sendAITextGenRequest(String prompt, List<BoxAIItem> items, List<BoxAIDialogueEntry> dialogueHistory)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#sendAITextGenRequest-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List-java.util.List-) method. In the request you have to provide a prompt, a list of items that your prompt refers to and optionally a dialogue history, which provides additional context to the LLM in generating the response. ``` List<BoxAIDialogueEntry> dialogueHistory = new ArrayList<>(); dialogueHistory.add( new BoxAIDialogueEntry( "Make my email about public APIs sound more professional", "Here is the first draft of your professional email about public APIs.", BoxDateFormat.parse("2013-05-16T15:26:57-07:00") ) ); BoxAIResponse response = BoxAI.sendAITextGenRequest( api, "Write an email to a client about the importance of public APIs.", Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), dialogueHistory ); ``` You can also provide an AI Agent configuration to customize the behavior of the AI response generation. ## Get AI Agent default configuration To get the default configuration of the AI Agent, call static [`getAiAgentDefaultConfig(BoxAPIConnection api, BoxAIAgent.Mode mode, String language, String model)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#getAiAgentDefaultConfig-com.box.sdk.BoxAPIConnection-com.box.sdk.ai.BoxAIAgent.Mode-java.lang.String-java.lang.String-) method. In the request you have to provide the mode of the AI Agent, the language and the model, with the model is required while the language and mode are optional. ``` BoxAIAgentConfig config = BoxAI.getAiAgentDefaultConfig( api, BoxAIAgent.Mode.ASK, "en", "openai__gpt_3_5_turbo" ); ``` ## Extract metadata freeform To send an AI request to supported Large Language Models (LLMs) and extract metadata in form of key-value pairs, call static [`extractMetadataFreeform(BoxAPIConnection api, String prompt, List<BoxAIItem> items)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataFreeform-com.box.sdk.BoxAPIConnection-java.lang.String-java.util.List-) method. In the request you have to provide a prompt, a list of items that your prompt refers to and an optional agent configuration. ``` BoxAIResponse response = BoxAI.extractMetadataFreeform( api, "firstName, lastName, location, yearOfBirth, company", Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)) ); ``` ## Extract metadata structured Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. For this request, you need to use an already defined metadata template or define a schema yourself. To send an AI request to extract metadata from files with a predefined metadata template, call static [`extractMetadataStructured extractMetadataStructured(BoxAPIConnection api, List<BoxAIItem> items, BoxAIExtractMetadataTemplate template)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataStructured-com.box.sdk.BoxAPIConnection-java.util.List-com.box.sdk.ai.metadata.BoxAIExtractMetadataTemplate-) method. ``` BoxAIExtractMetadataTemplate template = new BoxAIExtractMetadataTemplate("templateKey", "enterprise"); BoxAIExtractStructuredResponse result = BoxAI.extractMetadataStructured( api, Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), template ); JsonObject sourceJson = result.getSourceJson(); ``` To send an AI request to extract metadata from files with custom fields, call static [`extractMetadataStructured extractMetadataStructured(BoxAPIConnection api, List<BoxAIItem> items, List<BoxAIExtractField> fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAI.html#extractMetadataStructured-com.box.sdk.BoxAPIConnection-java.util.List-java.util.List-) method. ``` List<BoxAIExtractField> fields = new ArrayList<>(); fields.add(new BoxAIExtractField("firstName")); BoxAIExtractStructuredResponse result = BoxAI.extractMetadataStructured( api, Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)), fields ); JsonObject sourceJson = result.getSourceJson(); ``` --- ## Untitled *Type: page* Logging in SDK We are using Java Util Logging within Box Java SDK. You can read about details of this approach here. Logging Levels We are… # Logging in SDK We are using `Java Util Logging` within Box Java SDK. You can read about details of this approach [here](https://docs.oracle.com/javase/8/docs/technotes/guides/logging/overview.html). ## Logging Levels We are using only few of the logging levels: - `FINE` - when logging debugging information, like success responses, - `WARNING` - when API returned 4xx response code, - `SEVERE` - when API returned 5XX response code. By default, the `Java Util Logging` prints to console output only messages that are logged at least at `INFO` level. You can limit what is being logged by setting desired level on `com.box.sdk` logger like this: ``` import com.box.sdk.BoxLogger; BoxLogger.defaultLogger().setLevelToError(); ``` Example above will limit printed logs to `SEVERE` level only. ### Getting FINE (ALL) logs printed By default `FINE` level logs are not printed to the console. There are several ways to do that. One way is to define custom handler: ``` import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; Logger sdkLogger = BoxLogger.defaultLogger(); Handler systemOut = new ConsoleHandler(); // this handler will print any message to System.out systemOut.setLevel(Level.ALL); sdkLogger.addHandler(systemOut); // allow sdk logger to print FINE logs sdkLogger.setLevelToAll(); // prevent logs from being processed by default Console handler sdkLogger.setUseParentHandlers(false); ``` you can do this in your aplication initialization. ### Turn logging off To disable logging use `BoxLogger.defaultLogger().turnLoggingOff()`. ### Reset to default logging level To reset to default logging level use `BoxLogger.defaultLogger().resetToDefaultLevel()`. ## Putting SDK logs into application logs If you are using different logging solution like Log4J2 or Logstash you can use SLF4J and proper bridgge to get your logs into desired solution. Below is an example of adding SDK logs into Logstash. First you will need to add SLF4j and Logstash binaries: ``` implementation 'org.slf4j:jul-to-slf4j:1.7.32' // bridge from Java Util Logging to SLF4J API implementation 'org.slf4j:slf4j-api:1.7.32' // define SLF4J API implementation 'ch.qos.logback:logback-core:1.2.7' // use the Logback logging framework implementation 'ch.qos.logback:logback-classic:1.2.7' // get bindings between SLF4J and Logback ``` Now when initializing application you will need to make Java Util Logging to use SLF4J. This sample is based on description provided [here](http://www.slf4j.org/api/org/slf4j/bridge/SLF4JBridgeHandler.html): ``` import org.slf4j.bridge.SLF4JBridgeHandler; // Remove existing handlers attached to JUL root logger SLF4JBridgeHandler.removeHandlersForRootLogger(); // add SLF4JBridgeHandler to JUL's root logger SLF4JBridgeHandler.install(); ``` Now all logs generated by SDK will be captured by Logback. If you want to see debug logs from SDK you will need to add this configuration to your logback.xml file: ``` <logger name="com.box.sdk" level="DEBUG"/> ``` Below is a list of log levels used by SDK and coresponding Logback levels: | SDK | Logback | | --- | --- | | ALL | ALL | | OFF | OFF | | FINE | DEBUG | | INFO | INFO | | WARN | WARN | | SEVERE | ERROR | You can read more on java Util Logging to SLF4J bridge [here](http://www.slf4j.org/legacy.html#jul-to-slf4j). --- ## Untitled *Type: page* Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other… # Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other common file operations (move, copy, delete, etc.). - [Get a File's Information](#get-a-files-information) - [Update a File's Information](#update-a-files-information) - [Download a File](#download-a-file) - [Upload a File](#upload-a-file) - [Upload Preflight Check](#upload-preflight-check) - [Upload a Large File in Chunks](#upload-a-large-file-in-chunks) - [Upload a Large File in Chunks Including Attributes](#upload-a-large-file-in-chunks-including-attributes) - [Upload a Large File Version in Chunks](#upload-a-large-file-version-in-chunks) - [Upload a Large File Version in Chunks Including Attributes](#upload-a-large-file-version-in-chunks-including-attributes) - [Upload a Large File Or File Version Manually](#upload-a-large-file-or-file-version-manually) - [Move a File](#move-a-file) - [Copy a File](#copy-a-file) - [Delete a File](#delete-a-file) - [Get Previous Versions of a File](#get-previous-versions-of-a-file) - [Upload a New Version of a File](#upload-a-new-version-of-a-file) - [Download a Previous Version of a File](#download-a-previous-version-of-a-file) - [Promote a Previous Version of a File](#promote-a-previous-version-of-a-file) - [Delete a Previous Version of a File](#delete-a-previous-version-of-a-file) - [Lock a File](#lock-a-file) - [Unlock a File](#unlock-a-file) - [Find File for Shared Link](#find-file-for-shared-link) - [Download File for Shared Link](#download-file-for-shared-link) - [Create a Shared Link](#create-a-shared-link) - [Get a Shared Link](#get-a-shared-link) - [Update a Shared Link](#update-a-shared-link) - [Remove a Shared Link](#remove-a-shared-link) - [Add a Collaborator](#add-a-collaborator) - [Get an Embed Link](#get-an-embed-link) - [Create Metadata](#create-metadata) - [Set Metadata](#set-metadata) - [Get Metadata](#get-metadata) - [Update Metadata](#update-metadata) - [Delete Metadata](#delete-metadata) - [Get All Metadata on File](#get-all-metadata-on-file) - [Set Classification on File](#set-classification-on-file) - [Get Classification on File](#get-classification-on-file) - [Remove Classification on File](#remove-classification-on-file) - [Get File Representations](#get-file-representations) - [Get Representation Content](#get-representation-content) ## Get a File's Information Calling [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfo-java.lang.String...-) on a file returns a snapshot of the file's info. ``` BoxFile file = new BoxFile(api, "id"); BoxFile.Info info = file.getInfo(); ``` Requesting information for only the fields you need with [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfo-java.lang.String...-) can improve performance and reduce the size of the network request. ``` BoxFile file = new BoxFile(api, "id"); // Only get information about a few specific fields. BoxFile.Info info = file.getInfo("size", "owned_by"); ``` ## Update a File's Information Updating a file's information is done by creating a new [`BoxFile.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.Info.html) object or updating an existing one, and then calling [`updateInfo(BoxFile.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateInfo-com.box.sdk.BoxFile.Info-). ``` BoxFile file = new BoxFile(api, "id"); BoxFile.Info info = file.new Info(); info.setName("New Name"); file.updateInfo(info); ``` ## Download a File A file can be downloaded by calling [`download(OutputStream stream)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#download-java.io.OutputStream-) and providing an `OutputStream` where the file's contents will be written. ``` BoxFile file = new BoxFile(api, "id"); BoxFile.Info info = file.getInfo(); FileOutputStream stream = new FileOutputStream(info.getName()); file.download(stream); stream.close(); ``` Download progress can be tracked by providing a [`ProgressListener`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/ProgressListener.html) to [`download(OutputStream stream, ProgressListener progress)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#download-java.io.OutputStream-com.box.sdk.ProgressListener-). The `ProgressListener` will then receive progress updates as the download completes. ``` BoxFile file = new BoxFile(api, "id"); BoxFile.Info info = file.getInfo(); FileOutputStream stream = new FileOutputStream(info.getName()); // Provide a ProgressListener to monitor the progress of the download. file.download(stream, new ProgressListener() { public void onProgressChanged(long numBytes, long totalBytes) { double percentComplete = numBytes / totalBytes; } }); stream.close(); ``` ## Upload a File Files are uploaded to a folder by calling the [`uploadFile(InputStream fileContents, String fileName)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String-) method on the [`BoxFolder`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html) you want to upload the file into. ``` BoxFolder rootFolder = BoxFolder.getRootFolder(api); FileInputStream stream = new FileInputStream("My File.txt"); BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt"); stream.close(); ``` Note that using `FileInputStream` allows you to read the content of the file only once. If the first upload attempt fails, the stream will become exhausted, and request retry with no content might be performed. To retry an upload, you would have to create a new `FileInputStream` and call `uploadFile()` method again. If you want the SDK to automatically retry the upload in case of any error, you need to provide an `InputStream` class that supports the `reset()` operation. For example, you can read all bytes from your file into a `ByteArrayInputStream` and then use it for the upload method. Be aware that this approach will load the whole file into memory, so it is not recommended for large files, as it can exhaust easily your memory. ``` BoxFolder rootFolder = BoxFolder.getRootFolder(api); InputStream stream = new ByteArrayInputStream(Files.readAllBytes(new File(path).toPath())); BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt"); stream.close(); ``` Upload progress can be tracked by providing the size of the file and a [`ProgressListener`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/ProgressListener.html) to [`uploadFile(InputStream fileContents, String fileName, long fileSize, ProgressListener progress)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String-long-com.box.sdk.ProgressListener-). The `ProgressListener` will then receive progress updates as the upload completes. ``` BoxFolder rootFolder = BoxFolder.getRootFolder(api); FileInputStream stream = new FileInputStream("My File.txt"); BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt", 1024, new ProgressListener() { public void onProgressChanged(long numBytes, long totalBytes) { double percentComplete = numBytes / totalBytes; } }); stream.close(); ``` We also support the ability to attach a description of the file upon upload by calling the [`uploadFile(InputStream fileContents, String fileName, String fileDescription)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-java.io.InputStream-java.lang.String-java.lang.String-) method. ``` BoxFolder rootFolder = BoxFolder.getRootFolder(api); FileInputStream stream = new FileInputStream("My File.txt"); BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt", "File Description"); stream.close(); ``` ## Upload Preflight Check You may want to check if a file can be successfully uploaded before beginning the file transfer, in order to the time and bandwidth of sending the file over the network if the upload would not have succeeded. Calling the [`BoxFolder#canUpload(String fileName, long fileSize)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#canUpload-java.lang.String-long-) method on the folder you want to upload a new file into will verify that there is no name conflict and that the account has enough storage space for the file. ``` String fileName = "My Doc.pdf"; BoxFolder rootFolder = BoxFolder.getRootFolder(api); try { folder.canUpload(fileName, 98734576); // If the file upload would not have succeeded, it will not be attempted folder.uploadFile(fileContents, fileName); } catch (BoxAPIException ex) ( ) ``` ## Upload a Large File in Chunks A large file can be uploaded with the [`uploadLargeFile(InputStream fileContents, String fileName, long fileSize)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadLargeFile-java.io.InputStream-java.lang.String-long-) method on the folder to upload the new file into. This will upload the file in parts with integrity checks on each part, to ensure that network errors mid-upload do not fail the entire operation. ``` File myFile = new File("My Large_File.txt"); FileInputStream stream = new FileInputStream(myFile); BoxFolder rootFolder = BoxFolder.getRootFolder(api); BoxFile.Info fileInfo = rootFolder.uploadLargeFile(inputStream, "My_Large_File.txt", myFile.length()); ``` ## Upload a Large File in Chunks Including Attributes A large file can be uploaded, including attributes, with the [`uploadLargeFile(InputStream fileContents, String fileName, long fileSize, Map<String, String> fileAttributes)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadLargeFile-java.io.InputStream-java.lang.String-long-java.util.Map-) method on the folder to upload the new file into. This will upload the file in parts with integrity checks on each part, to ensure that network errors mid-upload do not fail the entire operation. ``` File myFile = new File("My Large_File.txt"); FileInputStream stream = new FileInputStream(myFile); Map<String, String> fileAttributes = new HashMap<String, String>(); fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); BoxFolder rootFolder = BoxFolder.getRootFolder(api); BoxFile.Info fileInfo = rootFolder.uploadLargeFile(inputStream, "My_Large_File.txt", myFile.length(), fileAttributes); ``` ## Upload a Large File Version in Chunks To upload a new file version for a large file, call the [`uploadLargeFile(InputStream fileContents, long fileSize)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadLargeFile-java.io.InputStream-long-) method on the file to be updated. This will upload the new version of the file in parts with integrity checks on each part, to ensure that network errors mid-upload do not fail the entire operation. ``` File myFile = new File("My Large_File.txt"); FileInputStream stream = new FileInputStream(myFile); String fileID = "12345"; BoxFile file = new BoxFile(api, fileID); BoxFile.Info fileInfo = file.uploadLargeFile(inputStream, myFile.length()); ``` ## Upload a Large File Version in Chunks Including Attributes To upload a new file version for a large file, including attributes, call the [`uploadLargeFile(InputStream fileContents, long fileSize, Map<String, String> fileAttributes)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadLargeFile-java.io.InputStream-long-java.util.Map-) method on the file to be updated. This will upload the new version of the file in parts with integrity checks on each part, to ensure that network errors mid-upload do not fail the entire operation. ``` File myFile = new File("My Large_File.txt"); FileInputStream stream = new FileInputStream(myFile); Map<String, String> fileAttributes = new HashMap<String, String>(); fileAttributes.put("content_modified_at", "2017-04-08T00:58:08Z"); String fileID = "12345"; BoxFile file = new BoxFile(api, fileID); BoxFile.Info fileInfo = file.uploadLargeFile(inputStream, myFile.length(), fileAttributes); ``` ## Upload a Large File Or File Version Manually To start the process of uploading a large file or file version, first create a new upload session with [`BoxFolder#createUploadSession(String fileName, String fileSize)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createUploadSession-java.lang.String-long-) for a new file, or [`BoxFile#createUploadSession(long fileSize)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createUploadSession-long-) for a new file version. Once the upload session is created, all other steps are identical for both cases. ``` BoxFileUploadSession.Info sessionInfo; if (/* uploading a new file */) { // Create the upload session for a new file BoxFolder rootFolder = BoxFolder.getRootFolder(api); sessionInfo = rootFolder.createUploadSession("New Large File.pdf", fileSize); } else if (/* uploading a new version of an exiting file */) { // Create the uplaod session for a new version of an existing file String fileID = "93465"; BoxFile file = new BoxFile(api, fileID); sessionInfo = file.createUploadSession(fileSize); } //Get the session resource from the session info BoxFileUploadSession session = sessionInfo.getResource(); //Create the Message Digest for the whole file MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException ae) { throw new BoxAPIException("Digest algorithm not found", ae); } ``` Both of these methods will return a Once the upload session is created, the large file can be uploaded in chunks with the [`uploadPart(InputStream stream, long offset, int partSize, long totalSizeOfFile)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#uploadPart-java.io.InputStream-long-int-long-) method of the session instance. If there is a failure in uploading any of the parts, the failed part can be uploaded again without affecting the other parts. ``` //Reading a large file FileInputStream fis = new FileInputStream("My_Large_File.txt"); //Create the digest input stream to calculate the digest for the whole file. DigestInputStream dis = new DigestInputStream(fis, digest); List<BoxFileUploadSessionPart> parts = new ArrayList<BoxFileUploadSessionPart>(); //Get the part size. Each uploaded part should match the part size returned as part of the upload session. //The last part of the file can be less than part size if the remaining bytes of the last part is less than //the given part size long partSize = sessionInfo.getPartSize(); //Start byte of the part long offset = 0; //Overall of bytes processed so far long processed = 0; while (processed < fileSize) { long diff = fileSize - processed; //The size last part of the file can be less than the part size. if (diff < partSize) { partSize = diff; } //Upload a part. It can be uploaded asynchorously BoxFileUploadSessionPart part = session.uploadPart(dis, offset, (int)partSize, fileSize); parts.add(part); //Increase the offset and proceesed bytes to calculate the Content-Range header. processed += partSize; offset += partSize; } ``` At any point in time, the list of parts that have been uploaded successfully can be retrieved with the [`listParts(int offset, int limit)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#listParts-int-int-) method of the session instance. ``` //The following snippet retrives first 1000 parts that are uploaded. BoxFileUploadSessionPartList partList = session.listParts(0, 1000); List<BoxFileUploadSessionPart> parts = partList.getEntries(); ``` Once all the parts are uploaded successfully, the upload session can be committed with the [`commit(String digest, List<BoxFileUploadSessionPart> parts, Map<String, String> attributes, String ifMatch, String ifNoneMatch)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#commit-java.lang.String-java.util.List-java.util.Map-java.lang.String-java.lang.String-) method. ``` //Creates the file hash byte[] digestBytes = digest.digest(); //Base64 encoding of the hash String digestStr = Base64.encode(digestBytes); //Commit the upload session. If there is a failure, abort the commit. BoxFile.Info fileInfo = session.commit(digestStr, parts, null, null, null); ``` The upload session can be aborted at any time with the [`abort()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#abort--) method of the session instance. This will cancel the upload and any parts that were already uploaded will be lost. ``` session.abort(); ``` The upload session status can be retrieved at any time with the [`getStatus()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileUploadSession.html#getStatus--) method. This call will update the parts processed and other information in the session info instance. ``` BoxFileUploadSession.Info updatedSessionInfo = session.getStatus(); ``` ## Move a File To move a file from one folder into another, call [`move(BoxFolder destination)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#move-com.box.sdk.BoxFolder-) on the file to be moved with the destination folder. ``` String fileID = "1234"; String destinationFolderID = "5678"; BoxFile file = new BoxFile(api, fileID); BoxFolder destinationFolder = new BoxFolder(destinationFolderID); file.move(destinationFolder) ``` To avoid name conflicts in the destination folder, you can optionally provide a new name for the file to [`move(BoxFolder destination, String newName)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#move-com.box.sdk.BoxFolder-java.lang.String-). The file will be placed into the destination folder with the new name. ``` String fileID = "1234"; String destinationFolderID = "5678"; BoxFile file = new BoxFile(api, fileID); BoxFolder destinationFolder = new BoxFolder(destinationFolderID); file.move(destinationFolder, "Vacation Photo (1).jpg"); ``` ## Copy a File A file can be copied to a new folder and optionally be renamed with the [`copy(BoxFolder destination)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#copy-com.box.sdk.BoxFolder-) and [`copy(BoxFolder destination, String newName)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#copy-com.box.sdk.BoxFolder-java.lang.String-) methods. ``` // Copy a file into the user's root folder BoxFolder rootFolder = BoxFolder.getRootFolder(api); BoxFile file = new BoxFile(api, "id"); BoxFile.Info copiedFileInfo = file.copy(rootFolder, "New Name"); ``` ## Delete a File Calling the [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#delete--) method will move the file to the user's trash. ``` BoxFile file = new BoxFile(api, "id"); file.delete(); ``` ## Get Previous Versions of a File For users with premium accounts, versions of a file can be retrieved with the [`getVersions()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getVersions--) method. By default, it will return up to 1000 file versions with all default fields set. ``` BoxFile file = new BoxFile(api, "id"); Collection<BoxFileVersion> versions = file.getVersions(); for (BoxFileVersion version : versions) { System.out.format("SHA1 of \"%s\": %s\n", file.getInfo().getName(), version.getSha1()); } ``` File versions can be retrieved with specified starting position with the [`getVersionsRange(long offset, long limit)`][get-versions-range] method. You can use the `limit` and `offset` parameters to page through the all available file versions. ``` BoxFile file = new BoxFile(api, "id"); Collection<BoxFileVersion> versions = file.getVersionsRange(1000, 2000); for (BoxFileVersion version : versions) { System.out.format("SHA1 of \"%s\": %s\n", file.getInfo().getName(), version.getSha1()); } ``` You can specify selected fields to be returned while getting versions information. Assume we want to get version SHA1 and version number: ``` BoxFile file = new BoxFile(api, "id"); Collection<BoxFileVersion> versions = file.getVersions("sha1", "version_number"); for (BoxFileVersion version : versions) { System.out.format("SHA1 of \"%d\": %s\n", version.getVersionNumber(), version.getSha1()); } ``` You can find a list of available fields at [`BoxFile.ALL_VERSION_FIELDS`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#ALL_VERSION_FIELDS--). ## Upload a New Version of a File New versions of a file can be uploaded with the [`uploadNewVersion(InputStream fileContents)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#uploadNewVersion-java.io.InputStream-) method. ``` BoxFile file = new BoxFile(api, "id"); FileInputStream stream = new FileInputStream("My File.txt"); file.uploadNewVersion(stream); ``` ## Download a Previous Version of a File For users with premium accounts, previous versions of a file can be downloaded by calling [`download(OutputStream output)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html#download-java.io.OutputStream-). ``` BoxFile file = new BoxFile(api, "id"); Collection<BoxFileVersion> versions = file.getVersions(); BoxFileVersion firstVersion = versions.iterator().next(); FileOutputStream stream = new FileOutputStream(firstVersion.getName()); firstVersion.download(stream); stream.close(); ``` ## Promote a Previous Version of a File A previous version of a file can be promoted with the [`promote()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html#promote--) method to become the current version of the file. ``` BoxFile file = new BoxFile(api, "id"); Collection<BoxFileVersion> versions = file.getVersions(); BoxFileVersion firstVersion = versions.iterator().next(); firstVersion.promote(); ``` ## Delete a Previous Version of a File A version of a file can be deleted and moved to the trash by calling [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html#delete--). ``` BoxFile file = new BoxFile(api, "id"); Collection<BoxFileVersion> versions = file.getVersions(); BoxFileVersion firstVersion = versions.iterator().next(); firstVersion.delete(); ``` ## Lock a File A file can be locked indefinitely by calling [`lock()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date-) on the file to be locked. A locked file cannot be modified by any other user until it is unlocked. This is useful if you want to "check out" a file while you're working on it, to ensure that other collaborators do not make changes while your changes are in progress. ``` BoxFile file = new BoxFile(api, "id"); file.lock(); ``` When locking a file, you can optionally prevent other users from downloading the file in addition to prevent changes by calling [`lock(boolean preventDownload)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-boolean-) with `true`. ``` // Lock the file and prevent downloading BoxFile file = new BoxFile(api, "id"); file.lock(true); ``` You can also set a date when the lock will automatically be released by calling [`lock(Date expirationDate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date-) with the date on which the lock should expire. This is recommended to prevent a file from accidentally being locked longer than intended. ``` final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; long expirationTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; Date expirationTime = new Date(expirationTimestamp); BoxFile file = new BoxFile(api, "id"); file.lock(expirationTime); ``` Both options can be passed together to [`lock(boolean preventDownload, Date expireTime)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#lock-java.util.Date-boolean-). ## Unlock a File A file can be unlocked by calling [`unlock()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#unlock--). ``` BoxFile file = new BoxFile(api, "id"); file.unlock(); ``` ## Find File for Shared Link To get the file information for a shared link, you can call [`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-) with the shared link to get information about the file behind it. ``` String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); ``` If the shared link is password-protected, call [`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-) with the shared link and password. ``` String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; String password = "letmein"; BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); ``` ## Download File from Shared Link A file can be downloaded via a shared link by calling [`downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String-) and providing an `OutputStream` where the file's contents will be written and shared link of the file. If the shared link is password-protected, call [`downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink, String password)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String-java.lang.String-) method. ``` FileOutputStream stream = new FileOutputStream("My File.txt"); String sharedLink = "https://cloud.box.com/s/12339wbq4c7y2xd3drg4j9j9wer3ptt6n"; String password = "Secret123@"; BoxFile.downloadFromSharedLink(api, stream, sharedLink, password); stream.close(); ``` Download progress can be tracked by providing a [`ProgressListener`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/ProgressListener.html) to [` downloadFromSharedLink(BoxAPIConnection api, OutputStream output, String sharedLink, String password, ProgressListener listener)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#downloadFromSharedLink-com.box.sdk.BoxAPIConnection-java.io.OutputStream-java.lang.String-java.lang.String-com.box.sdk.ProgressListener-). The `ProgressListener` will then receive progress updates as the download completes. ``` FileOutputStream stream = new FileOutputStream("My File.txt"); // Provide a ProgressListener to monitor the progress of the download. BoxFile.downloadFromSharedLink(api, stream, sharedLink, password, new ProgressListener() { public void onProgressChanged(long numBytes, long totalBytes) { double percentComplete = numBytes / totalBytes; } }); stream.close(); ``` ## Create a Shared Link A shared link for a file can be generated by calling [`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkRequest-). ``` // Optionally we can calculate and set the date when shared link will automatically be disabled final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; Date unsharedDate = new Date(unsharedTimestamp); BoxFile file = new BoxFile(api, "id"); BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() .access(OPEN) .permissions(true, true) .unsharedDate(unsharedDate); BoxSharedLink sharedLink = file.createSharedLink(sharedLinkRequest); ``` A set of shared link access level constants are available through the SDK for convenience: - `BoxSharedLink.Access.OPEN` - `BoxSharedLink.Access.COLLABORATORS` - `BoxSharedLink.Access.COMPANY` - `BoxSharedLink.Access.DEFAULT` ## Get a Shared Link Retrieve the shared link for a file by calling [`getSharedLink()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.Info.html#getSharedLink--). ``` BoxFile file = new BoxFile(api, "id"); BoxFile.Info info = file.getInfo(); BoxSharedLink link = info.getSharedLink(); String url = link.getUrl(); ``` ## Update a Shared Link A shared link for a file can be updated by calling the same method as used when creating a shared link, [`createSharedLink(BoxSharedLinkRequest sharedLinkRequest)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkRequest-). ``` BoxFile file = new BoxFile(api, "id"); BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() .access(OPEN) .permissions(true, true); BoxSharedLink sharedLink = file.createSharedLink(sharedLinkRequest); ``` ## Remove a Shared Link A shared link for a file can be removed by calling [`removeSharedLink()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#removeSharedLink--). ``` BoxFile file = new BoxFile(api, "12345"); BoxFile.Info info = file.getInfo(); info.removeSharedLink(); file.updateInfo(info); ``` ## Add a Collaborator You can invite another person to collaborate on a file by email with [`collaborate(String emailAddress, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#collaborate-java.lang.String-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.lang.String-java.util.Date-java.lang.Boolean-). The `notify` parameter will determine if the user or group will receive an email notification when being added as a collaborator. This option is only available to enterprise administrators. The `canViewPath` parameter allows the invitee to see the entire list of ancestor folders of the associated file. The user will not gain privileges in any ancestor folder, but will be able to see the whole path to that file in the owner's account. The `expiresAt` parameter allows the owner to set a date-time in the future when the collaboration should expire. The `isAccessOnly` parameter allows the owner to set the collaboration to be access only collaboration. The `notify`, `canViewPath`, `expiresAt` and `isAccessOnly` parameters can be left as `null`. ``` BoxFile file = new BoxFile(api, "id"); BoxCollaboration.Info collabInfo = file.collaborate("testuser@example.com", BoxCollaboration.Role.EDITOR, true, true); ``` Alternatively, if you know the user's ID, you can invite them directly without needing to know their email address with the [`collaborate(BoxCollaborator user, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath, Date expiresAt, Boolean isAccessOnly)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#collaborate-com.box.sdk.BoxCollaborator-com.box.sdk.BoxCollaboration.Role-java.lang.Boolean-java.lang.Boolean-java.lang.String-java.util.Date-java.lang.Boolean-) ``` BoxUser collaborator = new BoxUser(api, "user-id"); BoxFile file = new BoxFile(api, "file-id"); BoxCollaboration.Info collabInfo = file.collaborate(collaborator, BoxCollaboration.Role.EDITOR, true, true); ``` ## Get an Embed Link A file embed link can be generated by calling [`getPreviewLink()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getPreviewLink--). ``` BoxFile file = new BoxFile(api, "id"); URL embedLink = file.getPreviewLink(); ``` ## Create Metadata Metadata can be created on a file by calling [`createMetadata(Metadata metadata)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-com.box.sdk.Metadata-), [`createMetadata(String typeName, Metadata metadata)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-java.lang.String-com.box.sdk.Metadata-), or [`createMetadata(String typeName, String scope, Metadata metadata)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#createMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata-). ``` // Add property "foo" with value "bar" to the default metadata properties BoxFile file = new BoxFile(api, "id"); file.createMetadata(new Metadata().add("/foo", "bar")); ``` Note: This method will only succeed if the provided metadata template is not currently applied to the file, otherwise it will fail with a Conflict error. To get to know how to edit existing metadata please go to [set metadata](#set-metadata) and [update metadata](#update-metadata) sections. ## Set Metadata To set metadata on a file, call [`setMetadata(String templateName, String scope, Metadata metadata)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setMetadata-java.lang.String-java.lang.String-com.box.sdk.Metadata-). This method will try to create provided metadata on a file. However, if metadata has already been applied to this file, it will overwrite values of metadata keys specified in the `metadata` parameter. The metadata keys not specified in the `metadata` parameter will remain unchanged. ``` BoxFile file = new BoxFile(api, "id"); file.setMetadata("test_template", "enterprise", new Metadata().add("/foo", "bar")); ``` Note: If you want to set new metadata on a file including hard reset of the current metadata (also removing keys not specified in the `metadata` param): first delete metadata as specified in [delete metadata](#delete-metadata) section and then set new metadata again. ## Get Metadata Retrieve a file's Metadata by calling [`getMetadata()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata--), [`getMetadata(String typeName)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String-), or [`getMetadata(String typeName, String scope)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getMetadata-java.lang.String-java.lang.String-). These methods return a [`Metadata`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html) object, which allows access to metadata values. ``` // Get the default free-form metadata properties BoxFile file = new BoxFile(api, "id"); Metadata metadata = file.getMetadata(); // Unknown type metadata field, you can test for type or try to get as any type JsonValue unknownValue = metadata.getValue("/someField"); // String or Enum metadata fields String stringValue = metadata.getString("/author"); // Float metadata fields can be interpreted as any numeric type float floatValue = metadata.getFloat("/price"); // Date metadata fields Date dateValue = metadata.getDate("/deadline"); // Multiselect metadata fields List<String> multiSelectValues = metadata.getMultiSelect("/categories"); ``` ## Update Metadata Update a file's Metadata by calling [`updateMetadata(Metadata properties)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateMetadata-com.box.sdk.Metadata-). Note: This method will only succeed if the provided metadata template has already been applied to the file. If the file does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know the file will already have metadata applied, since it will save an API call compared to `setMetadata()`. ``` BoxFile file = new BoxFile(api, "id"); file.updateMetadata(new Metadata("templateScope", "templateKey").add("/foo", "bar")); ``` Also, it is possible to add multi-select fields for your file metadata by calling [`updateMetadata(Metadata properties)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateMetadata-com.box.sdk.Metadata-) with a list of values. ``` BoxFile file = new BoxFile(api, "id"); List<String> valueList = new ArrayList<String>(); valueList.add("bar"); valueList.add("qux"); file.updateMetadata(new Metadata("templateScope", "templateKey").add("/foo", valueList)); ``` If you wanted to replace all selected fields for a specified key you can use the [`replace(String path, List<String> values)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#replace-java.lang.String-java.util.List-). ``` BoxFile file = new BoxFile(api, "id"); List<String> valueList = new ArrayList<String>(); valueList.add("bar"); valueList.add("qux"); file.updateMetadata(new Metadata("templateScope", "templateKey").replace("/foo", valueList)); ``` If you wanted to remove a metadata value for a specified key you can use the [`remove(String path)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#remove-java.lang.String-). ``` BoxFile file = new BoxFile(api, "id"); file.updateMetadata(new Metadata("templateScope", "templateKey").remove("/foo")); ``` ## Delete Metadata A file's Metadata can be deleted by calling [`deleteMetadata()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata--), [`deleteMetadata(String typeName)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata-java.lang.String-), or [`deleteMetadata(String typeName, String scope)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteMetadata-java.lang.String-java.lang.String-). ``` BoxFile file = new BoxFile(api, "id"); file.deleteMetadata("myMetadataTemplate"); ``` ## Get All Metadata on File Calling the [`getAllMetadata()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getAllMetadata-java.lang.String...-) method on a file will return an iterable that will page through all of the metadata associated with the file. ``` BoxFile file = new BoxFile(api, "id"); Iterable<Metadata> metadataList = file.getAllMetadata(); for (Metadata metadata : metadataList) { // Do something with the metadata. } ``` ## Set Classification on File Calling the [`setClassification(String classificationType)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setClassification-java.lang.String...-) method on a file will add a classification template on the file. This method will return the classification type applied on the file. The classification types include `Public`, `Internal`, and `Confidential`. `Public` being the most available permission, `Internal` which restricts the specified file to company and collaborators only, and finally, `Confidential`, which is for collaborators only. ``` BoxFile file = new BoxFile(api, "id"); String classificationType = file.setClassification("Public"); ``` It is important to note that this call will attempt to create a classification on the file first, if one already exists then it will do the update. If you already know that a classification exists on the file and would like to save an API call, we encourage you to use the [`updateClassification(String classificationType)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#updateClassification-java.lang.String...-) method. ``` BoxFile file = new BoxFile(api, "id"); String classificationType = file.updateClassification("Public"); ``` ## Get Classification on File To retrieve the classification assigned on the file, use the [`getClassification()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getClassification-java.lang.String...-) method. This will return the classification type on the file. ``` BoxFile file = new BoxFile(api, "id"); String classificationType = file.getClassification(); ``` ## Remove Classification on File To remove classification from the file, use the [`deleteClassification()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#deleteClassification--) method. ``` BoxFile file = new BoxFile(api, "id"); file.deleteClassification(); ``` ## Get File Representations To get the preview representations of a file, call the [`getInfoWithRepresentations(String representationHints, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfoWithRepresentations-java.lang.String-java.lang.String...-) method with the [representation hints](https://developer.box.com/v2.0/reference/#section-x-rep-hints-header) to fetch, along with any other fields on the file object to fetch simultaneously. This method returns a [`BoxFile.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.Info.html) object that contains the representations as a list of [`Representation`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Representation.html) objects. Note that this method only provides information about a set of available representations; your application will need to handle checking the status of the representations and downlaoding them via the provided content URL template. ``` BoxFile file = new BoxFile(api, "1234"); // Get the PDF representation and file name String repHints = "[pdf]"; BoxFile.Info fileInfo = file.getInfoWithRepresentations(repHints, "name"); List<Representation> representations = fileInfo.getRepresentations(); String name = fileInfo.getName(); ``` ## Get Representation Content To write the contents of a single file representation to an `OutputStream`, call the [`getRepresentationContent(String representationHint, OutputStream output)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getRepresentationContent-java.lang.String-java.lang.String-java.io.OutputStream-) method with an [X-Rep-Hints value](https://developer.box.com/v2.0/reference/#section-x-rep-hints-header) specifying the representation you want. **Note:** This method only supports getting the contents of a single representation; if your X-Rep-Hints value specifies multiple representations, an arbitrary one of them will be fetched. ``` // Read the PDF representation of file 12345 into memory ByteArrayOutputStream output = new ByteArrayOutputStream(); BoxFile file = new BoxFile(api, "12345"); file.getRepresentationContent("[pdf]", output); ``` For representations with multiple files, e.g. multi-page images, you will need to pass an `assetPath` parameter to specify which file you want to fetch. ``` // If file 12345 is a document, its PNG representation will consist of one image per page of the document // Get the image of the first page of the document and write it to a file FileOutputStream output = new FileOutputStream("/path/to/file.png"); BoxFile file = new BoxFile(api, "12345"); file.getRepresentationContent("[png?dimensions=1024x1024]", "1.png", output); ``` Generating a representation for the selected file is an asynchronous operation and may take some time. Therefore, by default, the `getRepresentationContent` method periodically checks the status of the generated file and downloads it when it is ready. With the `maxRetries` parameter in [`getRepresentationContent(String representationHint, String assetPath, OutputStream output, int maxRetries)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getRepresentationContent-java.lang.String-java.lang.String-java.io.OutputStream-int-), you can define the number of status checks for the generated file, which will be performed at intervals of 100 ms. If this number is exceeded, a `BoxApiException` will be thrown. ``` FileOutputStream output = new FileOutputStream("/path/to/file.png"); BoxFile file = new BoxFile(api, "12345"); file.getRepresentationContent("[png?dimensions=1024x1024]", "1.png", output, 10); ``` --- ## Untitled *Type: page* Recent Items Recent Items returns information about files that have been accessed by a user not long ago. It keeps track of items that were… # Recent Items Recent Items returns information about files that have been accessed by a user not long ago. It keeps track of items that were accessed either in the last 90 days or the last 1000 items accessed (both conditions must be met). - [Get a User's Recent Items](#get-a-users-recent-items) ## Get a User's Recent Items Get a list of all recent items the user has by calling [`BoxRecents.getRecentItems(BoxAPIConnection api, int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRecents.html#getRecentItems-com.box.sdk.BoxAPIConnection-int-java.lang.String...-). This returns an ordered iterable of the [`BoxRecentItem`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRecentItem.html) records, which describe which item the user interacted with, when they interacted with it, and what type of interaction it was. Any `fields` specified relate to the items themselves (e.g. the recent files and folders). ``` // Get the latest 100 items the user has interacted with Iterable<BoxRecentItem> recentItems = BoxRecents.getRecentItems(api, 100); ``` --- ## Untitled *Type: page* Metadata Templates Metadata that belongs to a file is grouped by templates. Templates allow the metadata service to provide a multitude of… # Metadata Templates Metadata that belongs to a file is grouped by templates. Templates allow the metadata service to provide a multitude of services, such as pre-defining sets of key:value pairs or schema enforcement on specific fields. - [Create Metadata Template](#create-metadata-template) - [Update Metadata Template](#update-metadata-template) [Get Metadata Template](#get-metadata-template) - [Get by scope and template key](#get-by-scope-and-template-key) - [Get by ID](#get-by-id) [Get Enterprise Metadata Templates](#get-enterprise-metadata-templates) [Delete a Metadata Template](#delete-a-metadata-template) [Execute Metadata Query](#execute-metadata-query) ## Create Metadata Template The [`createMetadataTemplate(BoxAPIConnection api, String templateScope, String templateKey, String displayName, Boolean hidden, List<Field> fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#createMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String-boolean-java.util.List-) method will create a metadata template schema. You can create custom metadata fields that will be associated with the metadata template. ``` MetadataTemplate.Field metadataField = new MetadataTemplate.Field(); metadataField.setType("string"); metadataField.setKey("text"); metadataField.setDisplayName("Text"); List<MetadataTemplate.Field> fields = new ArrayList<MetadataTemplate.Field>(); fields.add(metadataField); MetadataTemplate template = MetadataTemplate.createMetadataTemplate(api, "enterprise", "CustomField", "Custom Field", false, fields); final JsonObject jsonObject = new JsonObject(); jsonObject.add("text", "This is a test text"); Metadata metadata = new Metadata(jsonObject); boxFile.createMetadata("CustomField", metadata); ``` ## Update Metadata Template To update an existing metadata template, call the [`updateMetadataTemplate(BoxAPIConnection api, String scope, String template, List<FieldOperation> fieldOperations)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#updateMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.util.List-) method with the scope and key of the template, and the list of field operations to perform: ``` List<MetadataTemplate.FieldOperation> updates = new ArrayList<MetadataTemplate.FieldOperation>(); String addCategoryFieldJSON = "{\"op\":\"addField\","\"data\":{" + "\"displayName\":\"Category\",\"key\":\"category\",\"hidden\":false,\"type\":\"string\"}}"; updates.add(new MetadataTemplate.FieldOperation(addCategoryFieldJSON)); String changeTemplateNameJSON = "{\"op\":\"editTemplate\",\"data\":{" + "\"displayName\":\"My Metadata\"}}"; updates.add(new MetadataTemplate.FieldOperation(changeTemplateNameJSON)); MetadataTemplate.updateMetadataTemplate(api, "enterprise", "myData", updates); ``` ## Get Metadata Template ### Get by scope and template key The [`getMetadataTemplate(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection-) method will return information about default metadata schema. Also, [`getMetadataTemplate(BoxAPIConnection api, String templateKey)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-) and [`getMetadataTemplate(BoxAPIConnection api, String templateKey, String templateScope, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String...-) can be used to set metadata template name, metadata scope and fields to retrieve. ``` MetadataTemplate template = MetadataTemplate.getMetadataTemplate(api, "templateName"); ``` ### Get by ID The static [`MetadataTemplate.getMetadataTemplateByID(BoxAPIConnection api, String templateID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getMetadataTemplateByID-com.box.sdk.BoxAPIConnection-java.lang.String-) method will return a specific metadata template. ``` MetadataTemplate template = MetadataTemplate.getMetadataTemplateByID(api, "37c0204b-3fe1-4a32-b9da-f28e88f4c4c6"); ``` ## Get Enterprise Metadata Templates Calling the static [`getEnterpriseMetadataTemplates(BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-com.box.sdk.BoxAPIConnection-java.lang.String...-) will return an iterable that will page through all metadata templates within a user's enterprise. Also, [`getEnterpriseMetadataTemplates(String templateScope, BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-java.lang.String-com.box.sdk.BoxAPIConnection-java.lang.String...-) and [`getEnterpriseMetadataTemplates(String templateScope, int limit, BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#getEnterpriseMetadataTemplates-java.lang.String-int-com.box.sdk.BoxAPIConnection-java.lang.String...-) can be used to set metadata scope, limit of items per single response. ``` Iterable<MetadataTemplate> templates = MetadataTemplate.getEnterpriseMetadataTemplates(api); for (MetadataTemplate templateInfo : templates) { // Do something with the metadata template. } ``` To return the metadata templates available to all enterprises pass in the `global` scope. ``` Iterable<MetadataTemplate> templates = MetadataTemplate.getEnterpriseMetadataTemplates('global', api); for (MetadataTemplate templateInfo : templates) { // Do something with the metadata template. } ``` ## Delete a Metadata Template The [`deleteMetadataTemplate(BoxAPIConnection api, String scope, String template)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#deleteMetadataTemplate-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-) method will remove a metadata template schema from an enterprise. ``` MetadataTemplate.deleteMetadataTemplate(api, "enterprise", "templateName"); ``` ## Execute Metadata Query The [`executeMetadataQuery(BoxAPIConnection api, MetadataQuery queryBody)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/MetadataTemplate.html#executeMetadataQuery-com.box.sdk.BoxAPIConnection-com.box.sdk.MetadataQuery-) method queries files and folders based on their metadata. ``` String from = "enterprise_341532.test"; String query = "testfield = :arg"; String ancestorFolderId = "0"; MetadataQuery.OrderBy primaryOrderBy = MetadataQuery.OrderBy.ascending("primarySortKey"); MetadataQuery.OrderBy secondaryOrderBy = MetadataQuery.OrderBy.ascending("secondarySortKey"); MetadataQuery mQuery = new MetadataQuery(from); mQuery.setQuery(query); mQuery.setAncestorFolderId(ancestorFolderId); mQuery.setOrderBy(primaryOrderBy, secondaryOrderBy); mQuery.addParameter("arg", "test"); mQuery.setFields("metadata.enterprise_341532.test.customField"); BoxResourceIterable<BoxItem.Info> results = MetadataTemplate.executeMetadataQuery(api, mQuery); for (BoxItem.Info r: results) { if (r instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) r; Metadata fileMetadata = fileInfo.getMetadata("test", "enterprise_341532"); String customFieldValue = fileMetadata.getString("/customField"); System.out.println(customFieldValue); } else if (r instanceof BoxFolder.Info) { BoxFolder.Info folderInfo = (BoxFolder.Info) r; Metadata folderMetadata = folderInfo.getMetadata("test", "enterprise_341532"); String customFieldValue = folderMetadata.getString("/customField"); System.out.println(customFieldValue); } } ``` --- ## Untitled *Type: page* Search Different examples of search which have been implemented in the example SearchExamplesAsAppUser.java For more information refer to… # Search Different examples of search which have been implemented in the example [SearchExamplesAsAppUser.java](https://github.com/box/box-java-sdk/blob/main/src/example/java/com/box/sdk/example/SearchExamplesAsAppUser.java) For more information refer to the [Search API documentation](https://developer.box.com/v2.0/reference#searching-for-content). - [Search](#search) ## Search A search can be performed in your Box instance with specified starting position with [`searchRange(long offset, long limit, BoxSearchParameters queryParams)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSearch.html#searchRange-long-long-com.box.sdk.BoxSearchParameters-) You can use the `limit` and `offset` parameters to page through the search results. ``` // Find the first 10 files matching "taxes" long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("taxes"); searchParams.setType("file"); PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` You can also sort the search results with the `sort` and `direction` flags passed into BoxSearch. This allows for the order of items returned to be maintained. The `sort` field can only be set to `modified_at` currently. For direction you can specify either `DESC` for descending order or `ASC` for ascending order to sort the results. ``` long offsetValue = 0; long limitValue = 10; BoxSearch boxSearch = new BoxSearch(api); BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("taxes"); searchParams.setSort("modified_at"); searchParams.setDirection("DESC"); PartialCollection<BoxItem.Info> searchResults = boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` --- ## Untitled *Type: page* Shared Items Shared Items represent files and folders on Box accessed via a shared link. Get a Shared Item Get a Shared Item To get the file… # Shared Items Shared Items represent files and folders on Box accessed via a shared link. - [Get a Shared Item](#get-a-shared-item) ## Get a Shared Item To get the file or folder information for a shared link, you can call [`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-) with the shared link to get information about the item behind it. ``` String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink); ``` If the shared link is password-protected, call [`BoxItem.getSharedItem(BoxAPIConnection api, String sharedLink, String password)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getSharedItem-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-) with the shared link and password. ``` String sharedLink = "https://app.box.com/s/abcdefghijklmnopqrstuvwxyz123456"; String password = "foo"; BoxItem.Info itemInfo = BoxItem.getSharedItem(api, sharedLink, password); ``` --- ## Untitled *Type: page* SDK Overview This guide covers the basics behind the various components of the Box Java SDK. It's also recommended that you take a look at… # SDK Overview This guide covers the basics behind the various components of the Box Java SDK. It's also recommended that you take a look at the documentation for the Box API. - [Authentication](#authentication) - [Resource Types](#resource-types) - [Requests and Responses](#requests-and-responses) - [Error Handling](#error-handling) - [As-User](#as-user) - [Suppressing Notifications](#suppressing-notifications) ## Authentication The first step in using the SDK is always authenticating and connecting to the API. The SDK does this through the [`BoxAPIConnection`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html) class. This class represents an authenticated connection to a specific version of the Box API. It is responsible for things such as: - Storing authentication information. - Automatically refreshing tokens. Configuring rate-limiting, number of retry attempts and other connection settings. You can also create more than one `BoxAPIConnection`. For example, you can have a connection for each user if your application supports multiple user accounts. See the [Authentication guide](https://developer.box.com/69a8a62320adb7087794d5bb03d56230/authentication.md) for details on how to create and use `BoxAPIConnection`. ## Resource Types Resources types are the classes you'll use the most. Things like `BoxFile`, `BoxFolder`, `BoxUser`, etc. are all resource types. A resource always has an ID and an associated API connection. Instantiating and using a resource type is simple: ``` // Print the name of the folder with ID "1234". BoxFolder folder = new BoxFolder(api, "1234") BoxFolder.Info info = folder.getInfo(); System.out.println(info.getName()); ``` A resource type will always have the same API connection as the type that instantiated it. For example, `creator` will have the same API connection that `folder` does. ``` BoxFolder folder = new BoxFolder(api, "1234") BoxFolder.Info info = folder.getInfo(); // This BoxUser has the same BoxAPIConnection as "folder". BoxUser creator = info.getCreatedBy(); ``` ## Requests and Responses All communication with Box's API is done through `BoxAPIRequest` and `BoxAPIResponse` (or their subclasses). These classes handle all the dirty work of setting appropriate headers, handling errors, and sending/receiving data. You generally won't need to use these classes directly, as the resource types are easier and cover most use-cases. However, these classes are extremely flexible and can be used if you need to make custom API calls. Here's an example using `BoxAPIRequest` and `BoxJSONResponse` that gets a list of items with some custom fields: ``` BoxAPIConnection api = new BoxAPIConnection("token"); URL url = new URL("https://api.box.com/2.0/folders/0/items?fields=name,created_at") BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); String json = response.getJSON(); ``` ## Error Handling Unless otherwise noted, the classes and methods in the SDK can throw an unchecked [`BoxAPIException`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIException.html) (unchecked meaning that the compiler won't force you to handle it) if an error occurs. This includes network errors or error statuses returned by the API. You should be aware of this when using the SDK so that your code can catch any errors that might happen when communicating with Box. If the error was due to a general networking error (for example, if the network connection was lost), the `BoxAPIException` will contain the underlying `IOException` as its cause. If the error was due to an API error, the `BoxAPIException` will contain the response code and body returned by the API. ``` BoxAPIConnection api = new BoxAPIConnection("token"); try { BoxFolder rootFolder = BoxFolder.getRootFolder(api); } catch (BoxAPIException e) { // Log the response code and the error message returned by the API. System.err.format("The API returned the error code: %d\n\n%s", e.getResponseCode(), e.getResponse()); } ``` ## As-User As-User is used by enterprise administrators to make API calls for their managed users. It can also be used by a Service Account to make API calls for managed users or app users. As-User state is set on the [`BoxAPIConnection`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html) instance with [`asUser(String userID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#asUser-java.lang.String-) and will be used for all requests made from that API connection going forward, until the state is removed with [`asSelf()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#asSelf--). ``` String userID = "12345"; String fileID = "98765"; BoxAPIConnection api = new BoxAPIConnection("ACCESS_TOKEN"); BoxFile file = new BoxFile(api, fileID); // API call made as user associated with access token BoxFile.Info info = file.getInfo(); api.asUser(userID); // API call made as user associated with userID info = file.getInfo(); api.asSelf(); // API call made as user associated with access token again BoxFile.Info info = file.getInfo(); ``` ## Suppressing Notifications If you are making administrative API calls (that is, your application has “Manage an Enterprise” scope, and the user signing in is a co-admin with the correct "Edit settings for your company" permission) then you can suppress both email and webhook notifications. This can be used, for example, for a virus-scanning tool to download copies of everyone’s files in an enterprise, without every collaborator on the file getting an email. All actions will still appear in users' updates feed and audit logs. **Note:** This functionality is only available for approved applications. To turn on notification suppression for all calls made through a [`BoxAPIConnection`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html) instance, call [`suppressNotifications()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#suppressNotifications--). To re-enable notifications on an API connection, call [`enableNotifications`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#enableNotifications--). ``` String userID = "12345"; String fileID = "98765"; OutputStream downloadStream; BoxAPIConnection api = new BoxAPIConnection("ACCESS_TOKEN"); BoxFile file = new BoxFile(api, fileID); // Notifications are sent by default downlaodStream = file.download(); api.suppressNotifications(); // Notifications are suppressed downlaodStream = file.download(); api.enableNotifications(); // Notifications are sent again downlaodStream = file.download(); ``` --- ## Untitled *Type: page* Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention… # Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. [Create Retention Policy](#create-retention-policy) - [Indefinite Retention Policies](#indefinite-policies) - [Finite Retention Policies](#finite-policies) - [Optional parameters](#optional-parameters) [Get Retention Policy](#get-retention-policy) [Update Retention Policy](#update-retention-policy) [Get Retention Policies](#get-retention-policies) [Get Retention Policy Assignments](#get-retention-policy-assignments) [Create Retention Policy Assignment](#create-retention-policy-assignment) [Get Retention Policy Assignment](#get-retention-policy-assignment) [Delete Retention Policy Assignment](#delete-retention-policy-assignment) [Get File Version Retention](#get-file-version-retention) [Get File Version Retentions](#get-file-version-retentions) [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) [Get File Versions Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) [Extend retention for a file](#extend-retention-for-a-file) ## Create Retention Policy ### Indefinite policies The static [`createIndefinitePolicy(BoxAPIConnection api, String name)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#createIndefinitePolicy-com.box.sdk.BoxAPIConnection-java.lang.String-) method will let you create a new indefinite retention policy with a specified name. ``` BoxRetentionPolicy.createIndefinitePolicy(api, name); ``` ### Finite policies The static [`BoxRetentionPolicy.createFinitePolicy(com.box.sdk.BoxAPIConnection, java.lang.String, int, com.box.sdk.BoxRetentionPolicy.BoxRetentionPolicyAction)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#createFinitePolicy-com.box.sdk.BoxAPIConnection-java.lang.String-int-com.box.sdk.BoxRetentionPolicy.BoxRetentionPolicyAction-) method will let you create a new finite retention policy with a specified name, amount of time to apply the retention policy (in days) and a disposition action. ``` BoxRetentionPolicy.createFinitePolicy(api, name, length, PermanentlyDelete); ``` ### Optional parameters Both finite and indefinite policies allow you to specify optional parameters using the [`RetentionPolicyParams`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/RetentionPolicyParams.html) object. ``` String notifiedUserID = "12345"; String description = "Policy to retain all reports"; RetentionPolicyParams optionalParams = new RetentionPolicyParams(); optionalParams.setCanOwnerExtendRetention(true); optionalParams.setAreOwnersNotified(true); optionalParams.setDescription(description); optionalParams.addCustomNotificationRecipient(notifiedUserID); // Create indefinite policy with optional parameters BoxRetentionPolicy.createIndefinitePolicy(api, "Retain Stuff Forever", optionalParams); // Create finite policy with optional parameters BoxRetentionPolicy.createFinitePolicy(api, "Keep One Year", 365, BoxRetentionPolicyAction.RemoveRetention, optionalParams); ``` ## Get Retention Policy Calling [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getInfo-java.lang.String...-) will return a [`BoxRetentionPolicy.Info'][retention-policy-info] object containing information about the retention policy. If necessary to retrieve limited set of fields, it is possible to specify them using the `fields` parameter. ``` // Get the policy name and status for a given retention policy BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); policy.getInfo("policy_name", "status"); ``` ## Update Retention Policy Updating a retention policy's information is done by calling [`updateInfo(BoxRetentionPolicy.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#updateInfo-com.box.sdk.BoxRetentionPolicy.Info-). ``` BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); BoxRetentionPolicy.Info policyInfo = policy.new Info(); policyInfo.setPolicyName("new policy name"); policy.updateInfo(policyInfo); ``` ## Get Retention Policies Calling the static [`getAll(BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...-) will return an iterable that will page through all of the retention policies. It is possible to specify filter for the name of retention policy, filter for the type of the policy, filter for the id of user, limit of items per single response and fields to retrieve by calling the static [`getAll(String name, String type, String userID, int limit, BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAll-java.lang.String-java.lang.String-java.lang.String-int-com.box.sdk.BoxAPIConnection-java.lang.String...-) method. ``` Iterable<BoxRetentionPolicy.Info> policies = BoxRetentionPolicy.getAll(api); for (BoxRetentionPolicy.Info policyInfo : policies) { // Do something with the retention policy. } ``` ## Get Retention Policy Assignments Calling [`getAllAssignments(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAllAssignments-java.lang.String...-) will return an iterable that will page through all of the assignments of the retention policy. It is possible to specify maximum number of items per single response and fields to retrieve by calling [`getAllAssignments(int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getAllAssignments-int-java.lang.String...-). If it is necessary to retrieve only assignments of certain type, you can call [`getFolderAssignments(int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getFolderAssignments-int-java.lang.String...-) or [`getEnterpriseAssignments(int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#getEnterpriseAssignments-int-java.lang.String...-). ``` BoxRetentionPolicy policy = new BoxRetentionPolicy(api, id); Iterable<BoxRetentionPolicyAssignment.Info> allAssignments = policy.getAllAssignments("assigned_by"); Iterable<BoxRetentionPolicyAssignment.Info> folderAssignments = policy.getFolderAssignments(50, "assigned_by"); Iterable<BoxRetentionPolicyAssignment.Info> enterpriseAssignments = policy.getEnterpriseAssignments(); for (BoxRetentionPolicyAssignments.Info assignmentInfo : allAssignments) { // Do something with the assignment. } for (BoxRetentionPolicyAssignments.Info assignmentInfo : folderAssignments) { // Do something with the assignment. } for (BoxRetentionPolicyAssignments.Info assignmentInfo : enterpriseAssignments) { // Do something with the assignment. } ``` ## Create Retention Policy Assignment To create new retention policy assignment call [`assignTo(BoxFolder target)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignTo-com.box.sdk.BoxFolder-) method to assign the policy to a specific folder, [`assignToEnterprise()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignToEnterprise--) to assign the retention policy to the entire enterprise, or [`assignToMetadataTemplate(String templateID, String startDateField, MetadataFieldFilter... filterFields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicy.html#assignToMetadataTemplate-java.lang.String-com.box.sdk.MetadataFieldFilter-) to assign the policy to items with a specific metadata template. ``` // Assign the policy to the entire enterprise BoxRetentionPolicy policy = new BoxRetentionPolicy(api, policyID); policy.assignToEnterprise(); // Assign the policy to a single folder BoxFolder folder = new BoxFolder(api, folderID); policy.assignTo(folderID); // Assign the policy to all items with metadata template String metadataTemplateID = "f0dce190-8106-43ca-9d67-7dce9b10a55e"; policy.assignToMetadataTemplate(metadataTemplateID); // You can also pass an optional `startDateField` parameter containing the ID of the metadata template's `date` field String dateFieldID = "fb523725-04b1-4502-b871-eac305274533"; policy.assignToMetadataTemplate(metadataTemplateID, dateFieldID); ``` ## Get Retention Policy Assignment Calling [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getInfo-java.lang.String...-) will return a [`BoxRetentionPolicyAssignment.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.Info.html) object containing information about the retention policy assignment. ``` BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, id); BoxRetentionPolicyAssignment.Info assignmentInfo = assignment.getInfo("assigned_to"); ``` ## Delete Retention Policy Assignment To delete Retention Policy Assignment call [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#delete()) method. ``` BoxRetentionPolicyAssignment assignment = new BoxRetentionPolicyAssignment(api, id); assignment.delete(); ``` ## Get File Version Retention Calling [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getInfo-java.lang.String...-) will return a [`BoxFileVersionRetention.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.Info.html) object containing information about the file version retention policy. ``` BoxFileVersionRetention policy = new BoxFileVersionRetention(api, id); BoxFileVersionRetention.Info policyInfo = policy.getInfo(); ``` ## Get File Version Retentions To get an iterable with all file version retentions for the current retention policy, call the static [`getAll(BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...-) method. It is possible to add filters to query passing a [`BoxFileVersionRetention.QueryFilter`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.QueryFilter.html) object as a parameter to [`getRetentions(BoxAPIConnection api, BoxFileVersionRetention.QueryFilter filter, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersionRetention.html#getRetentions-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxFileVersionRetention.QueryFilter-java.lang.String...-). ``` BoxFileVersionRetention.QueryFilter filter = new BoxFileVersionRetention.QueryFilter() .addFileID("0") .addFileVersionID("1") .addPolicyID("2") .addDispositionAction(BoxRetentionPolicy.ACTION_PERMANENTLY_DELETE) .addDispositionBefore(BoxDateFormat.parse("2016-09-15T13:15:35+0000")) .addDispositionAfter(BoxDateFormat.parse("2014-09-15T13:15:35+0000")); Iterable<BoxFileVersionRetention.Info> retentions = BoxFileVersionRetention.getRetentions(api, filter, "file", "applied_at"); for (BoxFileVersionRetention.Info retentionInfo : retentions) { // Do something with the file version retention. } ``` ## Get Files Under Retention For Assignment To get an iterable with all files under retention for assignment policy, call the [`getFilesUnderRetention(BoxAPIConnection api, int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getFilesUnderRetention-com.box.sdk.BoxAPIConnection-java.lang.String...-) method. This will return an interable with [`BoxFile.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.Info.html) objects containing information about the files. ``` BoxRetentionPolicyAssignment policyAssignment = new BoxRetentionPolicyAssignment(api, id); Iterable<BoxFile.Info> filesUnderRetention = policyAssignment.getFilesUnderRetention(); for (BoxFile.Info item : filesUnderRetention){ // Do something with the files under retention. } ``` ## Get File Versions Under Retention For Assignment To get an iterable with all file versions under retention for assignment policy, call the [`getFileVersionsUnderRetention(BoxAPIConnection api, int limit, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxRetentionPolicyAssignment.html#getFileVersionsUnderRetention-com.box.sdk.BoxAPIConnection-java.lang.String...-) method. This will return an interable with [`BoxFile.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.Info.html) objects containing information about the file. You can get version by calling [`BoxFile.Info#getVersion()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFileVersion.html). ``` BoxRetentionPolicyAssignment policyAssignment = new BoxRetentionPolicyAssignment(api, id); Iterable<BoxFile.Info> fileVersionsUnderRetention = policyAssignment.getFileVersionsUnderRetention(); for (BoxFile.Info file : fileVersionsUnderRetention){ BoxFileVersion version = file.getVersion(); // Do something with the file version under retention. } ``` ## Extend retention for a file Once you create retention policy and assign it to a folder all files and subfolders will have same policy applied. If you need to extend retention for some file you can change it's `dispositionAt` value: ``` BoxFile.Info info = someFile.getInfo(); // to read current disposition date coming from retention policy BoxFile.Info info = someFile.getInfo("disposition_at"); Date currentDispositionDate = info.getDispositionAt(); // calculate new disposition date Date dispositionAt = Date.from( LocalDateTime.ofInstant(currentDispositionDate.toInstant(), ZoneId.of("Z")) .plusDays(30) .toInstant(UTC) ); // to change disposition date on a file you need to updateInfo info.setDispositionAt(dispositionAt); uploadedFile.updateInfo(info); ``` --- ## Untitled *Type: page* Storage Policy Allows the enterprise admin to manage the Storage Policies for users in their enterprise. Used for an enterprise to decide… # Storage Policy Allows the enterprise admin to manage the Storage Policies for users in their enterprise. Used for an enterprise to decide storage location for users based on where they work/reside. - [Get Storage Policy](#get-storage-policy) - [Get List of Storage Policies](#get-list-of-storage-policies) - [Create New Assignment](#create-new-assignment) - [Get Assignment](#get-assignment) - [Get Assignment For Target](#get-assignment-for-target) - [Update Existing Assignment](#update-existing-assignment) - [Assign Storage Policy](#assign-storage-policy) - [Delete Assignment](#delete-assignment) ## Get Storage Policy Calling [`getInfo(String fields ...)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getInfo--) will return BoxStoragePolicy.Info object containing information about the storage policy. If necessary to retrieve limited set of fields. It is possible to specify them using param. ``` BoxStoragePolicy storagePolicy = new BoxStoragePolicy(api, id); BoxStoragePolicy.Info storagePolicyInfo = storagePolicy.getInfo(); ``` ## Get List of Storage Policies Calling the static [`getAll(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getAll--) will return an iterable that will page through all of the storage policies. It is possible to specify maximum number of items per response and fields to retrieve by calling the static [`getAll(BoxAPIConnection api, int limit, String fields ...)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicy.html#getAll-java.lang.String...-) method. ``` Iterable<BoxStoragePolicy.Info> storagePolicies = BoxStoragePolicy.getAll(api); for (BoxStoragePolicy.Info storagePolicyInfo : storagePolicies) { //Do something with the storage policy. } ``` ## Create New Assignment To create new storage policy assignment call [`create(BoxAPIConnection api, String policyID, String userID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-) method. ``` BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.create(api, policyID, userID); ``` ## Update Existing Assignment Updating a storage policy assignment information is done by calling [`updateInfo(BoxStoragePolicyAssignment.Info updatedInfo)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#updateInfo-com.box.sdk.BoxStoragePolicyAssignment.Info-). ``` BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api, "ASSIGNMENT_ID"); BoxStoragePolicyAssignment.Info assignmentInfo = storagePolicyAssignment.new Info(); assignmentInfo.setStoragePolicyID("NEW_STORAGE_POLICY_ID"); storagePolicyAssignment.updateInfo(assignmentInfo); ``` ## Get Assignment Calling [`getInfo(String fields ...)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#getInfo--) will return a BoxStoragePolicyAssignment.Info object containing information about the storage policy assignment. ``` BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment(api, id); BoxStoragePolicyAssignment.Info assignmentInfo = storagePolicyAssignment.getInfo(); ``` ## Get Assignment for Target Calling [`getAssignmentForTarget(BoxAPIConnection api, String resolvedForType, String resolvedForID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#getAssignmentForTarget-com.box.BoxAPIConnection-java.lang.String-java.lang.String-) will return a BoxStorageAssignment.Info object containing information about the storage policy assignment. ``` BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.getAssignmentForTarget(api, "user", "1234") ``` ## Assign Storage Policy Calling [`assign(BoxAPIConnection api, String storagePolicyID, String userID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssigbment.html#assign-com.box.BoxAPIConnection-java.lang.String-java.lang.String-) will check if this user already has storage policy assigned to them. If not then a new this user will be assigned the specified storage policy. ``` BoxStoragePolicyAssignment.Info assignmentInfo = BoxStoragePolicyAssignment.assign(api, "1234", "5678"); ``` ## Delete Assignment Calling [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxStoragePolicyAssignment.html#delete--) will remove the storage policy assignment from the user. ``` BoxStoragePolicyAssignment assignment = new BoxStoragePolicyAssignment(api, "dXNlcl8xMjM0"); assignment.delete(); ``` --- ## Untitled *Type: page* Collections Collections contain information about the items contained inside of them, including files and folders. The only collection… # Collections Collections contain information about the items contained inside of them, including files and folders. The only collection available currently is a “Favorites” collection. The contents of the collection are discovered in a similar way in which the contents of a folder are discovered. - [Get Collections](#get-collections) - [Get a Collection's Items](#get-a-collections-items) - [Add Items to a Collection](#add-items-to-a-collection) - [Remove Items from a Collection](#remove-items-from-a-collection) ## Get Collections Existing collections can be retrieved by calling the [`getAllCollections(BoxAPIConnection)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxCollection.html#getAllCollections-com.box.sdk.BoxAPIConnection-) method. Currently only "Favorites" collection is supported. ``` Iterable<BoxCollection.Info> collections = BoxCollection.getAllCollections(api); for (BoxCollection.Info collectionInfo : collections) { // Do something with the collection. } ``` ## Get a Collection's Items Every `BoxCollection` implements [`Iterable<BoxItem>`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxCollection.html#iterator--) which allows you to iterate over the collection's contents. The iterator automatically handles paging and will make additional network calls to load more data from Box when necessary. ``` BoxFolder folder = new BoxFolder(api, "id"); for (BoxItem.Info itemInfo : folder) { if (itemInfo instanceof BoxFile.Info) { BoxFile.Info fileInfo = (BoxFile.Info) itemInfo; // Do something with the file. } else if (itemInfo instanceof BoxFolder.Info) { BoxFolder.Info folderInfo = (BoxFolder.Info) itemInfo; // Do something with the folder. } } ``` ## Add Items to a Collection Add an item to a collection by calling [`setCollections(BoxCollection... collections)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#setCollections-com.box.sdk.BoxCollection...-) on any `BoxItem`. Note that this method will overwrite all collections that the item belongs to. ``` BoxCollection favorites = null; for (BoxCollection.Info info : BoxCollection.getAllCollections(api)) { if (info.getCollectionType().equals("favorites")) { favorites = info.getResource(); break; } } BoxFile file = new BoxFile(api, "id"); file.setCollections(favorites); ``` ## Remove Items from a Collection Remove an item from a collection by calling [`setCollections(BoxCollection... collections)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#setCollections-com.box.sdk.BoxCollection...-) on any `BoxItem` and exclude the collection to wish to remove it from. ``` BoxFile file = new BoxFile(api, "id"); BoxFile.Info info = file.getInfo("collections"); ArrayList<BoxCollection> collections = new ArrayList<BoxCollection>(); for (BoxCollection.Info info : info.getCollections(api)) { // Include every existing collection except for favorites to remove the file // from the favorites collection. if (!info.getCollectionType().equals("favorites")) { collections.add(info.getResource()); } } file.setCollections(collections.toArray()); ``` --- ## Untitled *Type: page* Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files… # Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files and can be sent to one or more Box Sign Request Signers. - [Create Sign Request](#create-sign-request) - [Get all Sign Requests](#get-all-sign-requests) - [Get Sign Request by ID](#get-sign-request-by-id) - [Cancel Sign Request](#cancel-sign-request) - [Resend Sign Request](#resend-sign-request) ## Create Sign Request The [`createSignRequest(BoxAPIConnection api, List<BoxSignRequestSigner> signers, List<BoxSignRequestFile> files, String parentFolderId)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#createSignRequest-com.box.sdk.BoxAPIConnection-java.util.List-java.util.List-java.lang.String-) method will create a Sign Request. You need to provide 1 to 10 files (from which the signing document will be created) and at least one signer to receive the Sign Request. You can use [`BoxSignRequestFile`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestFile.html) and [`BoxSignRequestSigner`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestSigner.html) classes to provide the necessary data. ``` List<BoxSignRequestFile> files = new ArrayList<BoxSignRequestFile>(); BoxSignRequestFile file = new BoxSignRequestFile("12345"); files.add(file); // you can also use specific version of the file BoxFile file = new BoxFile(api, "12345"); List<BoxFileVersion> versions = file.getVersions(); BoxFileVersion firstVersion = versions.get(0); BoxSignRequestFile file = new BoxSignRequestFile(firstVersion.getFileID(), firstVersion.getVersionID()); List<BoxSignRequestSigner> signers = new ArrayList<BoxSignRequestSigner>(); BoxSignRequestSigner newSigner = new BoxSignRequestSigner("signer@mail.com"); signers.add(newSigner); String destinationParentFolderId = "55555"; BoxSignRequest.Info signRequestInfo = BoxSignRequest.createSignRequest(api, files, signers, destinationParentFolderId); ``` [`createSignRequest`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#createSignRequest-com.box.sdk.BoxAPIConnection-java.util.List-java.util.List-java.lang.String-) allows you to specify optional parameters using the [`BoxSignRequestCreateParams`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequestCreateParams.html) object. ``` List<BoxSignRequestFile> files = new ArrayList<BoxSignRequestFile>(); BoxSignRequestFile file = new BoxSignRequestFile("12345"); files.add(file); List<BoxSignRequestSigner> signers = new ArrayList<BoxSignRequestSigner>(); BoxSignRequestSigner newSigner = new BoxSignRequestSigner("signer@mail.com"); signers.add(newSigner); String destinationParentFolderId = "55555"; BoxSignRequestCreateParams createParams = new BoxSignRequestCreateParams() .setIsDocumentPreparationNeeded(true); BoxSignRequest.Info signRequestInfo = BoxSignRequest.createSignRequest(api, files, signers, destinationParentFolderId, createParams); ``` If you set `isDocumentPreparationNeeded` flag to true, you need to visit `prepareUrl` before the Sign Request will be sent. For more information on `isDocumentPreparationNeeded` and the other `BoxSignRequestCreateParams` available, please refer to the [developer documentation](https://developer.box.com/guides/box-sign/). ## Get All Sign Requests Calling the static [`getAll(BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getAll-com.box.sdk.BoxAPIConnection-java.lang.String...-) will return an iterable that will page through all the Sign Requests. The static [`getAll(int limit, BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getAll-int-com.box.sdk.BoxAPIConnection-java.lang.String...-) method offers `limit` and `fields` parameters. The `limit` parameter specifies the maximum number of items to be returned in a single response. The `fields` parameter is used to specify what additional properties should be returned on the `BoxSignRequest.Info` objects. For more information on what `fields` are available, please refer to the [developer documentation](https://developer.box.com/guides/box-sign/). ``` Iterable<BoxSignRequest.Info> signRequests = BoxSignRequest.getAll(api); for (BoxSignRequest.Info signRequestInfo : signRequests) { // Do something with each `signRequestInfo`. } ``` ## Get Sign Request by ID Calling [`getInfo(String fields ...)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#getInfo-java.lang.String...-) will return a [`BoxSignRequest.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.Info.html) object containing information about the Sign Request. The `fields` parameter is used to specify what additional properties should be returned on the `BoxSignRequest.Info` objects. ``` BoxSignRequest signRequest = new BoxSignRequest(api, id); BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); //using `fields` parameter BoxSignRequest.Info signRequestInfoWithFields = signRequest.getInfo("status") ``` ## Cancel Sign Request Calling [`cancel()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#cancel--) will cancel a created Sign Request. ``` BoxSignRequest signRequest = new BoxSignRequest(api, id); BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); signRequestInfo.cancel(); ``` ## Resend Sign Request Calling [`resend()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignRequest.html#resend--) will resend a Sign Request to all signers that have not signed it yet. There is an 10-minute cooling-off period between re-sending reminder emails. If this method is called during the cooling-off period, a [`BoxAPIException`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIException.html) will be thrown. ``` BoxSignRequest signRequest = new BoxSignRequest(api, id); BoxSignRequest.Info signRequestInfo = signRequest.getInfo(); signRequestInfo.resend(); ``` --- ## Untitled *Type: page* Tasks Task objects represent a user-created task on a file. Get a Task's Information Get the Tasks on a File Add a Task to a File Update a… # Tasks Task objects represent a user-created task on a file. - [Get a Task's Information](#get-a-tasks-information) - [Get the Tasks on a File](#get-the-tasks-on-a-file) - [Add a Task to a File](#add-a-task-to-a-file) - [Update a Task's Information](#update-a-tasks-information) - [Delete a Task](#delete-a-task) - [Get a Task's Assignments](#get-a-tasks-assignments) - [Get Information About a Task Assignment](#get-information-about-a-task-assignment) - [Add a Task Assignment](#add-a-task-assignment) - [Delete a Task Assignment](#delete-a-task-assignment) - [Update a Task Assignment](#update-a-task-assignment) ## Get a Task's Information Calling [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#getInfo--) on a task returns a snapshot of the task's info. ``` BoxTask task = new BoxTask(api, "id"); BoxTask.Info info = task.getInfo(); ``` ## Get the Tasks on a File You can get all of the tasks on a file by calling the [`getTasks()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getTasks--) method. ``` BoxFile file = new BoxFile(api, "id"); List<BoxTask.Info> tasks = file.getTasks(); ``` ## Add a Task to a File A task can be added to a file with the [`addTask(BoxTask.Action action, String message, Date dueAt)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#addTask-com.box.sdk.BoxTask.Action-java.lang.String-java.util.Date-) method. ``` BoxFile file = new BoxFile(api, "id"); Date dueAt = new Date(); file.addTask(BoxTask.Action.REVIEW, "Please review this file.", dueAt); ``` ## Update a Task's Information The message of a task can be changed with the [`updateInfo(BoxTask.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#updateInfo-com.box.sdk.BoxTask.Info-) method. ``` BoxTask task = new BoxTask(api, "id"); BoxTask.Info info = task.new Info(); info.setMessage("An edited message."); task.updateInfo(info); ``` ## Delete a Task A task can be deleted with the [`delete()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#delete--) method. ``` BoxTask task = new BoxTask(api, "id"); task.delete(); ``` ## Get a Task's Assignments Retreive a tasks assignments with the [`getAssignments()`](https://box.github.io/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#getAssignments--) method. ``` BoxTask task = new BoxTask(api, "id"); task.getAssignments(); ``` ## Get Information About a Task Assignment To look up information about a task assignment by its ID, instantiate the [`BoxTaskAssignment`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html) object with the ID, and call [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#getInfo--) on the assignment. To retrieve only specific fields on the task assignment, call [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#getInfo-java.lang.String...-) with the fields to retrieve. ``` String assignmentID = "4256974"; BoxTaskAssignment.Info assignmentInfo = new BoxTaskAssignment(api, assignmentID).getInfo(); ``` ## Add a Task Assignment An assignment can be added to a task with the [`addAssignment(BoxUser assignee)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTask.html#addAssignment-com.box.sdk.BoxUser-) method. ``` BoxUser user = new BoxUser(api, "user-id") BoxTask task = new BoxTask(api, "id"); task.addAssignment(user); ``` ## Delete a Task Assignment An assignment can be deleted from a task with the [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#delete--) method on a [`BoxTaskAssignment`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html) instance. ``` BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, "id"); taskAssignment.delete(); ``` ## Update a Task Assignment A task assignment can be updated with the [`updateInfo(BoxTask.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTaskAssignment.html#updateInfo-com.box.sdk.BoxTaskAssignment.Info-) method. Updating the resolution state: ``` String assignmentID = "12345"; BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, assignmentID); BoxTaskAssignment.Info info = taskAssignment.getInfo(); info.setResolutionState(BoxTaskAssignment.ResolutionState.APPROVED); taskAssignment.updateInfo(info); ``` Updating the message: ``` String assignmentID = "12345"; BoxTaskAssignment taskAssignment = new BoxTaskAssignment(api, assignmentID); BoxTaskAssignment.Info info = taskAssignment.getInfo(); info.setMessage("Please review the meeting notes"); taskAssignment.updateInfo(info); ``` --- ## Untitled *Type: page* Sign Templates Box Sign enables you to create templates so you can automatically add the same fields and formatting to requests for… # Sign Templates Box Sign enables you to create templates so you can automatically add the same fields and formatting to requests for signature. With templates, you don't need to repetitively add the same fields to each request every time you send a new document for signature. Making and testing a template takes a few minutes, but when done it makes working with Box Sign easier and faster. - [Get all Sign Templates](#get-all-sign-templates) - [Get Sign Template by ID](#get-sign-template-by-id) ## Get All Sign Templates Calling the static [`getAll(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getAll-com.box.sdk.BoxAPIConnection-) will return an iterable that will page through all the Sign Templates. The static [`getAll(BoxAPIConnection api, int limit)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getAll-com.box.sdk.BoxAPIConnection-int-) method offers `limit` parameter. The `limit` parameter specifies the maximum number of items to be returned in a single response. ``` Iterable<BoxSignTemplate.Info> signTemplates = BoxSignTemplate.getAll(api); for (BoxSignTemplate.Info signTemplateInfo : signTemplates) { // Do something with each `signTemplateInfo`. } ``` ## Get Sign Template by ID Calling [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.html#getInfo-) will return a [`BoxSignTemplate.Info`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxSignTemplate.Info.html) object containing information about the Sign Template. ``` BoxSignTemplate signTemplate = new BoxSignTemplate(api, id); BoxSignTemplate.Info signTemplateInfo = signTemplate.getInfo(); ``` --- ## Untitled *Type: page* Terms of Service Terms of Service allows Box Admins to configure a custom Terms of Service for end users to accept/re-accept/decline for… # Terms of Service Terms of Service allows Box Admins to configure a custom Terms of Service for end users to accept/re-accept/decline for platform applications [Terms of Service](#terms-of-service) - [Create a Terms of Service](#create-a-terms-of-service) - [Edit a Terms of Service](#edit-a-terms-of-service) - [Get a Terms of Service](#get-a-terms-of-service) - [Get All Terms of Services](#get-all-terms-of-services) - [Accept or Decline a Terms of Service for New User](#accept-or-decline-a-terms-of-service-for-new-user) - [Accept or Decline a Terms of Service for Existing User](#accept-or-decline-a-terms-of-service-for-existing-user) - [Get User Status on a Terms of Service](#get-user-status-on-a-terms-of-service) ## Create a Terms of Service A terms of service can be created in an enterprise. Please note that only two can be created. One external and one managed. If a terms of service already exists please use the update call to change the current terms of service. You can create a custom terms of service by calling [`create(BoxAPIConnection api, BoxTermsOfService.TermsOfServiceStatus status, BoxTermsOfService.TermsOfServiceType type, String text)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#create-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxTermsOfService.TermsOfServiceStatus-com.box.sdk.BoxTermsOfService.TermsOfServiceType-java.lang.String-). ``` BoxTermsOfService.Info newTOS = BoxTermsOfService.create( api, BoxTermsOfService.TermsOfServiceStatus.ENABLED, BoxTermsOfService.TermsOfServiceType.EXTERNAL, "Terms of Service..." ); ``` ## Edit a Terms of Service You can update a terms of service status and text after you have created them by calling [`updateInfo(BoxTermsOfService.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#updateInfo-com.box.sdk.BoxTermsOfService.Info-) ``` BoxTermsOfService termsOfService = new BoxTermsOfService(api, "tos-id"); BoxTermsOfService.Info termsOfServiceInfo = termsOfService.new Info(); termsOfServiceInfo.setStatus(BoxTermsOfService.TermsOfServiceStatus.DISABLED); termsOfServiceInfo.setText("New Terms of Service Text"); termsOfService.updateInfo(termsOfService); ``` ## Get a Terms of Service You can retrieve a terms of service by providing the ID and calling [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getInfo--). ``` BoxTermsOfService termsOfService = new BoxTermsOfService(api, "tos-id"); BoxTermsOfService.Info tosInfo = termsOfService.getInfo(); ``` ## Get All Terms of Services You can also retrieve all terms of service in your enterprise by calling [`getAllTermsOfServices(BoxAPIConnection api)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getAllTermsOfServices-com.box.sdk.BoxAPIConnection-). This will return an iterable that will page through all of the enterprises terms of services. ``` List<BoxTermsOfService.Info> termsOfServices = BoxTermsOfService.getAllTermsOfServices(api); for(BoxTermsOfService.Info termsOfServiceInfo : termsOfServices){ // Do something with the terms of service. } ``` You can also filter by managed or external terms of service by calling [`getAllTermsOfServices(BoxAPIConnection api, BoxTermsOfService.TermsOfServiceType type)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfService.html#getAllTermsOfServices-com.box.sdk.BoxAPIConnection-com.box.sdk.BoxTermsOfService.TermsOfServiceType-). ## Accept or Decline a Terms of Service for New User For new users you can accept or decline a terms of service by calling [`create(BoxAPIConnection api, String tosID, Boolean accepted, String userID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#create-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.Boolean-java.lang.String-) ``` BoxTermsOfService.Info newUserStatus = BoxTermsOfServiceUserStatus.create(api, "tos-id", true, "user-id"); ``` You can only create a new user status on a terms of service if the user has never accepted/declined a terms of service. If they have then you will need to make the update call. ## Accept or Decline a Terms of Service for Existing User For an existing user you can accept or decline a terms of service by calling [`updateInfo(BoxTermsOfService.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#updateInfo-com.box.sdk.BoxTermsOfServiceUserStatus.Info-). ``` BoxTermsOfServiceUserStatus tosUserStatus = new BoxTermsOfServiceUserStatus(api, "tos-user-status-id"); BoxTermOfServiceUserStatus.Info tosUserStatusInfo = tosUserStatus.new Info(); tosUserStatusInfo.setStatus(newStatus); tosUserStatus.updateInfo(tosUSerStatusInfo); ``` ## Get User Status on a Terms of Service You can retrieve the terms of service status for a user by calling [`getInfo(BoxAPIConnection api, String tosID, String userID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#getInfo-com.box.sdk.BoxAPIConnection-java.lang.String-) ``` List<BoxTermsOfServiceUserStatus.Info> tosUserStatusInfo = BoxTermsOfServiceUserStatus.getInfo(api, "tos-id", "user-id"); for(BoxTermsOfServiceUserStatus.Info info : toUserStatusInfo){ // Do something with the user status on terms of service. } ``` Alternatively you can get the user status by the ID of the terms of service by calling [`getInfo(BoxAPIConnection api, String tosID)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTermsOfServiceUserStatus.html#getInfo-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-). ``` List<BoxTermsOfServiceUserStatus.Info> tosUserStatusInfo = BoxTermsOfServiceUserStatus.getInfo(api, "tos-id"); for(BoxTermsOfServiceUserStatus.Info info : toUserStatusInfo){ // Do something with the user status on terms of service. } ``` --- ## Untitled *Type: page* Upgrading to v4 v4 of the Box Java SDK introduces a lot of new design changes. Since this is a major version bump, there will be breaking… # Upgrading to v4 v4 of the Box Java SDK introduces a lot of new design changes. Since this is a major version bump, there will be breaking changes that will require you to update your application. ## What's New ### Features **Automatic rate-limiting and error retry.** API requests will automatically be retried with exponential back off if a 500+ (server error) or 429 (too many requests) response code is returned. **OAuth redesign.** OAuth should now be easier to use, allowing you to authenticate with an access token, auth code, or developer token. **New EventStream class.** This class makes it easier to listen for API events by allowing you to specify listeners that will be notified when an event occurs. **New classes for making custom API requests.** The BoxAPIRequest and BoxAPIResponse classes make it easy to send custom requests to the API while still having OAuth, rate-limiting back off, error handling and response parsing automatically handled. ### General Improvements **Simpler and more intuitive design.** We aimed to make the overall design of the SDK more intuitive and easier to learn. **More documentation and examples.** The Javadocs have been completely overhauled and there are new guides explaining how to accomplish common tasks with the SDK. **SDK size has been dramatically decreased.** Many of the SDK's dependencies have been removed and its overall size has been reduced - making it more suitable for mobile apps. **Easier integration.** With a single build process, it's easier and simpler to get the SDK building with other applications. It also follows the standard directory layout, making it easier to import into various IDEs or build systems. ## Authentication Authentication has been simplified by allowing you to provide tokens or auth codes directly. All authentication is now done by creating a `BoxAPIConnection` in order to establish an authenticated connection with the API. Connect to the API using a developer token: ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); ``` Connect to the API using access and refresh tokens: ``` BoxAPIConnection api = new BoxAPIConnection("CLIENT-ID", "CLIENT-SECRET", "ACCESS-TOKEN", "REFRESH-TOKEN"); ``` Connect to the API using an auth code: ``` BoxAPIConnection api = new BoxAPIConnection("CLIENT-ID", "CLIENT-SECRET", "AUTH-CODE"); ``` More information on authentication can be found [here](https://developer.box.com/69a8a62320adb7087794d5bb03d56230/authentication.md). ## New Resource Types Previously, interaction with the API was done through managers and request objects. For example: ``` BoxClient client = new BoxClient(...); IBoxFilesManager filesManager = boxClient.getFilesManager(); BoxDefaultRequestObject requestObj = new BoxDefaultRequestObject(); requestObj.getRequestExtras().addField(BoxFile.FIELD_SHA1); requestObj.getRequestExtras().addField(BoxFile.FIELD_DESCRIPTION); BoxFile file = filesManager.getFile(fileId, requestObj); ``` These objects have been removed and interacting with the API has been simplified. Resources can now be manipulated directly without needing to use managers or build custom requests. ``` BoxAPIConnection api = new BoxAPIConnection(...); BoxFile file = new BoxFile(api, fileID); BoxFile.Info fileInfo = file.getInfo("sha1", "description"); ``` More information on resource types can be found [here](resource-types.md). ## Custom Requests The SDK now provides request and response objects that allow you to easily make custom requests to the Box API. These objects will handle authentication, automatic retry, rate-limiting and errors out-of-the-box, giving you the flexibility to make your own API requests without having to worry about handling these things yourself. ``` BoxAPIConnection api = new BoxAPIConnection(...); URL url = new URL("https://api.box.com/2.0/folders/0/items?fields=name,created_at") BoxJSONRequest request = new BoxJSONRequest(api, url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); String json = response.getJSON(); ``` More information on resource types can be found [here](https://developer.box.com/7b374e99189519aca65b064deffbf92d/overview.md). --- ## Untitled *Type: page* Trash Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is moved to the Trash… # Trash Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is moved to the Trash. The Trash allows you to recover files and folders that have been deleted. By default, items in the Trash will be purged after 30 days. - [Get Trashed Items](#get-trashed-items) - [Get Trashed File Information](#get-trashed-file-information) - [Get Trashed Folder Information](#get-trashed-folder-information) - [Permanently Delete File From Trash](#permanently-delete-file-from-trash) - [Permanently Delete Folder From Trash](#permanently-delete-folder-from-trash) - [Restore a File from the Trash](#restore-a-file-from-the-trash) - [Restore a Folder from the Trash](#restore-a-folder-from-the-trash) ## Get Trashed Items The [`BoxTrash`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html) implements `Iterable<BoxItem.Info>`, so to get the collection of items currently in the trash, simply iterate over it. ``` BoxTrash trash = new BoxTrash(api); for (BoxItem.Info itemInfo : trash) { // Process the item } ``` Alternatively you can specify sort order, limit, use marker based pagination or specify which fields you want to extract with [`BoxTrash#items`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#items-com.box.sdk.SortParameters-com.box.sdk.PagingParameters-java.lang.String...-). To use sorting you have to use offset based pagination: ``` BoxTrash trash = new BoxTrash(api); Iterable<BoxItem.Info> trashEntries = trash.items( SortParameters.ascending("name"), PagingParameters.offset(0, 500) ); for (BoxItem.Info trashEntry : trashEntries) { // Process the item } ``` If you have a lot of items in trash and offset value is in tens of thousands it is better to use marker based pagination. However, marker based pagination cannot be used with sorting. To disable sorting use `SortParameters.none()`: ``` BoxTrash trash = new BoxTrash(api); Iterable<BoxItem.Info> trashEntries = trash.items( SortParameters.none(), PagingParameters.marker(500) ); for (BoxItem.Info trashEntry : trashEntries) { // Process the item } ``` ## Get Trashed File Information Ordinarily, trying to call [`getInfo()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getInfo-java.lang.String...-) on a file that is in the trash will return a 404 error. To get the information of a file in the trash, you must instead call [`BoxTrash#getFileInfo(String fileID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFileInfo-java.lang.String-) with the ID of the trashed file. You can optionally pass a specific list of fields to retrieve to [`getFileInfo(String fileID, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFileInfo-java.lang.String-java.lang.String...-), which will return only the specified fields to reduce payload size. ``` String fileID = "9873459"; BoxTrash trash = new BoxTrash(api); BoxFile.Info fileInfo = trash.getFileInfo(fileID); ``` ## Get Trashed Folder Information Ordinarily, trying to call [`getInfo()`][folder-get-info] on a folder that is in the trash will return a 404 error. To get the information of a folder in the trash, you must instead call [`BoxTrash#getFolderInfo(String fileID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFolderInfo-java.lang.String-) with the ID of the trashed folder. You can optionally pass a specific list of fields to retrieve to [`getFileInfo(String folderID, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#getFolderInfo-java.lang.String-java.lang.String...-), which will return only the specified fields to reduce payload size. ``` String folderID = "2345343"; BoxTrash trash = new BoxTrash(api); BoxFolder.Info folderInfo = trash.getFolderInfo(folderInfo); ``` ## Permanently Delete File From Trash To delete a file from the trash, call [`BoxTrash#deleteFile(String fileID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#deleteFile-java.lang.String-) with the ID of the file to delete. **Note:** This will permanently delete the file, and cannot be undone. ``` String fileID = "87398"; BoxTrash trash = new BoxTrash(api); trash.deleteFile(fileID); ``` ## Permanently Delete Folder From Trash To delete a folder from the trash, call [`BoxTrash#deleteFolder(String fileID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#deleteFolder-java.lang.String-) with the ID of the folder to delete. **Note:** This will permanently delete the folder, and cannot be undone. ``` String folder = "123456"; BoxTrash trash = new BoxTrash(api); trash.deleteFolder(folderID); ``` ## Restore a File from the Trash To restore a file from the trash, effectively undeleting it, call [`BoxTrash#restoreFile(String fileID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFile-java.lang.String-) with the ID of the file. To avoid scenarios where the parent folder that previously contained the file is no longer available, the user does not have permission to create items in that folder, or that folder has an item with the same name as the one being restored; you can pass a new parent folder ID and/or file name to [`BoxTrash#restoreFile(String fileID, String newName, String newParentID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFile-java.lang.String-java.lang.String-java.lang.String-). The new name and parent will only be used if a conflict is encountered while trying to restore the file to its original location. ``` String fileID = "125367"; String newName = "Presentation 2018 ORIGINAL.pptx"; String newParentID = "98765"; BoxTrash trash = new BoxTrash(api); // Avoid conflicts at the original location trash.restoreFile(fileID, newName, newParentID); ``` ## Restore a Folder from the Trash To restore a folder from the trash, effectively undeleting it, call [`BoxTrash#restoreFolder(String folderID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFolder-java.lang.String-) with the ID of the folder. To avoid scenarios where the parent folder that previously contained the folder to be restored is no longer available, the user does not have permission to create items in that folder, or that folder has an item with the same name as the one being restored; you can pass a new parent folder ID and/or folder name to [`BoxTrash#restoreFolder(String folderID, String newName, String newParentID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxTrash.html#restoreFolder-java.lang.String-java.lang.String-java.lang.String-). The new name and parent will only be used if a conflict is encountered while trying to restore the folder to its original location. ``` String folderID = "125367"; String newName = "My Documents ORIGINAL"; String newParentID = "98765"; BoxTrash trash = new BoxTrash(api); // Avoid conflicts at the original location trash.restoreFolder(folderID, newName, newParentID); ``` --- ## Untitled *Type: page* Watermarking The ability to watermark files and folders is represented as a sub-resource on the Files and Folders resources, respectively… # Watermarking The ability to watermark files and folders is represented as a sub-resource on the Files and Folders resources, respectively. You can think of the sub-resource as a "label" marking whether the file or folder is watermarked or not. If you apply a watermark label to a folder, then all files inside of it will be protected by the watermark (e.g. previews will be watermarked). However, those files' watermark sub-resource is independent from the folder that got watermarked. This allows you to watermark files and folders independently. - [Get Watermark on File](#get-watermark-on-file) - [Apply Watermark on File](#apply-watermark-on-file) - [Remove Watermark on File](#remove-watermark-on-file) - [Get Watermark on Folder](#get-watermark-on-folder) - [Apply Watermark on Folder](#apply-watermark-on-folder) - [Remove Watermark on Folder](#remove-watermark-on-folder) ## Get Watermark on File Calling [`getWatermark(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getWatermark-java.lang.String...-) will return a BoxWatermark object containing information about the watermark associated for this file. If the file does not have a watermark applied on it, a 404 Not Found will be returned. ``` BoxFile file = new BoxFile(api, id); BoxWatermark watermark = file.getWatermark(); ``` ## Apply Watermark on File To apply watermark on file, call [`applyWatermark()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#applyWatermark--) method. While the endpoint accepts a JSON body describing the watermark to apply, custom watermarks are not supported yet. The method will return a BoxWatermark object containing information about the watermark applied on this file. ``` BoxFile file = new BoxFile(api, id); file.applyWatermark(); ``` ## Remove Watermark on File A watermark can be removed by calling the [`removeWatermark()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#removeWatermark--) method. If the file did not have a watermark applied on it, a 404 Not Found will be returned by API. ``` BoxFile file = new BoxFile(api, id); file.removeWatermark(); ``` ## Get Watermark on Folder Calling [`getWatermark(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#getWatermark-java.lang.String...-) will return a BoxWatermark object containing information about the watermark associated for this folder. If the folder does not have a watermark applied on it, a 404 Not Found will be returned. ``` BoxFolder folder = new BoxFolder(api, id); BoxWatermark watermark = folder.getWatermark(); ``` ## Apply Watermark on Folder To apply watermark on folder, call [`applyWatermark()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#applyWatermark--) method. The method will return a BoxWatermark object containing information about the watermark applied on this folder. ``` BoxFolder folder = new BoxFolder(api, id); fodler.applyWatermark(); ``` ## Remove Watermark on Folder A watermark can be removed by calling the [`removeWatermark()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#removeWatermark--) method. If the folder did not have a watermark applied on it, a 404 Not Found will be returned by API. ``` BoxFolder folder = new BoxFolder(api, id); folder.removeWatermark(); ``` --- ## Untitled *Type: page* Webhooks Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your… # Webhooks Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your application when they occur. A webhook notifies your application by sending HTTP requests to a URL of your choosing. - [Get a Webhook](#get-a-webhook) - [Get All Webhooks](#get-all-webhooks) - [Create a Webhook](#create-a-webhook) - [Delete a Webhook](#delete-a-webhook) - [Update a Webhook](#update-a-webhook) - [Verify a Webhook Message](#verify-a-webhook-message) ## Get a Webhook A webhook infocan be retrieved by calling the [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#getInfo-java.lang.String...-) method. ``` BoxWebHook webhook = new BoxWebHook(api, id); BoxWebHook.Info info = webhook.getInfo(); ``` ## Get All Webhooks Calling the static [`all(BoxAPIConnection api, String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#all-com.box.sdk.BoxAPIConnection-java.lang.String...-) will return an iterable that will page through all defined webhooks for the requesting application and user. ``` Iterable<BoxWebHook.Info> webhooks = BoxWebHook.all(api); for (BoxWebHook.Info webhookInfo: webhooks) { // Do something with the webhook. } ``` ## Create a Webhook The static [`create(BoxResource targetItem, URL callbackURL, BoxWebHook.Trigger... triggerEvents)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#create-com.box.sdk.BoxResource-java.net.URL-com.box.sdk.BoxWebHook.Trigger...-) method will let you create a new webhook for a specified target object. ``` // Listen for preview events for a file BoxFile file = new BoxFile(api, id); BoxWebHook.Info webhookInfo = BoxWebHook.create(file, url, BoxWebHook.Trigger.FILE.PREVIEWED); ``` ``` // Listen for file upload events in the specified folder BoxFolder folder = new BoxFolder(api, id); BoxWebHook.Info webhookInfo = BoxWebHook.create(folder, url, BoxWebHook.Trigger.FILE_UPLOADED); ``` ## Delete a Webhook A webhook can be deleted by calling the [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#delete--) method. ``` BoxWebHook webhook = new BoxWebHook(api, id); webhook.delete(); ``` ## Update a Webhook A webhook can be updated by calling the [`update(BoxWebHook.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHook.html#updateInfo-com.box.sdk.BoxWebHook.Info-) method. ``` BoxWebHook webhook = new BoxWebHook(api, id); BoxWebHook.Info info = webhook.new Info(); info.setAddress(url); webhook.update(info); ``` ## Verify a Webhook Message When you receive a webhook message from Box, you should validate that it actually came from Box by calling [`BoxWebHookSignatureVerifier#verify(String sigVersion, String sigAlgorithm, String primarySignature, String secondarySignature, String payload, String deliveryTimestamp)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebHookSignatureVerifier.html#verify-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-java.lang.String-) **Note:** It is recommended to ensure that your application and verifier use both a primary and secondary key to ensure that these keys can be safely rotated. ``` // Webhook message contents are shown for demonstration purposes // Normally these would come from your HTTP handler // Webhook message HTTP body String messagePayload = "{" + "\"type\":\"webhook_event"," + "\"webhook\":{" + "\"id\":\"1234567890\"" + "}," + "\"trigger\":\"FILE.UPLOADED\"," + "\"source\":{" + "\"id\":\"1234567890\"," + "\"type\":\"file\"," + "\"name\":\"Test.txt\"" + "}}"; // Webhook message HTTP headers Map<String, String> messageHeaders = new HashMap<String, String>(); headers.put("BOX-DELIVERY-ID", "f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f"); headers.put("BOX-DELIVERY-TIMESTAMP", "2020-01-01T00:00:00-07:00"); headers.put("BOX-SIGNATURE-ALGORITHM", "HmacSHA256"); headers.put("BOX-SIGNATURE-PRIMARY", "6TfeAW3A1PASkgboxxA5yqHNKOwFyMWuEXny/FPD5hI="); headers.put("BOX-SIGNATURE-SECONDARY", "v+1CD1Jdo3muIcbpv5lxxgPglOqMfsNHPV899xWYydo="); headers.put("BOX-SIGNATURE-VERSION", "1"); // Your application's webhook keys, obtained from the Box Developer Console String primaryKey = "4py2I9eSFb0ezXH5iPeQRcFK1LRLCdip"; String secondaryKey = "Aq5EEEjAu4ssbz8n9UMu7EerI0LKj2TL"; BoxWebHookSignatureVerifier verifier = new BoxWebHookSignatureVerifier(primaryKey, secondaryKey); boolean isValidMessage = verifier.verify( headers.get("BOX-SIGNATURE-VERSION"), headers.get("BOX-SIGNATURE-ALGORITHM"), headers.get("BOX-SIGNATURE-PRIMARY"), headers.get("BOX-SIGNATURE-SECONDARY"), messagePayload, headers.get("BOX-DELIVERY-TIMESTAMP") ); if (isValidMessage) { // Message is valid, handle it } else { // Message is invalid, reject it } ``` --- ## Untitled *Type: page* Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link… # Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects. - [Create Web Link](#create-web-link) - [Get Web Link](#get-web-link) - [Update Web Link](#update-web-link) - [Delete Web Link](#delete-web-link) - [Create Shared Link](#create-shared-link) - [Remove Shared Link](#remove-shared-link) ## Create Web Link Calling [`BoxFolder.createWebLink(String name, URL url, String description)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createWebLink-java.lang.String-java.net.URL-java.lang.String-) will let you create a new web link with a specified name and description. ``` BoxFolder folder = new BoxFolder(api, id); URL url = new URL("https://www.example.com"); folder.createWebLink("Link to Example", url, "This goes to an example page"); ``` Name and description params are optional, so it is possible to create web link with only one of them or with URL only: [`BoxFolder.createWebLink(URL url)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#createWebLink-java.net.URL-) ``` BoxFolder folder = new BoxFolder(api, id); URL url = new URL("https://www.example.com"); BoxWebLink.Info webLinkInfo = folder.createWebLink(url); ``` ## Get Web Link A web link info can be retrieved by calling the [`getInfo(String... fields)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#getInfo-java.lang.String...-) method. Optional parameters can be used to retrieve specific fields of the Device Pin object. ``` BoxWebLink webLink = new BoxWebLink(api, id); BoxWebLink.Info webLinkInfo = webLink.getInfo(); ``` ## Update Web Link A web link can be updated by calling the [`updateInfo(BoxWebLink.Info fieldsToUpdate)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#updateInfo-com.box.sdk.BoxWebLink.Info-) method. ``` BoxWebLink webLink = new BoxWebLink(api, id); BoxWebLink.Info webLinkInfo = webLink.new Info(); webLinkInfo.setName("new name for weblink"); webLink.updateInfo(webLinkInfo); ``` ## Delete Web Link A web link can be deleted by calling the [`delete()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#delete--) method. ``` BoxWebLink webLink = new BoxWebLink(api, id); webLink.delete(); ``` ## Create Shared Link You can create a shared link for a web link by calling the [`createSharedLink(BoxSharedLinkWithoutPermissionsRequest sharedLinkRequest)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxWebLink.html#createSharedLink-com.box.sdk.sharedlink.BoxSharedLinkWithoutPermissionsRequest-) method. ``` // Optionally we can calculate and set the date when shared link will automatically be disabled final long ONE_WEEK_MILLIS = 1000 * 60 * 60 * 24 * 7; long unsharedTimestamp = System.currentTimeMillis() + ONE_WEEK_MILLIS; Date unsharedDate = new Date(unsharedTimestamp); BoxWebLink webLink = new BoxWebLink(api, "id"); BoxSharedLinkWithoutPermissionsRequest sharedLinkRequest = new BoxSharedLinkWithoutPermissionsRequest() .access(OPEN) .unsharedDate(unsharedDate); BoxSharedLink sharedLink = webLink.createSharedLink(sharedLinkRequest); ``` ## Remove Shared Link You can remove a shared link for a web link by calling the [`removeSharedLink`](remove-shared-link) method. ``` BoxWebLink webLink = new BoxWebLink(api, "12345"); BoxWebLink.Info webLinkInfo = webLink.getInfo(); info.removeSharedLink() webLink.updateInfo(info) ``` --- ## Untitled *Type: page* Zip Download Allows you to create a temporary zip file of Box files and folders and download them. Create a Zip File Download a Zip File… # Zip Download Allows you to create a temporary zip file of Box files and folders and download them. - [Create a Zip File](#create-a-zip-file) - [Download a Zip File](#download-a-zip-file) ## Create a Zip File Calling [`BoxZip.create(String name, List<BoxZipItem> items)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxZip.html) will let you create a new zip file with the specified name and with the specified items and will return a `BoxZipInfo` object with the download link. This file does not show up in your Box account, but will be temporarily available for download. ``` ArrayList<BoxZipItem> items = new ArrayList<BoxZipItem>(); BoxZipItem file = new BoxZipItem("file", "12345"); BoxZipItem folder = new BoxZipItem("folder", "156472"); items.add(file); items.add(folder); BoxZip zip = new BoxZip(api); BoxZipInfo zipInfo = zip.create("Awesome Zip File", items); ``` ## Download a Zip File Calling [`BoxZip.download(String name, List<BoxZipItem> items, OutputStream output)`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxZip.html) will let you create a new zip file with the specified name and with the specified items and download it to the stream that is passed in. The return object is a `BoxZipDownloadStatus` object that contains information about the download, including whether it was successful. The created zip file does not show up in your Box account. ``` ArrayList<BoxZipItem> items = new ArrayList<BoxZipItem>(); BoxZipItem file = new BoxZipItem("file", "12345"); BoxZipItem folder = new BoxZipItem("folder", "156472"); items.add(file); items.add(folder); BoxZip zip = new BoxZip(api); FileOutputStream stream = new FileOutputStream(); BoxZipDownloadStatus zipDownloadStatus = zip.download("Another Awesome Zip File", items, stream); stream.close(); if (zipDownloadStatus.getState() == BoxZipDownloadStatus.State.SUCCEEDED) { System.out.println("Zip downloaded successfully"); } ``` --- ## Untitled *Type: page* Users Users represent an individual's account on Box. Get the Current User's Information Get User Information Get Avatar for a User Add or… # Users Users represent an individual's account on Box. - [Get the Current User's Information](#get-the-current-users-information) - [Get User Information](#get-user-information) - [Get Avatar for a User](#get-avatar-for-a-user) - [Add or update user avatar](#add-or-update-user-avatar) - [Delete user avatar](#delete-user-avatar) - [Create An Enterprise User](#create-an-enterprise-user) - [Create An App User](#create-an-app-user) - [Update User](#update-user) - [Delete User](#delete-user) - [Invite User](#invite-user) - [Get Email Aliases](#get-email-aliases) - [Add Email Alias](#add-email-alias) - [Delete Email Alias](#delete-email-alias) - [Get Enterprise Users](#get-enterprise-users) - [Get Enterprise Users (Marker Pagination)](#get-enterprise-users-marker-pagination) - [Get App Users By External App User ID](#get-app-users-by-external-app-user-id) - [Get App Users By External App User ID (Marker Pagination)](#get-app-users-by-external-app-user-id-marker-pagination) - [Move User's Folder](#move-users-folder) ## Get the Current User's Information To get the current user, call the static [`getCurrentUser(BoxAPIConnection api)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getCurrentUser-com.box.sdk.BoxAPIConnection-) method. Then use [`getInfo(String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getInfo-java.lang.String...-) to get information about the user. ``` BoxUser user = BoxUser.getCurrentUser(api); BoxUser.Info info = user.getInfo(); ``` ## Get User Information To get information about a user, call the [`getInfo()`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getInfo-java.lang.String...-) method on the user object. ``` String userID = "33333"; BoxUser user = new BoxUser(api, userID); BoxUser.Info userInfo = user.getInfo(); ``` ## Get Avatar for a User To retrieve the avatar for a User, call the [`downloadAvatar(OutputStream stream)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#downloadAvatar-java.io.OutputStream-) method on the user object. ``` String userID = "33333"; // some stream do download avatar try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){ BoxUser user=new BoxUser(api,userID); user.downloadAvatar(outputStream); } catch (IOException e) { throw new RuntimeException(e); } ``` ## Add or update user avatar To add or update the avatar for a User, call the [`uploadAvatar(File)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#uploadAvatar-java.io.File-) method on the user object. ``` String userID = "33333"; BoxUser user = new BoxUser(api, userID); AvatarUploadResponse response = user.uploadAvatar(new File("path_to_avatar_file")); ``` In return, you will get an object with links to several representations of an avatar within Box account. Your image file should have correct extension, it is used to determine image type used in upload. Supported formats are JPG and PNG. The image size cannot exceed 1024 * 1024 pixels or 1MB. You can upload avatart using `InputStream` with [`uploadAvatar(InputStream, String)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#uploadAvatar-java.io.InputStream-java.lang.String-): ``` String userID = "33333"; BoxUser user = new BoxUser(api, userID); AvatarUploadResponse response = user.uploadAvatar(Files.newInputStream(Paths.get("path_to_avatar_file")), "file_name.jpeg"); ``` Both upload methods supports [`ProgressListener`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/ProgressListener.html). ## Delete user avatar To delete User avatar image use [`deleteAvatar()`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#deleteAvatar--) method on the user object: ``` String userID = "33333"; BoxUser user = new BoxUser(api, userID); user.deleteAvatar(); ``` ## Create An Enterprise User To create an enterprise user, call the [`createEnterpriseUser(BoxAPIConnection api, String loginEmail, String userName, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createEnterpriseUser-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String-java.lang.String...-). To pass additional optional parameters, use the [`createEnterpriseUser(BoxAPIConnection api, String loginEmail, String userName, CreateUserParams options, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.CreateUserParams-java.lang.String...-) method. ``` BoxUser.Info createdUserInfo = BoxUser.createEnterpriseUser(api, "user@example.com", "A User"); ``` ## Create An App User To create an app user, call the [`createAppUser(BoxAPIConnection api, String userName, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...-) method. To pass additional optional parameters, use the [`createAppUser(BoxAPIConnection api, String userName, CreateUserParams options, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#createAppUser-com.box.sdk.BoxAPIConnection-java.lang.String-com.box.sdk.CreateUserParams-java.lang.String...-) method. ``` BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, "A User"); ``` ``` CreateUserParams params = new CreateUserParams(); params.setExternalAppUserId("An Identifier Like Login"); BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, "A User", params); ``` ## Update User To update a user call the [`updateInfo(BoxUser.Info fieldsToUpdate, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#updateInfo-com.box.sdk.BoxUser.Info-java.lang.String...-) method. ``` BoxUser user = new BoxUser(api, "0"); BoxUser.Info info = user.new Info(); info.setName(name); user.updateInfo(info); ``` ## Delete User To delete a user call the [`delete(boolean notifyUser, boolean force)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#delete-boolean-boolean-) method or one that uses API default parameters [`delete()](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#delete--) The `notifyUser` determines whether the user should receive an email about the deletion, and the `force` parameter will cause the user to be deleted even if they still have files in their account. ``` BoxUser user = new BoxUser(api, "0"); user.delete(false, false); ``` ## Invite User To invite an existing user to join an Enterprise call the [`inviteUser(String enterpriseID, String userEmail)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#inviteUser-java.lang.String-java.lang.String-) method. ``` BoxUser user = new BoxUser(api, "0"); user.invite("Enterprise ID", "Invited User Login"); ``` ## Get Email Aliases To get a user's email aliases call the [`getEmailAliases()`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getEmailAliases--) method. ``` BoxUser user = new BoxUser(api, "0"); Collection<EmailAlias> emailAliases = user.getEmailAliases(); ``` ## Add Email Alias To add an email alias for a user, call the [`addEmailAlias(String emailAddress)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#addEmailAlias-java.lang.String-) method. ``` BoxUser user = new BoxUser(api, "0"); user.addEmailAlias("user+alias@example.com"); ``` Enterprise admins can automatically confirm the new email alias by calling the [`addEmailAlias(String emailAddress, boolean confirm)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#addEmailAlias-java.lang.String-boolean-) method: ``` BoxUser user = new BoxUser(api, "0"); user.addEmailAlias("user+alias@eexample.com", true); ``` ## Delete Email Alias To delete a users email alias call the [`deleteEmailAlias(String emailAliasID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#deleteEmailAlias-java.lang.String-) method. ``` BoxUser user = new BoxUser(api, "0"); user.deleteEmailAlias("123"); ``` ## Get Enterprise Users To get an enterprise's users call the [`getAllEnterpriseUsers(BoxAPIConnection api)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection-), [`getAllEnterpriseUsers(BoxAPIConnection api, String filterTerm, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...-), or [`getAllEnterpriseOrExternalUsers(BoxAPIConnection api, String filterTerm, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseOrExternalUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...-) method. ``` Iterable<BoxUser.Info> users = BoxUser.getAllEnterpriseUsers(api); ``` ## Get Enterprise Users (Marker Pagination) To get a list of all users in an enterprise, call the [`getAllEnterpriseUsers(BoxAPIConnection api, boolean usemarker, String marker)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection-), [`getAllEnterpriseUsers(BoxAPIConnection api, String filterTerm, boolean usemarker, String marker, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...-), or [`getAllEnterpriseOrExternalUsers(BoxAPIConnection api, String filterTerm, boolean usemarker, String marker, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAllEnterpriseOrExternalUsers-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...-) method. To get a list of users starting from the first page of results, set the `usemarker` parameter as `true` and the `marker` parameter as `null`. If you would like to get the marker for the next page of results from the page the iterator is currently on, you must cast the iterable to `BoxResourseIterable<BoxUser.info>` and call `getNextMarker()` on that iterable. For more information on marker pagination, look here: [https://developer.box.com/en/guides/api-calls/pagination/marker-based/](https://developer.box.com/en/guides/api-calls/pagination/marker-based/). ``` Iterable<BoxUser.Info> users = BoxUser.getAllEnterpriseUsers(api, true, null); // Get marker String marker = ((BoxResourceIterable<BoxUser.Info>) users).getNextMarker(); ``` ## Get App Users By External App User ID To get app user using external app user ID, call the [`getAppUsersByExternalAppUserID(BoxAPIConnection api, String externalID, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAppUsersByExternalAppUserID-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...-). This method allows you to easily associate Box app users with your application's identifiers for those users. ``` Iterable<BoxUser.Info> users = BoxUser.getAppUsersByExternalAppUserID(api, "external_app_user_id"); ``` ## Get App Users By External App User ID (Marker Pagination) To get app user using external app user ID, call the [`getAppUsersByExternalAppUserID(BoxAPIConnection api, String externalID, boolean usemarker, String marker, String... fields)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAppUsersByExternalAppUserID-com.box.sdk.BoxAPIConnection-java.lang.String-java.lang.String...-). This method allows you to easily associate Box app users with your application's identifiers for those users. To get a list of users starting from the first page of results, set the `usemarker` parameter as `true` and the `marker` parameter as `null`. If you would like to get the marker for the next page of results from the page the iterator is currently on, you must cast the iterable to `BoxResourseIterable<BoxUser.info>` and call `getNextMarker()` on that iterable. For more information on marker pagination, look here: [https://developer.box.com/en/guides/api-calls/pagination/marker-based/](https://developer.box.com/en/guides/api-calls/pagination/marker-based/). ``` Iterable<BoxUser.Info> users = BoxUser.getAppUsersByExternalAppUserID(api, "external_app_user_id"); // Get marker String marker = ((BoxResourceIterable<BoxUser.Info>) users).getNextMarker(); ``` ## Move User's Folder To move all of a user's content to another user, call the [`transferContent(String destinationUserID)`](https://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#transferContent-java.lang.String-) method. ``` String sourceUserID = "11111"; String destinationUserID = "22222"; BoxUser sourceUser = new BoxUser(api, sourceUserID); BoxFolder.Info transferredFolderInfo = sourceUser.transferContent(destinationUserID); ``` --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - if you want to contribute code. Please be sure to file an issue first. ## Pull request best practices We want to accept your pull requests. Please follow these steps: ### Step 1: File an issue Before writing any code, please file an issue stating the problem you want to solve or the feature you want to implement. This allows us to give you feedback before you spend any time writing code. There may be a known limitation that can't be addressed, or a bug that has already been fixed in a different way. The issue allows us to communicate and figure out if it's worth your time to write a bunch of code for the project. ### Step 2: Fork this repository in GitHub This will create your own copy of our repository. ### Step 3: Add the upstream source The upstream source is the project under the Box organization on GitHub. To add an upstream source for this project, type: ``` git remote add upstream git@github.com:box/box-java-sdk.git ``` This will come in useful later. ### Step 4: Create a feature branch Create a branch with a descriptive name, such as `add-search`. ### Step 5: Push your feature branch to your fork We use [semantic-versioning](https://semver.org/) and the [conventional commit message format](https://www.conventionalcommits.org/en/v1.0.0/). Keep a separate feature branch for each issue you want to address. As you develop code, continue to push code to your remote feature branch. Example: ``` tag: short description longer description here if necessary. ``` The message summary should be a one-sentence description of the change, and it must be 72 characters in length or shorter. For a list of tags, please [click here](https://github.com/commitizen/conventional-commit-types/blob/master/index.json). Note that you must include the `!` for breaking changes (e.g. `feat!: removed old apis`). Shown below are examples of the release type that will be done based on a commit message. #### Commit Types "Semantic versioning" means that changes to the version number of the package (e.g. `3.42.11` to `3.43.0`) are done according to rules that indicate how the change will affect consumers. Read more on the [semver page](https://semver.org/). The version number is broken into 3 positions — `Major.Minor.Patch`. In semantic release terms, changes to the numbers follow `Breaking.Feature.Fix`. The `release` script parses commit messages and decides what type of release to make based on the types of commits detected since the last release. The rules for commit types are: - Anything that changes or removes an API, option, or output format is a breaking change denoted by `!`. - Anything that adds new functionality in a backwards-compatible way is a feature (`feat`). Consumers have to upgrade to the new version to use the feature, but nothing will break if they do so. - Bugfixes (`fix`) for existing behavior are a patch. Consumers don't have to do anything but upgrade. - Other prefixes, such as `docs` or `chore`, don't trigger releases and don't appear in the changelog. These tags signal that there are **no external changes to *any* APIs** (including non-breaking ones). In most cases, commits will be a `feat` or `fix`. Make sure to include the `!` in the title if there are non-backwards-compatible changes in the commit. | Commit message | Release type | New version | | --- | --- | --- | | feat!: remove old files endpoints | Major ("breaking") | X+1.0.0 | | feat: add new file upload endpoint | Minor ("feature") | X.Y+1.0 | | fix: file streaming during download | Patch ("fix") | X.Y.Z+1 | | docs: document files api | No release | X.Y.Z | | chore: remove commented code from file upload | No release | X.Y.Z | | refactor: rename a variable (invisible change) | No release | X.Y.Z | ### Step 6: Rebase Before sending a pull request, rebase against upstream, such as: ``` git fetch upstream git rebase upstream/main ``` This will add your changes on top of what's already in upstream, minimizing merge issues. ### Step 7: Run the tests Make sure that the code builds and passes all unit tests by running: ``` $ ./gradlew clean build ``` ### Step 8: Send the pull request Send the pull request from your feature branch to us. Be sure to include a description that lets us know what work you did. Keep in mind that we like to see one issue addressed per pull request, as this helps keep our git history clean and we can more easily track down issues. --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 4.16.3 (2025-0… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### 4.16.3 (2025-07-23) ### Bug Fixes: - Fix compare message webhook message signature ([#1315](https://github.com/box/box-java-sdk/issues/1315)) ([e2d407d](https://github.com/box/box-java-sdk/commit/e2d407ded3370ffee6eb074044fd562629a904be)) - Fix File Request Copy method to return valid data ([#1320](https://github.com/box/box-java-sdk/issues/1320)) ([8392a43](https://github.com/box/box-java-sdk/commit/8392a437c1a738bebb4e7d0f84d6bf833c76bdf3)) ### 4.16.2 (2025-06-02) ### Bug Fixes: - Fix parsing `downloadFileCount` property for `BoxZipDownloadStatus` ([50c2249](https://github.com/box/box-java-sdk/commit/50c2249ff5e0f0d1fdc99c9ff8786e9c134e58eb)) ### 4.16.1 (2025-04-29) ### Bug Fixes: - use `Locale.ROOT` to prevent issues with non-US locales ([#1306](https://github.com/box/box-java-sdk/issues/1306)) ([f083092](https://github.com/box/box-java-sdk/commit/f083092d5fdac37c93493945ab0c05ecdcdbc838)) ## 4.16.0 (2025-04-15) ### New Features and Enhancements: - Bump version of `zstd-jni` ([#1302](https://github.com/box/box-java-sdk/issues/1302)) ([9ebf8b5](https://github.com/box/box-java-sdk/commit/9ebf8b5d16c0ab8f4aa19849fdaa86935d38b294)) ### 4.15.3 (2025-03-12) ### Bug Fixes: - trim `content-length` header value ([#1297](https://github.com/box/box-java-sdk/issues/1297)) ([fa11d14](https://github.com/box/box-java-sdk/commit/fa11d141edf511eabc5f2398e55dc411d0cdcd31)) ### 4.15.2 (2025-02-26) ### Bug Fixes: - Improve logging for API Request and API Response ([#1295](https://github.com/box/box-java-sdk/issues/1295)) ([6eb1f57](https://github.com/box/box-java-sdk/commit/6eb1f57a584571b46daa14d045a36bca382493fa)) ### 4.15.1 (2025-02-24) ### Bug Fixes: - Fix parsing content length header ([#1292](https://github.com/box/box-java-sdk/issues/1292)) ([3bcf788](https://github.com/box/box-java-sdk/commit/3bcf788dd9849305aa2cc85b8e5f88b35803ecb2)) ## 4.15.0 (2025-02-19) ### New Features and Enhancements: - Add `canNonOwnersViewCollaborators` flag to `Folder` ([#1288](https://github.com/box/box-java-sdk/issues/1288)) ([9119adc](https://github.com/box/box-java-sdk/commit/9119adceae35e892e73ed61ed30cf82ad912960d)) - Support `zstd` encoding for downloads ([#1287](https://github.com/box/box-java-sdk/issues/1287)) ([0e3c4c0](https://github.com/box/box-java-sdk/commit/0e3c4c07e65ef1887cd5c393e3daf98aeb50ee47)) ### Bug Fixes: - Fix AI dialogue history ([#1289](https://github.com/box/box-java-sdk/issues/1289)) ([29b6519](https://github.com/box/box-java-sdk/commit/29b651987a5cbeead4b129cab20970f983cb6889)) ## 4.14.0 (2025-01-22) ### New Features and Enhancements: - Support downloading file from shared link ([#1282](https://github.com/box/box-java-sdk/issues/1282)) ([9b7f28b](https://github.com/box/box-java-sdk/commit/9b7f28b0288977513b0db3ed4f800647545e1f2c)) ### Bug Fixes: - Remove sensitive data when `BoxAPIException` logs request ([#1284](https://github.com/box/box-java-sdk/issues/1284)) ([f1e226f](https://github.com/box/box-java-sdk/commit/f1e226f710c301202acff067ef34687ddbb57b7b)) - Support creating ongoing Legal Hold policy with start date ([#1281](https://github.com/box/box-java-sdk/issues/1281)) ([d9564e2](https://github.com/box/box-java-sdk/commit/d9564e2e86ea110af933ca3dd0f728111d7140ae)) ### 4.13.1 (2024-11-29) ### Bug Fixes: - Correctly calculate `Content-Length` when reading from a stream ([#1277](https://github.com/box/box-java-sdk/issues/1277)) ([b1d5371](https://github.com/box/box-java-sdk/commit/b1d5371491abe1729a95eb9dc39d375135c8681d)) ## 4.13.0 (2024-11-21) ### New Features and Enhancements: - Enforce exact byte reading from `Content-Length` header for `BoxFile` representation ([#1274](https://github.com/box/box-java-sdk/issues/1274)) ([0b45cdb](https://github.com/box/box-java-sdk/commit/0b45cdb74c21996d1dfea505d25430a1fa9ee730)) - Expose `getVersionByID` method on `BoxFile` ([#1268](https://github.com/box/box-java-sdk/issues/1268)) ([6ea70f7](https://github.com/box/box-java-sdk/commit/6ea70f79ad39dd9a427ee574b5536d0ab1e3a9a4)) - make `tryRestoreUsingAccessTokenCache` in Box API connection public ([#1272](https://github.com/box/box-java-sdk/issues/1272)) ([50f5a61](https://github.com/box/box-java-sdk/commit/50f5a61184bd1a17a17e811536166f9f8e081a13)) ### Bug Fixes: - Fix `accessToken` locking mechanism ([#1270](https://github.com/box/box-java-sdk/issues/1270)) ([5eb4c93](https://github.com/box/box-java-sdk/commit/5eb4c93bd3653b28dc7def747779d008369f486a)) ## 4.12.0 (2024-10-17) ### New Features and Enhancements: - Support AI Agent ([#1265](https://github.com/box/box-java-sdk/issues/1265)) ([3cb2c7c](https://github.com/box/box-java-sdk/commit/3cb2c7c275761a24be9403a6a2b41d0725ba8d9b)) - Support AI extract and AI extract structured ([#1266](https://github.com/box/box-java-sdk/issues/1266)) ([7ba90b9](https://github.com/box/box-java-sdk/commit/7ba90b96070a32b3e2ac60e5c55bd04d0a5973c0)) ### 4.11.1 (2024-07-16) ### Bug Fixes: - Fix order of file upload multipart request ([#1261](https://github.com/box/box-java-sdk/issues/1261)) ([7200ac7](https://github.com/box/box-java-sdk/commit/7200ac77888b3639f2c294486be278e316efcfb0)) ## 4.11.0 (2024-07-15) ### New Features and Enhancements: - Allow overriding creation of OkHttp Call ([#1257](https://github.com/box/box-java-sdk/issues/1257)) ([bd6fde6](https://github.com/box/box-java-sdk/commit/bd6fde6689bebe6cb5889c91214db68e08a4ec8b)) ### Bug Fixes: - Add missing fields when update classification template ([#1255](https://github.com/box/box-java-sdk/issues/1255)) ([f17f817](https://github.com/box/box-java-sdk/commit/f17f817bde5a412358bf3de8e489ed080715ec4b)) - Fix deserializing permissions for `BoxFile` and `BoxFolder` ([#1256](https://github.com/box/box-java-sdk/issues/1256)) ([f088448](https://github.com/box/box-java-sdk/commit/f08844889800a01f7c78941036f6228502fca8b0)) ## 4.10.0 (2024-06-06) ### New Features and Enhancements: - Overload the `getRepresentationContent` method with a `maxRetries` parameter ([#1251](https://github.com/box/box-java-sdk/issues/1251)) ([d26bd4f](https://github.com/box/box-java-sdk/commit/d26bd4f5a141150a372159bc3867abbbbdda1406)) - Support `login_required`, `password`, `suppress_nofitications`, `verification_phone_number` and `additional_info` fields in sign request ([#1250](https://github.com/box/box-java-sdk/issues/1250)) ([3ee55b3](https://github.com/box/box-java-sdk/commit/3ee55b3613c5f5fa92cdd4a17c0cb3e2cc86a9a4)) ### 4.9.1 (2024-05-20) ### Bug Fixes: - Bumped `org.bouncycastle:bcprov-jdk18on:1.78.1` and `org.bouncycastle:bcpkix-jdk18on:1.78.1` ([#1246](https://github.com/box/box-java-sdk/issues/1246)) ([0557bed](https://github.com/box/box-java-sdk/commit/0557bed2b65d1be717b64a612d74fca73ba21096)) ## 4.9.0 (2024-05-06) ### New Features and Enhancements: - Support AI API ([#1243](https://github.com/box/box-java-sdk/issues/1243)) ([4e64f27](https://github.com/box/box-java-sdk/commit/4e64f27874fabf36f7fbf385ca4a60683f4a7670)) - Support pagination of file versions ([#1240](https://github.com/box/box-java-sdk/issues/1240)) ([7e7af3f](https://github.com/box/box-java-sdk/commit/7e7af3f6e40a44522a7649817547846e3f633fc8)) ### Bug Fixes: - Support create empty shared link ([#1241](https://github.com/box/box-java-sdk/issues/1241)) ([0c86487](https://github.com/box/box-java-sdk/commit/0c86487848e5004a713873baffa2d9dcc63b1502)) - Update exception message for get representation content ([#1239](https://github.com/box/box-java-sdk/issues/1239)) ([a608f9a](https://github.com/box/box-java-sdk/commit/a608f9a4350b723e9f07eaf00af45243737a17c9)) ## 4.8.0 (2024-02-27) ### New Features and Enhancements: - allow modifying `BoxAPIRequest` URL ([#1236](https://github.com/box/box-java-sdk/issues/1236)) ([eaea019](https://github.com/box/box-java-sdk/commit/eaea0193ab7e72b73746ea85806e62468825bbce)) - Bumped `org.bouncycastle:bcprov-jdk18on:1.77` and `org.bouncycastle:bcpkix-jdk18on:1.77` ([#1237](https://github.com/box/box-java-sdk/issues/1237)) ([6c7fe7b](https://github.com/box/box-java-sdk/commit/6c7fe7b74dbfb34e729fcecf8a29a1d3a1ba596f)), closes [#1235](https://github.com/box/box-java-sdk/issues/1235) ### Bug Fixes: - fix download for empty files ([#1231](https://github.com/box/box-java-sdk/issues/1231)) ([0e2230b](https://github.com/box/box-java-sdk/commit/0e2230b0be36f6bfb35f1d6b9dd4ba58e4d125ec)) - stop using `SharedLinkAPIConnection` in `getSharedItem()` ([#1234](https://github.com/box/box-java-sdk/issues/1234)) ([9f9af8e](https://github.com/box/box-java-sdk/commit/9f9af8e22b4a38dc9a31a611ff1b962966bbd6b5)) ## 4.7.0 (2024-01-16) ### New Features and Enhancements: - Add `signer_group_id` for signer in sign request ([#1220](https://github.com/box/box-java-sdk/issues/1220)) ([f560db8](https://github.com/box/box-java-sdk/commit/f560db8d5587406099066803789d16374ec7dbb9)) - Introduce `IPrivateKeyDecryptor` to allow using custom cryptography provider ([#1226](https://github.com/box/box-java-sdk/issues/1226)) ([727e6d7](https://github.com/box/box-java-sdk/commit/727e6d71ee375a48b4241a26a093becfe0965898)) ### Bug Fixes: - Remove delete classification ([#1222](https://github.com/box/box-java-sdk/issues/1222)) ([9814038](https://github.com/box/box-java-sdk/commit/981403896b4cd16a42c9feeecf30e75e1e8fa072)) ### 4.6.1 (2023-11-02) ### Dependency Upgrades: - Bumped `org.bitbucket.b_c:jose4j:0.9.3` ([#1212](https://github.com/box/box-java-sdk/issues/1212)) ([f522a56](https://github.com/box/box-java-sdk/commit/f522a5660f3522b11a0516774ba0cca69db3ec31)) ## 4.6.0 (2023-09-28) ### New Features and Enhancements: - Support search deleted filters ([#1207](https://github.com/box/box-java-sdk/issues/1207)) ([5e0e9ed](https://github.com/box/box-java-sdk/commit/5e0e9ed9aea2818da6fba0d562b56987c4948aaa)) ### Bug Fixes: - Added protected accessors for trust manager and hostname verifier. ([#1206](https://github.com/box/box-java-sdk/issues/1206)) ([0c79d17](https://github.com/box/box-java-sdk/commit/0c79d1754bffeb3f0487e10d55d716ba1cbed1aa)) - fix not closing response body ([#1208](https://github.com/box/box-java-sdk/issues/1208)) ([ab5e170](https://github.com/box/box-java-sdk/commit/ab5e1702934607b258802b33f3663af3e9c56027)) ## 4.5.0 (2023-09-13) ### New Features and Enhancements: - Add `iframeable_embed_url` field to `BoxSignRequestSigner` class ([#1202](https://github.com/box/box-java-sdk/issues/1202)) ([2e931d8](https://github.com/box/box-java-sdk/commit/2e931d8c36694a665d1c6315d3bf2d226929b713)) ### Bug Fixes: - `SharedLinkAPIConnection` uses request interceptor ([#1203](https://github.com/box/box-java-sdk/issues/1203)) ([b2b6a1d](https://github.com/box/box-java-sdk/commit/b2b6a1dba316ba50a1e011250c320fca156c6708)), closes [#1200](https://github.com/box/box-java-sdk/issues/1200) - Update sign template missing enum ([#1201](https://github.com/box/box-java-sdk/issues/1201)) ([fcb6657](https://github.com/box/box-java-sdk/commit/fcb6657bb2375e32c3fb0f861e7ecaeb84503f2c)) ## 4.4.0 (2023-08-29) ### New Features and Enhancements: - Support sign template and new sign status ([#1197](https://github.com/box/box-java-sdk/issues/1197)) ([e37c0dc](https://github.com/box/box-java-sdk/commit/e37c0dce86a422de5e8e6ed26fd93f1324f4b3e3)) ## 4.3.0 (2023-08-11) ### New Features and Enhancements: - Support access only collaboration ([#1193](https://github.com/box/box-java-sdk/issues/1193)) ([664c01f](https://github.com/box/box-java-sdk/commit/664c01f80ca0647645c60920eb0ef1f9353a619f)) ### 4.2.1 (2023-08-03) ### Bug Fixes: - Fixed upload when data are coming from a dynamic source ([#1189](https://github.com/box/box-java-sdk/issues/1189)) ([77b39f2](https://github.com/box/box-java-sdk/commit/77b39f2645d53bdab0ade23b637c211ea070fcf5)), closes [#1183](https://github.com/box/box-java-sdk/issues/1183) [#1190](https://github.com/box/box-java-sdk/issues/1190) ## 4.2.0 (2023-06-21) ### New Features and Enhancements: - Getting collaborators allows to specify fields ([#1178](https://github.com/box/box-java-sdk/issues/1178)) ([1694d75](https://github.com/box/box-java-sdk/commit/1694d75fff0fbddb938426ef03ba24f360a344aa)) ### 4.1.2 (2023-06-14) ### Bug Fixes: - Class cast exception when uploading large file ([#1174](https://github.com/box/box-java-sdk/issues/1174)) ([e7d28bd](https://github.com/box/box-java-sdk/commit/e7d28bddb706c8b4fd1328f0eebc50db19a8c656)), closes [#1173](https://github.com/box/box-java-sdk/issues/1173) - Make `SharedLinkAPIConnection` constructors public ([#1172](https://github.com/box/box-java-sdk/issues/1172)) ([4d1616d](https://github.com/box/box-java-sdk/commit/4d1616ddd2c39d1cb0d03af998d2c47efe607853)) - Remove invalid Group membership role ([#1171](https://github.com/box/box-java-sdk/issues/1171)) ([a5915f9](https://github.com/box/box-java-sdk/commit/a5915f94114a8269287831280a57949ed203e4e8)) ### 4.1.1 (2023-05-16) ### Bug Fixes: - Allow users to disable adding authentication header. ([#1167](https://github.com/box/box-java-sdk/issues/1167)) ([3433e5a](https://github.com/box/box-java-sdk/commit/3433e5a405ceb9bc32791642518b1fd65c4b4032)) - Logging headers when retrying request ([#1164](https://github.com/box/box-java-sdk/issues/1164)) ([e0c3d8e](https://github.com/box/box-java-sdk/commit/e0c3d8e730962ba5c97105ce506ee931a3bba362)) ## 4.1.0 (2023-04-24) ### New Features and Enhancements: - Add missing `fields` parameter to create and update `BoxUser` methods ([#1155](https://github.com/box/box-java-sdk/issues/1155)) ([be3820d](https://github.com/box/box-java-sdk/commit/be3820dc4df15e99dfc13602d4f7269841bd15b3)), closes [#1154](https://github.com/box/box-java-sdk/issues/1154) ### Bug Fixes: - Allow registering custom logger handlers ([#1156](https://github.com/box/box-java-sdk/issues/1156)) ([7373d5c](https://github.com/box/box-java-sdk/commit/7373d5cc2bf49bc198cbca70d056e43f0dffdb3a)) - Fallback to default value of `maxRetryAttempts` when restoring `BoxAPIConnection` ([#1161](https://github.com/box/box-java-sdk/issues/1161)) ([2a10e5d](https://github.com/box/box-java-sdk/commit/2a10e5d07497611e077a9207fe98c1d8146cfd22)), closes [#1160](https://github.com/box/box-java-sdk/issues/1160) ### 4.0.1 (2023-03-06) ### Bug Fixes: - `OAUTH_SUFFIX` gets appended twice to `baseAuthorizationURL` ([#1148](https://github.com/box/box-java-sdk/issues/1148)) ([3164770](https://github.com/box/box-java-sdk/commit/3164770498e5115a43318640735317a896950f54)), closes [#1147](https://github.com/box/box-java-sdk/issues/1147) - Wrong progress reported to `ProgressListener` by `AbstractBoxMultipartRequest` ([#1151](https://github.com/box/box-java-sdk/issues/1151)) ([947ded3](https://github.com/box/box-java-sdk/commit/947ded394490fc840b8191bc7ad69ae0ea5f5c7d)), closes [#1149](https://github.com/box/box-java-sdk/issues/1149) ## 4.0.0 (2023-01-17) The most important change this release includes is the replacement of the HTTP library from a native one to [OkHttp](https://square.github.io/okhttp/) which allows SDK to - Support the HTTP2 version of the HTTP protocol. Support proxies that do not use only basic authentication method. For details on creating custom proxy authenticators and an example of [NTLM proxy authentication](https://github.com/box/box-java-sdk/blob/kb/ok-http/doc/configuration.md#custom-proxy-authenticator). ### Breaking Changes - `BatchAPIRequest` – is no longer supported by the SDK - `BoxAPIConnection#DEFAULT_MAX_ATTEMPTS` is replaced with `BoxAPIConnection#DEFAULT_MAX_RETRIES` - `BoxRedirectResponse` – was removed and will not be replaced - `BoxEvent.Type` is replaced with `EventType` - Removing deprecated methods from `BoxFile`, `BoxFileVersionRetention`, `BoxFolder`, `BoxGroup`, `BoxGroupMembership`,`BoxItem`, `BoxRetentionPolicy`, `BoxTask`, `BoxUser`, `BoxWebLink`, `EventLog`, `Metadata` and `MetadataTemplate`. Migration details can be found [here](doc/upgrades/3.x.x%20to%204.x.x.md). ### New Features and Enhancements: - Using `OkHttp` in Java SDK ([#1083](https://github.com/box/box-java-sdk/issues/1083)) ([2656698](https://github.com/box/box-java-sdk/commit/265669897100dd8f1757fc2c5f25665da42c2889)) ### 3.8.2 (2023-01-04) ### Bug Fixes: - Fixed restoring state without refresh token. ([#1139](https://github.com/box/box-java-sdk/issues/1139)) ([3544709](https://github.com/box/box-java-sdk/commit/3544709480eb03e5bd50f5dc99be7409569304c4)) ### 3.8.1 (2022-12-19) ### Bug Fixes: - Restoring state from previous `SDK` version works. ([#1134](https://github.com/box/box-java-sdk/issues/1134)) ([b6d97dd](https://github.com/box/box-java-sdk/commit/b6d97dd5b0cc91eb2e4c922ff217e0878e0f63ec)) ## 3.8.0 (2022-11-15) ### New Features and Enhancements: - Added Box Sign webhooks ([#1109](https://github.com/box/box-java-sdk/issues/1109)) ([99051a5](https://github.com/box/box-java-sdk/commit/99051a575f120a8c0939359c1f4875b16b98b7f0)) ### Bug Fixes: - `NullPointerException` when using `BoxSignRequestPrefillTag` ([#1121](https://github.com/box/box-java-sdk/issues/1121)) ([73fd5b6](https://github.com/box/box-java-sdk/commit/73fd5b6e6e40f7e79b385edf46b8eee5ff612ace)), closes [#1120](https://github.com/box/box-java-sdk/issues/1120) - Regenerate JWT ID and retry auth request when JTI claim is rejected ([#1110](https://github.com/box/box-java-sdk/issues/1110)) ([420da0f](https://github.com/box/box-java-sdk/commit/420da0f2c80bfe8cfbaba4fa8dec4826c4cb6337)) ### Dependency Upgrades: - Bumped org.bitbucket.b_c:jose4j:0.9.0 ([#1111](https://github.com/box/box-java-sdk/issues/1111)) ([349694d](https://github.com/box/box-java-sdk/commit/349694ddcfeb701a9ecdfd5ae555d49bea4d1030)) ### 3.7.1 (2022-09-29) ### Bug Fixes: - Better logging when JSON cannot be parsed ([#1106](https://github.com/box/box-java-sdk/issues/1106)) ([5e66ef8](https://github.com/box/box-java-sdk/commit/5e66ef8cc983a6cff34995efc75e9effd3195d48)) ## 3.7.0 (2022-09-20) ### New Features and Enhancements: - Add `is_accessible_via_shared_link` field to File and Folder ([#1103](https://github.com/box/box-java-sdk/issues/1103)) ([45e9906](https://github.com/box/box-java-sdk/commit/45e9906efca6a7f2d4d738914dc804de12d3646e)) ### Bug Fixes: - `BoxCollaboration.getItem()` returns `BoxItem.Info` not `BoxFolder.Info` ([#1102](https://github.com/box/box-java-sdk/issues/1102)) ([135850d](https://github.com/box/box-java-sdk/commit/135850d97164ee5f6d74708d74c531f7fa8bee26)), closes [#1101](https://github.com/box/box-java-sdk/issues/1101) [#1100](https://github.com/box/box-java-sdk/issues/1100). `BoxCollaboration.getItem()` used to return `BoxFolder.Info`. However, if collaboration was added on a file it would still return `BoxFolder.Info` which will end with throwing `BoxAPIException` when doing any API call. If you are getting collaboration item it is best to store it as `BoxItem.Info` or check its type and store it as `BoxFile.Info` or `BoxFolder.Info`. - Add missing constructor to `BoxNotificationEmail` class ([#1098](https://github.com/box/box-java-sdk/issues/1098)) ([2534f34](https://github.com/box/box-java-sdk/commit/2534f34133f9554abd1e80fc1555659a2c52b23f)) ## 3.6.0 (2022-09-07) ### New Features and Enhancements: - Add support for modifiable retention policies & enable deleting retention policy assignment ([#1093](https://github.com/box/box-java-sdk/issues/1093)) ([30e2fcb](https://github.com/box/box-java-sdk/commit/30e2fcb74c12867fd3859c3490539557b47ab006)) ### Bug Fixes: - Stop sending not specified optional fields when creating a user ([#1095](https://github.com/box/box-java-sdk/issues/1095)) ([b7d894d](https://github.com/box/box-java-sdk/commit/b7d894d3f134137f3a5925f09accfd4334837f81)) ## 3.5.0 (2022-08-26) ### New Features and Enhancements: - Add `content-type` sign request and response ([#1087](https://github.com/box/box-java-sdk/issues/1087)) ([49411aa](https://github.com/box/box-java-sdk/commit/49411aaeea6d3ff8de10e3fbc3c60bba1bc54748)) - Add `notification_email` to `BoxUser` ([#1088](https://github.com/box/box-java-sdk/issues/1088)) ([5477223](https://github.com/box/box-java-sdk/commit/547722347a920ba11e5fff7a8df5201720af815a)) - Add `redirect_url` and `declined_redirect_url` to sign request response ([#1089](https://github.com/box/box-java-sdk/issues/1089)) ([3921fe1](https://github.com/box/box-java-sdk/commit/3921fe1a4a6249146a8dd2f22e15801846bc073b)) ### Bug Fixes: - Fixed canceling sign request fails because of empty body ([#1085](https://github.com/box/box-java-sdk/issues/1085)) ([32b8e79](https://github.com/box/box-java-sdk/commit/32b8e79ebc8995ab933c32d28c3e2f17d9627a70)) ## 3.4.0 (2022-08-10) ### New Features and Enhancements: - Added pagination for getting items in trash with new `BoxTrash#items` API ([#1072](https://github.com/box/box-java-sdk/issues/1072)) ([9cd411d](https://github.com/box/box-java-sdk/commit/9cd411d20af1bc76ae815905396d72008af62539)) ### Bug Fixes: - buffered body write and fixed SDK logging ([#1079](https://github.com/box/box-java-sdk/issues/1079)) ([bc35ef3](https://github.com/box/box-java-sdk/commit/bc35ef3279e68a3d794de454f506ba41d14c3b16)) ## 3.3.0 (2022-07-01) ### New Features and Enhancements: - Added support of Editable Shared Links ([#1064](https://github.com/box/box-java-sdk/issues/1064)) ([9b7d60c](https://github.com/box/box-java-sdk/commit/9b7d60c41fbd481465bf3f2a5877746f10849712)) ### Bug Fixes: - Fix closed stream exception in `canUpload` method ([#1067](https://github.com/box/box-java-sdk/issues/1067)) ([543f91c](https://github.com/box/box-java-sdk/commit/543f91c46dfcc9de7e61ce11cd93d472916533ac)) ### 3.2.1 (2022-06-10) ### Bug Fixes: - Fix getting proper URL to authenticate with OAuth ([#1059](https://github.com/box/box-java-sdk/issues/1059)) ([42876b4](https://github.com/box/box-java-sdk/commit/42876b45ccdb7fa6f357186cecaba051abf1c269)), closes [#1057](https://github.com/box/box-java-sdk/issues/1057) ## 3.2.0 (2022-05-23) ### New Features and Enhancements: - Revamped setting base URLs ([#1042](https://github.com/box/box-java-sdk/issues/1042)) ([129baf7](https://github.com/box/box-java-sdk/commit/129baf704ced127788bb0f62ef9f4fb6a50fdc63)) - support for Avatar V2 API ([#1044](https://github.com/box/box-java-sdk/issues/1044)) ([18651d7](https://github.com/box/box-java-sdk/commit/18651d7a5b419796e3733c7582ae471d7af7ed5c)) ### 3.1.2 (2022-03-22) ### Bug Fixes: - Allow using `As-User` header with CCG Authentication ([#1031](https://github.com/box/box-java-sdk/issues/1031)) ([b0c2389](https://github.com/box/box-java-sdk/commit/b0c238913cc1dbcecfd546a5eae68277c3c76d42)) - Fix retry logic when `Retry-After` header is present ([#1033](https://github.com/box/box-java-sdk/issues/1033)) ([05224c4](https://github.com/box/box-java-sdk/commit/05224c433d2a101a01959644674153df9542b711)) ### 3.1.1 (2022-02-28) ### Bug Fixes: - retry `jwt` auth when error code is in error field ([#1020](https://github.com/box/box-java-sdk/issues/1020)) ([8c9d11d](https://github.com/box/box-java-sdk/commit/8c9d11d1b3556552751c9f4ac99a0f7180af97f3)), closes [#1019](https://github.com/box/box-java-sdk/issues/1019) ## 3.1.0 (2022-02-17) ### New Features and Enhancements: - Added support for Client Credentials Grant authentication method ([#1002](https://github.com/box/box-java-sdk/issues/1002)) ([9cfcaff](https://github.com/box/box-java-sdk/commit/9cfcaff243dbf0541409f91f9f863a207345dc47)) - API to extend disposition date on a file ([#1001](https://github.com/box/box-java-sdk/issues/1001)) ([f3f6b60](https://github.com/box/box-java-sdk/commit/f3f6b6043eec362c5a8ad9a01d6588538ca34e71)) - Deprecating `indexName` when executing metadata query ([#1000](https://github.com/box/box-java-sdk/issues/1000)) ([c20dbbf](https://github.com/box/box-java-sdk/commit/c20dbbf6a927e31cfdd7ffa71069c0897f7a0536)) ### Dependency Upgrades: - Upgrade Gradle to 7.3.3 ([#985](https://github.com/box/box-java-sdk/issues/985)) ([e4acbb1](https://github.com/box/box-java-sdk/commit/e4acbb1f0c10ccdeeee139e2566b344052680010)) ## 3.0.0 (2022-01-17) ### ⚠ BREAKING CHANGES - Changed `BoxFileVersion` class and removed `fileVersion` field (#978) - Removed deprecated API `BoxCollaborationWhitelist` replaced with `BoxCollaborationAllowlist`, `BoxCollaborationWhitelistExemptTarget` replaced with `BoxCollaborationAllowlistExemptTarget` (#969) - Dropping Java 7 support (#962) - Downgrading `bouncycastle` libraries to 1.57 (#942) ### New Features and Enhancements: - Add `typeName` to `BoxEvent` that contains name of the event, even if it is not mapped to `BoxEvent.EventType` ([#979](https://github.com/box/box-java-sdk/issues/979)) ([b30f61f](https://github.com/box/box-java-sdk/commit/b30f61f8cc9c02a1fc4cd5eb35469749e1a16558)), closes [#968](https://github.com/box/box-java-sdk/issues/968) - Add new optional `description` parameter to the `retention_policies` endpoint and `start_date_field` to the `retention_policy_assignments endpoint`. ([#967](https://github.com/box/box-java-sdk/issues/967)) ([0aa4ff4](https://github.com/box/box-java-sdk/commit/0aa4ff48a1e035efc9ac6aaa42f18f4c92955b7b)) - Adding `BoxFile#getVersions(String... fields)` to allow users to specify what information they want to extract. Fixes [#946](https://github.com/box/box-java-sdk/issues/946). ([#947](https://github.com/box/box-java-sdk/issues/947)) ([a2eb638](https://github.com/box/box-java-sdk/commit/a2eb63896606a6c00ccee6bd9745f4c51f8d89a2)) - Missing `eventTypes` from `BoxAPI` Documents. Fixes [#974](https://github.com/box/box-java-sdk/issues/974) ([#975](https://github.com/box/box-java-sdk/issues/975)) ([2c69360](https://github.com/box/box-java-sdk/commit/2c69360e80b1bdd6213933cf2f4da195d52c92d4)) - Removed deprecated API `BoxCollaborationWhitelist` replaced with `BoxCollaborationAllowlist`, `BoxCollaborationWhitelistExemptTarget` replaced with `BoxCollaborationAllowlistExemptTarget` ([#969](https://github.com/box/box-java-sdk/issues/969)) ([2fd4d6f](https://github.com/box/box-java-sdk/commit/2fd4d6f884410c8884c4c038687bfc8f32837b55)) ### Bug Fixes: - Changed `BoxFileVersion` class and removed `fileVersion` field ([#978](https://github.com/box/box-java-sdk/issues/978)) ([8c39451](https://github.com/box/box-java-sdk/commit/8c3945167581400043a070c2f6906ef05d3d7b85)) - Changed SDK loggers name to `"com.box.sdk"`, fixes [#638](https://github.com/box/box-java-sdk/issues/638) ([#950](https://github.com/box/box-java-sdk/issues/950)) ([443c230](https://github.com/box/box-java-sdk/commit/443c23085e55bbcaa1524c5b9e1bf852a1e2a1ce)) - Date parsing error when `BoxSignRequestPrefillTag` created with date value. ([#970](https://github.com/box/box-java-sdk/issues/970)) ([cc2c8da](https://github.com/box/box-java-sdk/commit/cc2c8da9ea7d066ae2c247c2de5ac8b8bbba9b99)) - Fix sending limit param in `EventLog` ([#977](https://github.com/box/box-java-sdk/issues/977)) ([96bdccc](https://github.com/box/box-java-sdk/commit/96bdccc9ca40ed43a6028a2b0d055d9d9a8de525)) - Fixed `NullPointerException` when empty metadata used on BoxFile or `BoxFolder` ([#918](https://github.com/box/box-java-sdk/issues/918)) ([#945](https://github.com/box/box-java-sdk/issues/945)) ([68bc3c5](https://github.com/box/box-java-sdk/commit/68bc3c578d760b7239f6d704fed9bb5a834bf52a)) - Fixes issue ([#951](https://github.com/box/box-java-sdk/issues/951)) error when deserialising sign request ([#952](https://github.com/box/box-java-sdk/issues/952)) ([070bdc5](https://github.com/box/box-java-sdk/commit/070bdc56074a1533c41f9085943d09502c79a7f4)) ### Dependency Upgrades: - Dropping Java 7 support ([#962](https://github.com/box/box-java-sdk/issues/962)) ([953ad78](https://github.com/box/box-java-sdk/commit/953ad78ac84833082439d0def1dcc63dc11ac04a)) - Downgrading `bouncycastle` libraries to 1.57 ([#942](https://github.com/box/box-java-sdk/issues/942)) ([26aaed5](https://github.com/box/box-java-sdk/commit/26aaed51fd914eaf2061da735f11830524e4cfe4)) ## [2.58.0] (2021-11-23) ### ⚠ BREAKING CHANGES ### New Features and Enhancements: - SDK support for new GET /events stream_type: admin_logs_streaming ([#938](https://github.com/box/box-java-sdk/pull/938)) - Adding BoxDeveloperEditionAPIConnection#getUserConnection to indicate that we can use this connection for managed users or app users ([#940](https://github.com/box/box-java-sdk/pull/940)) ### Bug Fixes: - Fix for deprecated enums still being used ([#931](https://github.com/box/box-java-sdk/issues/931)) ## [2.57.0] (2021-10-18) ### ⚠ BREAKING CHANGES ### New Features and Enhancements: - Add support for marker-based paging in BoxFolder.getChildren ([#927](https://github.com/box/box-java-sdk/pull/927)) - Upgraded minimal-json to v0.9.5 - Upgraded jose4j to v0.7.9 - Adding Gradle wrapper in version 4.0.1 ([#928](https://github.com/box/box-java-sdk/pull/928)) ### Bug Fixes: - Fix for infinite recursion ([#924](https://github.com/box/box-java-sdk/pull/924)) - Fix unable to set Vanity URL on `BoxSharedLink` for BoxFile and BoxFolder ([#925](https://github.com/box/box-java-sdk/issues/925)) ## [2.56.0] (2021-08-31) ### New Features and Enhancements: - Replace `submaster` GroupMembershipRole with `coadmin`. Replace `MASTER_INVITE_ACCEPT` and `MASTER_INVITE_REJECT` with `ADMIN_INVITE_ACCEPT` and `ADMIN_INVITE_REJECT`. ([#907](https://github.com/box/box-java-sdk/pull/907)) - Add `tracking_codes` to create User API call ([#910](https://github.com/box/box-java-sdk/pull/910)) ### Bug Fixes: - Fix `url` for `BoxFileRequest.Info` object ([#906](https://github.com/box/box-java-sdk/pull/906)) - Attempt to fix thread locking issue on refresh of access token ([#912](https://github.com/box/box-java-sdk/pull/912)) ## [2.55.1] (2021-07-30) ### Bug Fixes: - Restore methods for Execute Metadata Query, which were removed in ([#890](https://github.com/box/box-java-sdk/pull/890)), and mark them as deprecated ([#905](https://github.com/box/box-java-sdk/pull/905)) ## [2.55.0] (2021-07-26) NOTE: Due to the benign nature of the "breaking change" below, we decided NOT to increment the major version for this release. There should be no customer impact due to this change. ### ⚠ BREAKING CHANGES Update execute metadata query to match API response ([#890](https://github.com/box/box-java-sdk/pull/890)) - NOTE: This change removes a method without deprecating it. It was not possible to use the method correctly at all, because the underlying service no longer supported it. ### New Features and Enhancements: - Remove or deprecate insensitive language ([#889])([https://github.com/box/box-java-sdk/pull/889](https://github.com/box/box-java-sdk/pull/889)) - Add support for `is_external_collab_restricted` parameter for User ([#896](https://github.com/box/box-java-sdk/pull/896)) - Add configurable permissions support for `GroupMembership` ([#897](https://github.com/box/box-java-sdk/pull/897)) - Add `SHIELD_JUSTIFICATION_APPROVAL` event type ([#898](https://github.com/box/box-java-sdk/pull/898)) - Add ability to get files under retention for assignment and file versions under retention for assignment ([#899](https://github.com/box/box-java-sdk/pull/899)) - Add `TASK_UPDATE`, `FILE_VERSION_RESTORE` and `ADVANCED_FOLDER_SETTINGS_UPDATE` event types ([#902](https://github.com/box/box-java-sdk/pull/902)) - Add SignAPI support ([#904](https://github.com/box/box-java-sdk/pull/904)) ### Bug Fixes: - Add setters for `BoxLegalHoldPolicy` ([#885](https://github.com/box/box-java-sdk/pull/885)) - Add setters for `BoxTaskAssignment` ([#886](https://github.com/box/box-java-sdk/pull/886)) - Add setters for Group Membership and Web Links ([#887](https://github.com/box/box-java-sdk/pull/887)) - Add setters for Webhooks ([#888](https://github.com/box/box-java-sdk/pull/888)) - Deprecate `BoxFile.getThumbnail` in favor of `BoxFile.getRepresentationContent` ([#891](https://github.com/box/box-java-sdk/pull/891)) ## [2.54.0] (2021-04-01) ### New Features and Enhancements: - Add file request support ([#869](https://github.com/box/box-java-sdk/pull/869)) ### Bug Fixes: - Fix `BoxWeblink` deserialization ([#881](https://github.com/box/box-java-sdk/pull/881)) ## [2.53.0] (2021-01-08) ### New Features and Enhancements: - Add offset and limit parameters to `BoxFolder.getChildren` ([#861](https://github.com/box/box-java-sdk/pull/861)) ## [2.52.0] (2020-11-24) ### New Features and Enhancements: - Add folder lock functionality ([#856](https://github.com/box/box-java-sdk/pull/856)) - Add support for search param to get shared link items ([#855](https://github.com/box/box-java-sdk/pull/855)) ### Bug Fixes: - Fix bug with updating tracking codes ([#857](https://github.com/box/box-java-sdk/pull/857)) ## [2.51.1] (2020-11-12) ### Bug Fixes: - Fix for cross-enterprise collaborator calls to updateMetadata on files ## [2.51.0] (2020-10-29) ### New Features and Enhancements: - Add support for `copyInstanceOnItemCopy` field for metadata templates ([#850](https://github.com/box/box-java-sdk/pull/850)) - Add support for more fields in `BoxCollaborator.Info` ([#843](https://github.com/box/box-java-sdk/pull/843)) ### Bug Fixes: - Update `getAllGroupsByName()` to use documented parameter ([#851](https://github.com/box/box-java-sdk/pull/851)) ## [2.50.1] (2020-08-20) - Fix bug that occurred when downscoping a token for a Box folder ([#832](https://github.com/box/box-java-sdk/pull/832)) ## [2.50.0] (2020-07-21) - API request creation errors are now retried with the same automatic retry logic as 429 and 5XX response errors ([#828](https://github.com/box/box-java-sdk/pull/828)) ## [2.49.0] (2020-07-17) - Fix bug with setting the unshared at date for a shared link ([#819](https://github.com/box/box-java-sdk/pull/819)) - Add zip functionality ([#825](https://github.com/box/box-java-sdk/pull/825)) - Add `fields` parameter for metadata query ([#826](https://github.com/box/box-java-sdk/pull/826)) ## [2.48.0] (2020-06-23) - Add ability to get groups by name with fields option ([#789](https://github.com/box/box-java-sdk/pull/789)) - Add shared link downscoping ([#785](https://github.com/box/box-java-sdk/pull/785)) - Deprecate the use of float for Metadata values, in preference of the underlying value (double) ([#811](https://github.com/box/box-java-sdk/pull/811)) - Add iterator support for group collaborations ([#813](https://github.com/box/box-java-sdk/pull/813)) - Add ability to set the filename when uploading a new version of a file ([#810](https://github.com/box/box-java-sdk/pull/810)) - Add support for the classification field for Files and Folders ([#809](https://github.com/box/box-java-sdk/pull/809)) - Add support for setting Tracking Codes ([#766](https://github.com/box/box-java-sdk/pull/766)) - Fix issue for `getIsExternallyOwned()` for Files and Folders ([#808](https://github.com/box/box-java-sdk/pull/808)) ## [2.47.0] (2020-04-23) - Add support for the uploader display name field for Files and File Versions ([#791](https://github.com/box/box-java-sdk/pull/791)) - Fix path parameter sanitization ([#797](https://github.com/box/box-java-sdk/pull/797)) ## [2.46.0] (2020-04-09) Fix retry logic ([#787](https://github.com/box/box-java-sdk/pull/787)) - Retry for 400 `invalid_grant` error in authentication requests (Clock Skew) - Honor Retry-After header, if present, by waiting for the time specified in the header before retrying - The concept of setting / getting "Maximum API Requests" has been deprecated in favor of "Maximum API Retries" to more clearly show the number of times a request will be retried after an error response is received. Add ability to set expiration date for a collaboration ([#788](https://github.com/box/box-java-sdk/pull/788)) Add path parameter sanitization ([#790](https://github.com/box/box-java-sdk/pull/790)) ## [2.45.0] (2020-04-02) - Add preflight check before chunked uploads ([#782](https://github.com/box/box-java-sdk/pull/782)) - Check that part was successfully uploaded for large file uploads before retrying for 500 errors ([#781](https://github.com/box/box-java-sdk/pull/781)) - Fix bug with premature disconnect when renaming files and weblinks ([#779](https://github.com/box/box-java-sdk/pull/779)) - Add metadata to each item returned by a metadata query ([#778](https://github.com/box/box-java-sdk/pull/778)) ## [2.44.1] (2020-02-13) - Fix formatting bug for Java Logger - Improve date / time parsing for responses ## [2.44.0] (2020-01-21) - Fix Authentication Request Retries ## [2.43.0] (2019-12-20) - Throw exceptions for setMetadata on Files and Folders for non-409 errors ## [2.42.0] (2019-12-17) - Added Metadata Query support - Added marker based pagination for get users methods ## [2.41.0] (2019-10-24) - Added enum action option for completed in Box Task class. ## [2.40.0] (2019-10-24) - General doc changes. ## [2.39.0] (2019-10-17) - Deprecated Batch API functionality. - Added support for [Task completion_rule](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxFile.java#L249) ## [2.38.0] (2019-09-19) - Added missing fields for File Version: trashed_by, restored_at, purged_at, purged_by. - Added support for [chunked uploads with file attributes](https://github.com/box/box-java-sdk/blob/main/doc/files.md#upload-a-large-file-in-chunks-including-attributes). ## [2.37.0] (2019-08-22) Added support for replace in multi-select metadata for [files](https://github.com/box/box-java-sdk/blob/main/doc/files.md#update-metadata) and for [folders](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#update-metadata) - Improved getting started with JWT authentication docs that can be found [here](https://github.com/box/box-java-sdk/blob/main/doc/authentication.md#server-authentication-with-jwt) ## [2.36.0] (2019-08-01) - Added support for [removing shared link](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxItem.java#L413) and fixed an issue with setting null for shared link field on BoxItem. - Added support for additional fields for Box files, folders, and web links. ## [2.35.0] (2019-07-18) - Added support for retrieving [is_external_only field](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxFile.java#L1668) for Box Files and Folders. ## [2.34.0] (2019-06-06) Added support for retrieving a [string type action for tasks](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxTask.java#L281). Please use getActionType() going forward instead of the deprecated getAction(). ## [2.33.0] (2019-05-23) - Added support for [setting can_owners_invite field](https://github.com/box/box-java-sdk/blob/1ed10d7a457e44b863ec1c9b1d0d1408fb55e1e5/src/main/java/com/box/sdk/BoxFolder.java#L1272) Thank you @Band-Aid for you pull request! Greatly Appreciated. - Fixed a bug where chunked upload was not populating the correct part size for upload part. ## [2.32.0] (2019-04-25) - Added support [setting metadata](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#set-metadata). ## [2.31.0] (2019-04-11) - Added support for [sorting folder items](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#get-a-folders-items) retrieved from a folder by ascending or descending order. ## [2.30.1] (2019-04-08) - Fixed a bug where the SDK could throw when parsing JSON containing dates using the Zulu timezone format ## [2.30.0] (2019-04-04) - Added `action_by` field to enterprise events stream. ## [2.29.0] (2019-04-01) - Added support for [sorting results returned from Box Search](https://github.com/box/box-java-sdk/blob/main/doc/search.md#search-1) - Added ability to [attach a file description upon file upload](https://github.com/box/box-java-sdk/blob/main/doc/files.md#upload-a-file) ## [2.28.1] (2019-03-07) - Fixed a bug where BoxMetadataCascadePolicy.forceApply() would not return correctly. ## [2.28.0] (2019-02-21) - Added ability for user to [retrieve an avatar](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.html#getAvatar--)) for a specified user. ## [2.27.0] (2019-01-31) - Added support for Metadata Classification for [File](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#setClassification-java.lang.String...-) and [Folder](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#setClassification-java.lang.String...-) ## [2.26.0] (2019-01-17) - Added [invite_email](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxCollaboration.java#L277) field to collaboration object. - Added [is_collaboration_restricted_to_enterprise](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxFolder.java#L1104) field to folder object. - Added [status](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxTaskAssignment.java#L196) field to task assignment object. - Added ability to retrieve fields for [`BoxFile#getTasks()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFile.html#getTasks-java.lang.String...-) - Fixed bug where offset based paging would not return correctly. ## [2.25.1] (2019-01-03) - Upgraded dependencies: jose4j to v0.5.5, and bouncycastle to v1.60 ## [2.25.0] (2018-12-13) - Added functionality to allow [content streaming to Box through outputstream](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxFolder.html#uploadFile-com.box.UploadFileCallback-java.lang.String-). Thank you @gajarajkalburgi for the pr! ## [2.24.0] (2018-11-16) - Added `getOptionsObjects()` on `MetadataTemplate.Field` which returns both key and type. - Added functionality for [`BoxItem#getType()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxItem.html#getType--) for BoxItem. - Added functionality for [`BoxAPIConnection#BoxGlobalSettings()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#setConnectTimeout-java.lang.String-) and [`BoxAPIConnection#BoxGlobalSettings()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxAPIConnection.html#getConnectTimeout--) as well as getting and reading the timeout for the connection. - Added functionality for [`BoxGlobalSettings#getMaxRequestAttempts()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGlobalSettings.html#getMaxRequestAttempts--) and [`BoxGlobalSettings#setMaxRquestAttempts()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxGlobalSettings.html#setMaxRequestAttempts-java.lang.Integer-) - Fixed a bug where [`BoxLegalHoldPolicy#create()`](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxLegalHoldPolicy.html#create-com.box.BoxAPIConnection-java.lang.String-) was not setting the correct legal hold policy duration. ## [2.23.2] (2018-09-27) - Fixed a bug where the specified headers for batch requests were not being sent. ## [2.23.1] (2018-09-13) - Fixed a bug where too many TCP connections were being opened. Thank you @pmatte1 for implementing this fix! ## [2.23.0] (2018-08-23) - Added support for [Metadata Cascade Policy](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#create-cascade-policy-on-folder) ## [2.22.0] (2018-08-09) - Deprecated the [moveFolderToUser()](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxUser.java#L455) for Box Users. We encourage users to use [transferContent](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxUser.java#L482) going forward because idiomatically it is more correct. ## [2.21.0] (2018-07-05) - Added functionality to allow users to [set passwords on shared links](https://github.com/box/box-java-sdk/pull/623) for Box files, folders, and web links. - Fixed wrong redirect for two links in the `Getting Started` and `Quick Test` section of the README. ## [2.20.2] (2018-06-28) - Fixed a bug where customers had issues with large file uploads because they fail to parse the Retry-After header from the commit response. Reason being headers storage/lookup was case sensitive. ## [2.20.1] (2018-06-04) - Added better exception handling for JSON parse in response exception. - Fixed a bug where uploadNewVersion() was returning an empty object. ## [2.20.0] (2018-05-24) - Fixed a bug where multiple As-User headers could be set. - Added support to [test update](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/Metadata.html#test-java.lang.String-java.util.List-) for multiselect field on metadata ## [2.19.0] (2018-05-10) - Added support for enterprise admins with Box Zones purchased to have support for [Box Storage Policies and Box Storage Policy Assignments](./doc/storage_policy) - Added support to allow users to work with [multiselect metadata](./doc/files.md#get-metadata) - Added `getLogin()` method for the "login" field on the "accessible by" for BoxCollaboration.Info class. ## [2.18.0] (2018-04-30) - Fixed a bug where the the private key password should be passed into `setPrivateKetPassword()` instead of the private key. A big thank you to [breach10ck](https://github.com/breach10ck) for their pull request! - Added an additional check to ensure that the [request properties on the request object is not null in the `toString()` method](https://github.com/box/box-java-sdk/pull/595) - Added support to [fetch the content of the generated representation](./doc/files.md#get-representation-content) after it has been generated - Improved error messages for API response errors to allow for better debugging. ## [2.17.0] (2018-04-10) - Added support for assigning [Retention Policies to Metadata Templates](./doc/retention_policies.md#create-retention-policy-assignment) ## [2.16.1] (2018-03-29) - Added `CONTENT_ACCESS` to event type enum ## [2.16.0] (2018-03-22) - Added support for [user tracking codes](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxUser.Info.html#getTrackingCodes--) on the user object. - Fixed a bug where JWT authentication would fail due to improper date parsing. - Added support for setting custom headers on API connection. This allow for setting [As-User support](./doc/overview.md#as-user) and [suppressing notifications](./doc/overview.md/suppressing-notifications) support. - Changed default JWT expiration window to reduce chances of error. ## [2.15.0] (2018-03-12) - Added support for retrieving a [metadata template by ID](./doc/metadata_template.md#get-by-id) - Added support for allowing the user to [retrieve specific Collaboration fields on a Collaboration object](./doc/collaborations.md#get-a-collaborations-information) ## [2.14.1] (2018-03-01) - Reduced the number of API calls that the `EventStream` makes to fetch new events, which should help users who are running into rate limit issues. - Force support for TLSv1.1 or higher when available to improve the security of connections to the Box API - Add randomized jitter to the exponential backoff algorithm used by the SDK to improve the success rate of retried requests. ## [2.14.0] (2018-02-15) - Added support for getting and setting the `can_view_path` field on a collaboration object. - Added support for getting and setting the `tags` field on files and folders. ## [2.13.0] (2018-02-07) - Fixed an issue where all types of metadata values were being coerced to Strings. This change deprecates `Metadata#get()` in favor of type-specific methods like `Metadata#getFloat()` or a generic `Metadata#getValue()`, which returns a `JsonValue` object that represents any JSON type. See the [file metadata](./doc/files.md#get-metadata) or [folder metadata](./doc/folders.md#get-metadata) documentation for more information. ## [2.12.0] (2018-02-01) - Fixed ability to notify users or groups regarding [file collaboration](https://github.com/box/box-java-sdk/blob/main/doc/files.md#share-a-file) or [folder collaboration](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#share-a-folder) - Added [OAuth2 token creation event types](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxEvent.java#L747) - Added support for [inviting a user to another Box Enterprise](http://opensource.box.com/box-java-sdk/javadoc/com/box/sdk/BoxInvite.html) - Fixed an [OutOfMemory error in large file upload by capping the maximum number of parts that are uploaded concurrently](https://github.com/box/box-java-sdk/pull/543) ## [2.11.0] (2018-01-25) - [uploadLargeFile now returns a BoxFile object](https://github.com/box/box-java-sdk/pull/524) - [Fixed chunked upload for Box Files greater than 2GB](https://github.com/box/box-java-sdk/pull/531) - [Perform modified retry on JWT auth for when the local clock and the Box Server clock are not aligned as well as if the JWT ID has already been consumed](https://github.com/box/box-java-sdk/pull/523) - BoxFolder.search has been deprecated in favor of [BoxSearch.searchRange](https://github.com/box/box-java-sdk/blob/86b82f2be3c57e3b89ae150b5f237d410e2d4900/doc/search.md) ## [2.10.0] (2018-01-11) - [Add optional is_confirmed paramater for adding user email alias](https://github.com/box/box-java-sdk/pull/499) - Added support for [Metadata Template Delete](./doc/metadata_template#delete-a-metadata-template) ## [2.9.0] (2018-01-04) - Added option to pass file [SHA-1 hash for upload integrity](https://github.com/box/box-java-sdk/blob/main/doc/files.md#upload-a-file) - Added support for [Terms of Service](./doc/terms_of_service) endpoint - Fixed missing [webhook triggers](https://github.com/box/box-java-sdk/pull/497) - Fixed missing [event types for events enum](https://github.com/box/box-java-sdk/pull/500) - Added [modified_at timestamp to BoxComment.Info](https://github.com/box/box-java-sdk/pull/499) - Added support for [Collaboration Whitelists](./doc/collaboration_whitelists) endpoint ## [2.8.2] (2017-10-05) - Added additional check for `PrivateKeyInfo` in `BoxDeveloperEditionApiConnection` ## [2.8.1] (2017-10-05) - Added ability to [set connect and read timeout globally](https://github.com/box/box-java-sdk/pull/459) ## [2.8.0] (2017-09-07) - Added method for getting file representations - Changes to Representation object ## [2.7.0] (2017-08-30) - Added support for [Representations](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxFile.java#L445) endpoint ## [2.6.0] (2017-08-28) - Added support for [Batch](https://github.com/box/box-java-sdk/blob/575861fad0b3e67d432b5d5955d1e760b3f6444e/README.md#batchrequestexample) - Added support for [Unified Metadata](./doc/folders#get-metadata-using-unified-metadata-api) ## [2.5.0] (2017-07-28) - Added support for [Recent Items](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxRecents.java#L1) endpoint - Added support [Get All Groups By Name](https://github.com/box/box-java-sdk/blob/a1833950c18139fd9cbb4d8ee61d310c7bbedadf/src/main/java/com/box/sdk/BoxGroup.java#L143) endpoint - Added support for [Token Exchange](https://github.com/box/box-java-sdk/blob/main/src/main/java/com/box/sdk/BoxAPIConnection.java#L634) ## [2.4.0] (2017-05-02) - Support for multiput upload. New methods in BoxFolder and BoxFile support multiput upload for better performance and reliability for large files. - Single file collaborations. The BoxFile class now supports sharing individual files. - Automatic configuration for JWT auth. The Box Developer console now lets you download a JSON file of your JWT app configuration settings. You can import this file into the Java SDK to easily configure your app. ## [2.3.0] (2017-01-12) New API Endpoints: [Legal Holds](https://github.com/box/box-java-sdk/blob/main/doc/legal_holds.md) [Retention Policies](https://github.com/box/box-java-sdk/blob/main/doc/retention_policies.md) [Create Metadata Template](https://github.com/box/box-java-sdk/blob/main/doc/metadata_template.md#create-metadata-template) [Get All Metadata on File](https://github.com/box/box-java-sdk/blob/main/doc/files.md#get-all-metadata-on-file) [Get All Metadata on Folder](https://github.com/box/box-java-sdk/blob/main/doc/folders.md#get-all-metadata-on-folder) [Get Enterprise Metadata Templates](https://github.com/box/box-java-sdk/blob/main/doc/metadata_template.md#get-enterprise-metadata-templates) [Update Group](https://github.com/box/box-java-sdk/blob/main/doc/groups.md#update-a-group) [Watermarking](https://github.com/box/box-java-sdk/blob/main/doc/watermarking.md) [Webhooks V2](https://github.com/box/box-java-sdk/blob/main/doc/webhooks.md) [WebLinks](https://github.com/box/box-java-sdk/blob/main/doc/weblinks.md) [Collections](https://github.com/box/box-java-sdk/blob/main/doc/collections.md) [BoxGroupMembership with for Paging](https://github.com/box/box-java-sdk/blob/main/doc/groups.md) [Enterprise Device Pins](https://github.com/box/box-java-sdk/blob/86b82f2be3c57e3b89ae150b5f237d410e2d4900/doc/devices.md) New Features: Transactional Authentication. Support for Box's new Transactional Auth APIs. Upload file versions with SHA1. A file's SHA1 can be passed in to BoxFile.uploadVersion(...) when uploading new versions. Get effective_access for shared links. The effective_access field is accessible through BoxSharedLink. getEffectiveAccess(). Added additional Event Types. The TASK_ASSIGNMENT_COMPLETE, TASK_ASSIGNMENT_UPDATE, TASK_CREATE, COMMENT_DELETE types are now included in the BoxEvent class. ## [2.1.0] (2016-02-22) This release includes improvements to token caching for App Users and support for additional API endpoints. New Features: ``` - App Users token caching. A token cache can now be specified in BoxDeveloperEditionAPIConnection. This allows for improved performance when using App Users authentication. - Support for retrieving download URLs. The BoxFile.getDownloadURL() method allows for retrieving a direct download URL to a file. - File thumbnails. The BoxFile.getThumbnail() method allows for downloading the [Thumbnail](https://github.com/box/box-java-sdk/blob/main/doc/files.md#get-thumbnail) for a file. ``` Bug Fixes: ``` - Getting info for a file could crash when there's no preview. Previously, an exception would be thrown if BoxFile.getInfo (BoxFile.ALL_FIELDS) was called and the file didn't have a preview available. ``` --- ## Untitled *Type: page* Migration guide for versions 3.x.x -> 4.x.x Configuration changes BoxDeveloperEditionAPIConnection MaxRequestAttempts Removed deprecated… # Migration guide for versions 3.x.x -> 4.x.x [Configuration changes](#configuration-changes) - [BoxDeveloperEditionAPIConnection](#boxdevelopereditionapiconnection) - [MaxRequestAttempts](#maxrequestattempts) [Removed deprecated methods and classes](#removed-deprecated-methods-and-classes) [Replaced methods and classes](#replaced-methods-and-classes) - [Shared links](#shared-links) - [Retention Policies](#retention-policies) - [Enterprise Events](#enterprise-events) - [Search](#search) - [BoxGroup](#boxgroup) - [MetadataTemplate](#metadatatemplate) - [Others](#others) The most important change this release includes is the replacement of the HTTP library from a native one to OkHttp which allows SDK to: - Support the HTTP2 version of the HTTP protocol. - Support proxies that do not use only basic authentication method. For details on creating custom proxy authenticators and an example of NTLM proxy authentication, see [here](https://github.com/box/box-java-sdk/blob/kb/ok-http/doc/configuration.md#custom-proxy-authenticator). # Configuration changes ## BoxDeveloperEditionAPIConnection Replaced `com.box.sdk.BoxDeveloperEditionAPIConnection#getAppUserConnection`with `com.box.sdk.BoxDeveloperEditionAPIConnection#getUserConnection`. ### Example To create `com.box.sdk.BoxDeveloperEditionAPIConnection` configured for user access: ``` Reader reader = new FileReader("some-config.json"); BoxConfig boxConfig = BoxConfig.readFrom(reader); BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getUserConnection(boxConfig); ``` ### Documentation You can read more on BoxDeveloperEditionAPIConnection [here](../../README.md#boxdevelopereditionapiconnectionasenterpriseuser). ## MaxRequestAttempts The `MaxRequestAttempts` are removed from `com.box.sdk.BoxGlobalSettings` and replaced with `MaxRetryAttempts`. However, if you have API connection stored with the deprecated `MaxRequestAttempts` value it will be restored into `MaxRetryAttempts`. # Removed deprecated methods and classes 1. `com.box.sdk.BoxAPIRequest.BoxAPIRequest(java.net.URL, java.lang.String)` - use constuctor that accepts `com.box.sdk.BoxAPIConnection`. 2. `com.box.sdk.BoxUser.moveFolderToUser` - this method is removed as this operation is not allowed by API. You can only transfer root folder to another user using `com.box.sdk.BoxUser.transferContent`. # Replaced methods and classes ## Getting thumbnail Method `com.box.sdk.BoxFile.getThumbnail` was removed. To get any file representation use `com.box.sdk.BoxFile.getRepresentationContent(java.lang.String, java.io.OutputStream)` or `com.box.sdk.BoxFile.getRepresentationContent(java.lang.String, java.lang.String, java.io.OutputStream)`. ### Example To read the PDF representation of file with id `12345`: ``` ByteArrayOutputStream output = new ByteArrayOutputStream(); BoxFile file = new BoxFile(api, "12345"); file.getRepresentationContent("[pdf]", output); ``` ### Documentation For more details on getting representation content go [here](../files.md#get-representation-content). ## Shared links Removed variant of methods that do not use `com.box.sdk.sharedlink.BoxSharedLinkRequest`: 1. `com.box.sdk.BoxItem.createSharedLink` 2. `com.box.sdk.BoxFile.createSharedLink` 3. `com.box.sdk.BoxFolder.createSharedLink` 4. `com.box.sdk.BoxWebLink.createSharedLink` ### Example If you want to create a shared link, first create `com.box.sdk.sharedlink.BoxSharedLinkRequest`: ``` Date unsharedDate = ... BoxFile file = new BoxFile(api, "id"); BoxSharedLinkRequest sharedLinkRequest = new BoxSharedLinkRequest() .access(OPEN) .permissions(true, true) .unsharedDate(unsharedDate); BoxSharedLink sharedLink = file.createSharedLink(sharedLinkRequest); ``` ### Documentation For details on shared links, see: 1. [Create shared link for file](../files.md#create-a-shared-link) 2. [Create shared link for folder](../folders.md#create-a-shared-link) 3. [Create shared link for web link](../weblinks.md#create-shared-link) ## Retention Policies Removed variant of methods that were not using `com.box.sdk.BoxRetentionPolicy.BoxRetentionPolicyAction`: 1. `com.box.sdk.BoxRetentionPolicy.createFinitePolicy` ### Example If you want to create a finite retention policy: ``` BoxRetentionPolicy.createFinitePolicy(api, "My 30 days retention policy", 30, BoxRetentionPolicyAction.PermanentlyDelete); ``` ### Documentation You can read more on creating retention policies [here](../retention_policies.md#create-retention-policy). ## Enterprise Events Removed variant of methods that were not using `com.box.sdk.EnterpriseEventsRequest`: 1. `com.box.sdk.EventLog.getEnterpriseEvents` ### Example If you want to get historical enterprise events, first create `com.box.sdk.EnterpriseEventsRequest`: ``` EnterpriseEventsRequest request = new EnterpriseEventsRequest().limit(20); EventLog.getEnterpriseEvents(api, request1); // process recieved events ``` ### Documentation You can read more on getting enterprise events [here](../events.md#enterprise--admin--events). ## Search Method `com.box.sdk.BoxFolder.search` is replaced with class `com.box.sdk.BoxSearch`. ### Example If you would like to find the first 10 files matching "taxes": ``` long offsetValue = 0; long limitValue = 10; BoxSearchParameters searchParams = new BoxSearchParameters(); searchParams.setQuery("taxes"); searchParams.setType("file"); BoxSearch boxSearch = new BoxSearch(api); boxSearch.searchRange(offsetValue, limitValue, searchParams); ``` ### Documentation You can read more on search [here](https://developer.box.com/4676a077454d7307989f4ff8b48c06db/search.md). ## BoxGroup All methods that use `com.box.sdk.BoxGroupMembership.Role` were removed. Use ones that use `com.box.sdk.BoxGroupMembership.GroupRole`. Also `com.box.sdk.BoxGroupMembership.Role` was replaced with `com.box.sdk.BoxGroupMembership.GroupRole`. ### Example To add a new member to a group with specific role: ``` BoxUser user = ... BoxGroup boxGroup = new BoxGroup(api, "group_id"); boxGroup.addMembership(user, BoxGroupMembership.GroupRole.ADMIN); ``` To get membership role use `com.box.sdk.BoxGroupMembership.Info.getGroupRole`: ``` BoxGroupMembership membership = new BoxGroupMembership(api, "membership_id"); membership.getInfo().getGroupRole(); ``` To change membership role use `com.box.sdk.BoxGroupMembership.Info.setGroupRole`: ``` BoxGroupMembership membership = new BoxGroupMembership(api, "membership_id"); BoxGroupMembership.Info membershipInfo = membership.getInfo(); membershipInfo.setGroupRole(BoxGroupMembership.GroupRole.MEMBER); membership.updateInfo(membershipInfo); ``` ### Documentation You can read more on groups [here](https://developer.box.com/a0c1617a72414a043041fde8403ca480/groups.md). ## MetadataTemplate In `com.box.sdk.MetadataTemplate` methods that do not use `com.box.sdk.MetadataQuery` were removed. ### Example To execute a metadata query first create `com.box.sdk.MetadataQuery` instance. ``` MetadataQuery mQuery = new MetadataQuery("enterprise_341532.test"); mQuery.setQuery("testfield = :arg"); mQuery.setAncestorFolderId("0"); mQuery.setOrderBy( MetadataQuery.OrderBy.ascending("primarySortKey"), MetadataQuery.OrderBy.ascending("secondarySortKey") ); mQuery.addParameter("arg", "test"); mQuery.setFields("metadata.enterprise_341532.test.customField"); MetadataTemplate.executeMetadataQuery(api, mQuery); ``` ### Documentation You can read more on how to execute metadata query [here](../metadata_template.md#execute-metadata-query). ## Others | Old | New | | --- | --- | | com.box.sdk.BoxEvent.getType | com.box.sdk.BoxEvent.getEventType | | com.box.sdk.BoxEvent.Type | com.box.sdk.BoxEvent.EventType | | com.box.sdk.BoxFile.uploadVersion | com.box.sdk.BoxFile.uploadNewVersion | | com.box.sdk.BoxGlobalSettings.getMaxRequestAttempts | com.box.sdk.BoxGlobalSettings.getMaxRetryAttempts | | com.box.sdk.BoxGlobalSettings.setMaxRequestAttempts | com.box.sdk.BoxGlobalSettings.setMaxRetryAttempts | | com.box.sdk.BoxTask.Info.getAction | com.box.sdk.BoxTask.Info.getTaskType | --- ## Untitled *Type: page* Integration Tests Running integration tests locally Create Platform Application To run integration tests locally you will need a Custom App… # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created at [https://cloud.app.box.com/developers/console](https://cloud.app.box.com/developers/console) with `Server Authentication (with JWT)` selected as authentication method. Once created you can edit properties of the application. In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. In section `Advanced Features` enable `Make API calls using the as-user header` and `Generate user access tokens`. Now select `Authorization` and submit application to be reviewed by account admin. Next part is to obtain application settings. Select `Configuration` tab and in the bottom in the section `App Settings` download them as Json. ### Export configuration You will need to create environment variables in your system or IDE: - JAVA_COLLABORATOR_ID - you can find this in `General Settings` tab as `Collaborators` - JAVA_COLLABORATOR - you can find this in `General Settings` tab in field `User ID` - JAVA_ENTERPRISE_ID - you can find this in `General Settings` tab in field `Enterprise ID` - JAVA_JWT_CONFIG - contains Base64 of your configuration file. You can generate this in command line. On Linux/Mac OS you can use `base64 -i path_to_json_file`. ### Running Tests You can run tests from command line: ``` ./gradlew integrationTest ``` just remember that you need environment variables exported in previous step to be accessible. ## Useful help classes ### BoxApiProvider To obtain new API connection configured with provided JWT configuration use `BoxApiProvider` ``` BoxAPIConnection api = BoxApiProvider.jwtApiForServiceAccount(); ``` ### UniqueTestFolder `UniqueTestFolder` contains method that can help setup and remove unique folder for tests and upload files. To use new unique folder: ``` UniqueTestFolder.setupUniqeFolder(); // this will create a new test folder that can be used in tests UniqueTestFolder.getUniqueFolder(api); // this will retrieve unique folder UniqueTestFolder.removeUniqueFolder(); // this will remove unique folder with all subfolders and files ``` To upload files to root of the unique folder: ``` // to upload file with specified content BoxFile fileWithSpecifiedContent = UniqueTestFolder.uploadFileToUniqueFolder(api, "File Name", "Your content"); // to upload a file with some content BoxFile fileWithSomeContent = UniqueTestFolder.uploadFileToUniqueFolderWithSomeContent(api, "File Name"); ``` You can also upload file to some specified folder: ``` BoxFolder destinationFolder = UniqueTestFolder.getUniqueFolder(api); // obtain folder to upload file to BoxFile fileWithSomeContent = UniqueTestFolder.uploadFileWithSomeContent("File Name", destinationFolder); ``` ### Retry Sometimes API request can take some time to be processed and you might want to retry some logic when error occurs: ``` Retry.retry( () -> { BoxSignRequest signRequestGetByID = new BoxSignRequest(api, "signRequestId"); // do an API call, assert response - if call fails it will be repated BoxSignRequest.Info cancelationIfo = signRequestGetByID.cancel(); }, 5, // how many times retry the call 1000 // how long to wait between calls in miliseconds ); ``` ## Putting this all together Here is a sample test that uses some of the utility classes shown above: ``` public class BoxFolderIT { @BeforeClass public static void setup() { // create unique folder for all tests UniqueTestFolder.setupUniqeFolder(); } @AfterClass public static void tearDown() { // remove unique folder after all tests run UniqueTestFolder.removeUniqueFolder(); } @Test public void creatingAndDeletingFolderSucceeds() { // given BoxAPIConnection api = BoxApiProvider.jwtApiForServiceAccount(); BoxFolder rootFolder = UniqueTestFolder.getUniqueFolder(api); // expect new folder can be found // create subfolder in unique test folder BoxFolder childFolder = rootFolder.createFolder("My Folder").getResource(); assertThat(rootFolder, hasItem(Matchers.<BoxItem.Info>hasProperty("ID", equalTo(childFolder.getID())))); // expect folder cannot be found after deletion childFolder.delete(false); assertThat(rootFolder, not(hasItem(Matchers.<BoxItem.Info>hasProperty("ID", equalTo(childFolder.getID()))))); } } ``` --- ## Untitled *Type: page* Box Java SDK Project Status Platform License Build main Coverage The Box Java SDK for interacting with the Box Content API. Latest Release… # Box Java SDK [](http://opensource.box.com/badges) [](https://raw.githubusercontent.com/box/box-java-sdk/main/LICENSE) [](https://github.com/box/box-java-sdk/actions/workflows/build-main.yml) [](https://coveralls.io/github/box/box-java-sdk?branch=main) The Box Java SDK for interacting with the [Box Content API](https://developers.box.com/docs/). ## Latest Release Latest release can be found [here](https://github.com/box/box-java-sdk/tree/v4.16.3). ## Upgrades You can read about how to migrate to the 4 version [here](doc/upgrades/3.x.x%20to%204.x.x.md). ## Versions We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. See [version strategy](https://developer.box.com/27a720aa01575cc19988821a8bfea27a/VERSIONS.md) for details which is effective from 30 July 2022. ### Supported Version Only the current MAJOR version of SDK is supported. New features, functionality, bug fixes, and security updates will only be added to the current MAJOR version. A current release is on the leading edge of our SDK development, and is intended for customers who are in active development and want the latest and greatest features. Instead of stating a release date for a new feature, we set a fixed minor or patch release cadence of maximum 2-3 months (while we may release more often). At the same time, there is no schedule for major or breaking release. Instead, we will communicate one quarter in advance the upcoming breaking change to allow customers to plan for the upgrade. We always recommend that all users run the latest available minor release for whatever major version is in use. We highly recommend upgrading to the latest SDK major release at the earliest convenient time and before the EOL date. ### Version schedule | Version | Supported Environments | State | First Release | EOL/Terminated | | --- | --- | --- | --- | --- | | 4 | Java 8 and up | Supported | 17 Jan 2023 | TBD | | 3 | Java 8 and up | EOL | 17 Jan 2022 | 17 Jan 2023 | | 2 | | EOL | 07 Jan 2016 | 17 Jan 2022 | | 1 | | EOL | 15 Apr 2015 | 07 Jan 2016 | ## Getting Started Getting Started Docs: [https://developer.box.com/guides/tooling/sdks/java/](https://developer.box.com/guides/tooling/sdks/java/) API Reference: [https://developer.box.com/reference/](https://developer.box.com/reference/) ## JVM The SDK can be obtained by adding it as a [maven dependency](http://opensource.box.com/box-java-sdk/), cloning the source into your project, or by downloading one of the precompiled JARs from the [releases page on GitHub](https://github.com/box/box-java-sdk/releases). If you are developing application for Android visit our [Android guide](https://developer.box.com/a31234172e176f050227bd567f34bbaa/android.md) **IF YOU USE THE JAR, you'll also need to include several dependencies:** [minimal-json v0.9.5](https://github.com/ralfstx/minimal-json) Maven: `com.eclipsesource.minimal-json:minimal-json:0.9.5` [jose4j v0.9.4](https://bitbucket.org/b_c/jose4j/wiki/Home) Maven: `org.bitbucket.b_c:jose4j:0.9.4` [bouncycastle bcprov-jdk18on v1.78.1](https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk18on/1.78.1) Maven: `org.bouncycastle:bcprov-jdk18on:1.78.1` [bouncycastle bcpkix-jdk18on v1.78.1](https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk18on/1.78.1) Maven: `org.bouncycastle:bcpkix-jdk18on:1.78.1` [Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 7](http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html) If you don't install this, you'll get an exception about key length or exception about parsing PKCS private key for Box Developer Edition. This is not a Box thing, this is a U.S. Government requirement concerning strong encryption. The listed jar is for Oracle JRE. There might be other similar JARs for different JRE versions like the one below for IBM JDK [Java Cryptography Extension for IBM JDK](https://www14.software.ibm.com/webapp/iwm/web/preLogin.do?source=jcesdk) [okhttp v4.12.0](https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/4.12.0) Maven: `com.squareup.okhttp3:okhttp:4.12.0` [okio-jvm v3.2.0](https://mvnrepository.com/artifact/com.squareup.okio/okio-jvm/3.2.0) Maven: `com.squareup.okio:okio-jvm:3.2.0` [kotlin-stdlib v1.6.20](https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib/1.6.20) Maven: `org.jetbrains.kotlin:kotlin-stdlib:1.6.20` [kotlin-stdlib-common v1.6.20](https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-common/1.6.20) Maven: `org.jetbrains.kotlin:kotlin-stdlib-common:1.6.20` An app has to be authorized by the admin of the enterprise before these tests. It's always good to begin with the [Getting Started Section](https://developer.box.com/docs/setting-up-a-jwt-app) at Box's developer website. ## Android If you are developing application for Android visit our [Android guide](https://developer.box.com/a31234172e176f050227bd567f34bbaa/android.md). ## Box Java SDK and other frameworks Box Java SDK utilizes the OkHttp client as its underlying component. This client is widely adopted by various frameworks, which can occasionally result in issues. We recommend considering library upgrades or excluding OkHttp from those frameworks or the software development kit (SDK) to determine if that resolves the problems. Typically, it is advisable to search for any reports or instances where others encountered similar issues when using the specific framework alongside an external OkHttp client. ## Quick Test **Following things work only if the app has been configured and authorized as mentioned [here](https://developer.box.com/docs/setting-up-a-jwt-app)** Here is a simple example of how to authenticate with the API using a developer token and then print the ID and name of each item in your root folder. ``` BoxAPIConnection api = new BoxAPIConnection("developer-token"); BoxFolder rootFolder = BoxFolder.getRootFolder(api); for (BoxItem.Info itemInfo : rootFolder) { System.out.format("[%s] %s\n", itemInfo.getID(), itemInfo.getName()); } ``` For more details on how to get started, check out the [overview guide](https://developer.box.com/7b374e99189519aca65b064deffbf92d/overview.md). It has a short explanation of how the SDK works and how you can get started using it. ### Sample Projects Three sample projects can be found in `src/example`. #### Main This project will output your name and a list of the files and folders in your root directory. To run the project, first provide a developer token in `src/example/java/com/box/sdk/example/Main.java`. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/services). ``` public final class Main { private static final String DEVELOPER_TOKEN = "<YOUR_DEVELOPER_TOKEN>"; // ... } ``` Then just invoke `gradle runExample` to run the Main example! ### Other projects Below projects need app configurations stored in JSON format in `config.json` file at location `src/example/config/`. This configuration file can be downloaded from your application's `Configuration` tab in the [developer console](https://app.box.com/developers/console) #### CreateAppUser This project will output the user id of enterprise admin and will create a new App User for the enterprise. To run the project, first provide the name of the app user in `src/example/java/com/box/sdk/example/CreateAppUser.java`. ``` public final class CreateAppUser { private static final String APP_USER_NAME = ""; private static final String EXTERNAL_APP_USER_ID = ""; // ... } ``` Then just invoke `gradle runCreateAppUser` to run the CreateAppUser example! Note: The JCE bundled with oracle JRE supports keys upto 128 bit length only. To use larger cryptographic keys, install [JCE Unlimited Strength Jurisdiction Policy Files](http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html). #### AccessAsAppUser This project will retrieve the information of the given App User and will list the files/folders under root folder. To run the project, first provide the Id of the app user in `src/example/java/com/box/sdk/example/CreateAppUser.java`. ``` public final class AccessAsAppUser { private static final String USER_ID = ""; // ... } ``` Then just invoke `gradle runAccessAsAppUser` to run the AccessAsAppUser example! Note: The JCE bundled with oracle JRE supports keys upto 128 bit length only. To use larger cryptographic keys, install [JCE Unlimited Strength Jurisdiction Policy Files](http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html). #### BoxDeveloperEditionAPIConnectionAsEnterpriseUser This example shows how to get tokens for an enterprise user, say admin of the enterprise and do actions on behalf of admin. To run the project, follow below steps Turn on `Enterprise` in `Application Access` section in Developer Console for the app Turn on `Generate User Access Tokens` in `Advanced Features` section in Developer Console for the app Provide the Id of the admin user (or any enterprise user) in `src/example/java/com/box/sdk/example/BoxDeveloperEditionAPIConnectionAsEnterpriseUser.java`. ``` public final class BoxDeveloperEditionAPIConnectionAsEnterpriseUser { private static final String USER_ID = ""; // ... Reader reader = new FileReader("src/example/config/config.json"); BoxConfig boxConfig = BoxConfig.readFrom(reader); IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(10); BoxDeveloperEditionAPIConnection api = new BoxDeveloperEditionAPIConnection( USER_ID, DeveloperEditionEntityType.USER, boxConfig, accessTokenCache ); } ``` ## Compatibility The Box Java SDK is compatible with Java 8 and up. ## Compression Support The SDK supports both gzip and zstd compression for API requests. Compression is handled automatically based on server capabilities. ## Building The SDK uses Gradle for its build system. SDK comes with Gradle wrapper. Running `./gradlew build` from the root of the repository will compile, lint, and test the SDK. ``` $ ./gradlew build ``` The SDK also includes integration tests which make real API calls, and therefore are run separately from unit tests. Integration tests should be run against a test account since they create and delete data. To run the integration tests, remove the `.template` extension from `src/test/config/config.properties.template` and fill in your test account's information. Then run: ``` $ ./gradlew integrationTest ``` ## Documentation You can find guides and tutorials in the `doc` directory. - [BUILD ON BOX PLATFORM](https://developer.box.com/guides/getting-started/) - [Javadocs](http://box.github.io/box-java-sdk/javadoc/com/box/sdk/package-summary.html) - [Overview](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/overview.md) - [Configuration](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/configuration.md) - [Logging](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/logging.md) - [Authentication](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/authentication.md) - [Files](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/files.md) - [Folders](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/folders.md) - [Comments](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/comments.md) - [Collaborations](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/collaborations.md) - [Collaboration Allowlists](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/collaboration_allowlists.md) - [Events](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/events.md) - [Search](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/search.md) - [Users](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/users.md) - [Groups](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/groups.md) - [Tasks](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/tasks.md) - [Trash](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/trash.md) - [Collections](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/collections.md) - [Devices](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/devices.md) - [Retention Policies](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/retention_policies.md) - [Legal Holds Policy](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/legal_holds.md) - [Watermarking](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/watermarking.md) - [Webhooks](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/webhooks.md) - [Web Links](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/weblinks.md) - [Metadata Templates](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/metadata_template.md) - [Classifications](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/classifications.md) - [Recent Items](https://github.com/box/box-java-sdk/blob/v4.16.3/doc/recent_items.md) Javadocs are generated when `gradle javadoc` is run and can be found in `build/doc/javadoc`. ## FIPS 140-2 Compliance To generate a Json Web Signature used for retrieving tokens in the JWT authentication method, the Box Java SDK decrypts an encrypted private key. For this purpose, Box Java SDK uses libraries (`org.bouncycastle:bcpkix-jdk18on:1.77` and `org.bouncycastle:bcprov-jdk18on:1.77`) that are NOT compatible with FIPS 140-2 validated cryptographic library (`org.bouncycastle:bc-fips`). There are two ways of ensuring that decryption operation is FIPS-compiant. 1. You can provide a custom implementation of the `IPrivateKeyDecryptor` interface, which performs the decryption operation using FIPS-certified library of your choice. The interface requires the implementation of just one method: ``` PrivateKey decryptPrivateKey(String encryptedPrivateKey, String passphrase); ``` After implementing the custom decryptor, you need to set your custom decryptor class in the Box Config. Below is an example of setting up a `BoxDeveloperEditionAPIConnection` with a config file and the custom decryptor. ``` Reader reader = new FileReader(JWT_CONFIG_PATH); BoxConfig boxConfig = BoxConfig.readFrom(reader); boxConfig.setPrivateKeyDecryptor(customDecryptor) BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig); ``` 1. Alternative method is to override the Bouncy Castle libraries to the v.1.57 version, which are compatible with the FIPS 140-2 validated cryptographic library (`org.bouncycastle:bc-fips`). NOTE: This solution is not recommended as Bouncy Castle v.1.57 has some moderate vulnerabilities reported against those versions, including: - [CVE-2020-26939](https://github.com/advisories/GHSA-72m5-fvvv-55m6) - Observable Differences in Behavior to Error Inputs in Bouncy Castle - [CVE-2020-15522](https://github.com/advisories/GHSA-6xx3-rg99-gc3p) - Timing based private key exposure in Bouncy Castle Furthermore,using Bouncy Castle v.1.57 may lead to [Bouncycastle BadPaddingException for JWT auth](#bouncycastle-badPaddingException-for-jWT-auth). Gradle example ``` implementation('com.box:box-java-sdk:x.y.z') { exclude group: 'org.bouncycastle', module: 'bcprov-jdk15on' exclude group: 'org.bouncycastle', module: 'bcpkix-jdk15on' } runtimeOnly('org.bouncycastle:bcprov-jdk15on:1.57') runtimeOnly('org.bouncycastle:bcpkix-jdk15on:1.57') ``` Maven example: ``` <dependencies> <dependency> <groupId>com.box</groupId> <artifactId>box-java-sdk</artifactId> <version>x.y.z</version> <scope>compile</scope> <exclusions> <exclusion> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> </exclusion> <exclusion> <groupId>org.bouncycastle</groupId> <artifactId>bcpkix-jdk15on</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.57</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpkix-jdk15on</artifactId> <version>1.57</version> <scope>runtime</scope> </dependency> </dependencies> ``` ### Bouncycastle BadPaddingException for JWT auth As of October 2023, RSA keypairs generated on the Developer Console (refer to the [Generate a keypair guide](https://developer.box.com/guides/authentication/jwt/jwt-setup/#generate-a-keypair-recommended)) are no longer compatible with Bouncy Castle version 1.57, which was utilized in the Box Java SDK up to v4.6.1. Attempting to use a JWT configuration downloaded from the Developer Console results in a `javax.crypto.BadPaddingException: pad block corrupted` error. Prossible solutions: 1. Upgrade to the v4.7.0 of Box Java SDK, which uses newer version of the Bouncy Castle library. (recommended) Manually generate a keypair using OpenSSL version 1.0.x and add the Public Key to the Developer Console. The [manually add keypair guide](https://developer.box.com/guides/authentication/jwt/jwt-setup/#manually-add-keypair) provides assistance in this process. ## Copyright and License Copyright 2019 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- ## Untitled *Type: page* The Box Python SDK is an open source project supported by Box used to interact with the Box API. This is a list of contributors. @Jeff… The Box Python SDK is an open source project supported by [Box](https://box.com) used to interact with the Box API. This is a list of contributors. - [@Jeff-Meadows](https://github.com/Jeff-Meadows) - [@jmoldow](https://github.com/jmoldow) - [@aptxkid](https://github.com/aptxkid) - [@hnguyen08](https://github.com/hnguyen08) - [@potrebic](https://github.com/potrebic) - [@nsundareswaran](https://github.com/nsundareswaran) - [@kelseymorris95](https://github.com/kelseymorris95) - [@sp4x](https://github.com/sp4x) - [@capk1rk](https://github.com/capk1rk) - [@aculler](https://github.com/aculler) - [@ben-reilly](https://github.com/ben-reilly) - [@ab](https://github.com/ab) --- ## Untitled *Type: page* Deprecation notice This version of the Box Python SDK is under maintenance mode, and will be deprecated soon, only critical security updates… # Deprecation notice This version of the Box Python SDK is under maintenance mode, and will be deprecated soon, only critical security updates and bug fixes will be provided. We recommend using the new version Box Python SDK, which can be found at [box/box-python-sdk-gen](https://github.com/box/box-python-sdk-gen) You can find the migration guide [here](https://github.com/box/box-python-sdk-gen/blob/main/migration-guide.md) for transitioning from Box Python SDK v3.x to the new `box-sdk-gen` package. If you have any questions, please create an issue in the new repository or reach out to [Box Developer Support](https://developer.box.com/support/). # Box Python SDK [](http://opensource.box.com/badges) [](http://box-python-sdk.readthedocs.org/en/latest) [](https://github.com/box/box-python-sdk/actions) [](https://pypi.python.org/pypi/boxsdk) [](https://pypi.python.org/pypi/boxsdk) [](https://coveralls.io/github/box/box-python-sdk?branch=main) Getting Started Docs: [https://developer.box.com/guides/tooling/sdks/python/](https://developer.box.com/guides/tooling/sdks/python/) - [Deprecation notice](#deprecation-notice) - [Box Python SDK](#box-python-sdk) - [Installing](#installing) - [Getting Started](#getting-started) [Authorization](#authorization) - [Server-to-Server Auth with JWT](#server-to-server-auth-with-jwt) [Traditional 3-legged OAuth2](#traditional-3-legged-oauth2) - [Get the Authorization URL](#get-the-authorization-url) - [Authenticate (Get Access/Refresh Tokens)](#authenticate-get-accessrefresh-tokens) - [Create an Authenticated Client](#create-an-authenticated-client) - [Instantiate a Client Given an Access and a Refresh Token](#instantiate-a-client-given-an-access-and-a-refresh-token) [Other Auth Options](#other-auth-options) [Usage Documentation](#usage-documentation) - [Making API Calls Manually](#making-api-calls-manually) [Other Client Options](#other-client-options) - [Logging Client](#logging-client) - [Developer Token Client](#developer-token-client) - [Development Client](#development-client) [Customization](#customization) - [Custom Subclasses](#custom-subclasses) [FIPS 140-2 Compliance](#fips-140-2-compliance) [Versions](#versions) - [Supported Version](#supported-version) - [Version schedule](#version-schedule) [Contributing](#contributing) - [Developer Setup](#developer-setup) - [Testing](#testing) [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) [Copyright and License](#copyright-and-license) # Installing ``` pip install boxsdk ``` The current version of the SDK is v3.x --- With this release support for Python 3.5 and earlier (including 2.x) has been dropped. if you're looking for the code or documentation for v1.5.x, please see the 1.5 branch. # Getting Started To get started with the SDK, get a Developer Token from the Configuration page of your app in the Box Developer Console. You can use this token to make test calls for your own Box account. The SDK provides an interactive `DevelopmentClient` that makes it easy to test out the SDK in a REPL. This client will automatically prompt for a new Developer Token when it requires one, and will log HTTP requests and responses to aid in debugging and understanding how the SDK makes API calls. ``` >>> from boxsdk import DevelopmentClient >>> client = DevelopmentClient() Enter developer token: <ENTER DEVELOPER TOKEN HERE> >>> user = client.user().get() GET https://api.box.com/2.0/users/me {'headers': {'Authorization': '---wXyZ', 'User-Agent': 'box-python-sdk-2.0.0', 'X-Box-UA': 'agent=box-python-sdk/2.0.0; env=python/3.6.5'}, 'params': None} "GET https://api.box.com/2.0/users/me" 200 454 {'Date': 'Thu, 01 Nov 2018 23:32:11 GMT', 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Strict-Transport-Security': 'max-age=31536000', 'Cache-Control': 'no-cache, no-store', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'BOX-REQUEST-ID': '0b50luc09ahp56m2jmkla8mgmh2', 'Age': '0'} {'address': '', 'avatar_url': 'https://cloud.app.box.com/api/avatar/large/123456789', 'created_at': '2012-06-07T11:14:50-07:00', 'id': '123456789', 'job_title': '', 'language': 'en', 'login': 'user@example.com', 'max_upload_size': 16106127360, 'modified_at': '2018-10-30T17:01:27-07:00', 'name': 'Example User', 'phone': '', 'space_amount': 1000000000000000.0, 'space_used': 14330018065, 'status': 'active', 'timezone': 'America/Los_Angeles', 'type': 'user'} >>> print(f'The current user ID is {user.id}') The current user ID is 123456789 ``` Outside of a REPL, you can initialize a new `Client` with just the Developer Token to get started. ``` from boxsdk import OAuth2, Client auth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', access_token='YOUR_DEVELOPER_TOKEN', ) client = Client(auth) user = client.user().get() print(f'The current user ID is {user.id}') ``` # Authorization The Box API uses OAuth2 for auth. The SDK makes it relatively painless to work with OAuth2 tokens. ## Server-to-Server Auth with JWT The Python SDK supports your JWT Authentication applications. Authenticating with a JWT requires some extra dependencies. To get them, simply ``` pip install "boxsdk[jwt]" ``` Instead of instantiating your `Client` with an instance of `OAuth2`, instead use an instance of `JWTAuth`. ``` from boxsdk import JWTAuth from boxsdk import Client auth = JWTAuth( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', enterprise_id='YOUR_ENTERPRISE_ID', jwt_key_id='YOUR_JWT_KEY_ID', rsa_private_key_file_sys_path='CERT.PEM', rsa_private_key_passphrase='PASSPHRASE', ) access_token = auth.authenticate_instance() client = Client(auth) ``` This client is able to create application users: ``` ned_stark_user = client.create_user('Ned Stark') ``` These users can then be authenticated: ``` ned_auth = JWTAuth( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', user=ned_stark_user, jwt_key_id='YOUR_JWT_KEY_ID', rsa_private_key_file_sys_path='CERT.PEM', rsa_private_key_passphrase='PASSPHRASE' ) ned_auth.authenticate_user() ned_client = Client(ned_auth) ``` Requests made with `ned_client` (or objects returned from `ned_client`'s methods) will be performed on behalf of the newly created app user. ## Traditional 3-legged OAuth2 ### Get the Authorization URL ``` from boxsdk import OAuth2 oauth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', store_tokens=your_store_tokens_callback_method, ) auth_url, csrf_token = oauth.get_authorization_url('http://YOUR_REDIRECT_URL') ``` store_tokens is a callback used to store the access token and refresh token. You might want to define something like this: ``` def store_tokens(access_token, refresh_token): # store the tokens at secure storage (e.g. Keychain) ``` The SDK will keep the tokens in memory for the duration of the Python script run, so you don't always need to pass store_tokens. ### Authenticate (Get Access/Refresh Tokens) If you navigate the user to the auth_url, the user will eventually get redirected to [http://YOUR_REDIRECT_URL?code=YOUR_AUTH_CODE](http://YOUR_REDIRECT_URL?code=YOUR_AUTH_CODE). After getting the code, you will be able to use the code to exchange for an access token and refresh token. The SDK handles all the work for you; all you need to do is run: ``` # Make sure that the csrf token you get from the `state` parameter # in the final redirect URI is the same token you get from the # get_authorization_url method. assert 'THE_CSRF_TOKEN_YOU_GOT' == csrf_token access_token, refresh_token = oauth.authenticate('YOUR_AUTH_CODE') ``` ### Create an Authenticated Client ``` from boxsdk import Client client = Client(oauth) ``` And that's it! You can start using the client to do all kinds of cool stuff and the SDK will handle the token refresh for you automatically. ### Instantiate a Client Given an Access and a Refresh Token Alternatively, you can instantiate an OAuth2 object with the access token and refresh token. Once you have an oauth object you can pass that into the Client object to instantiate a client and begin making calls. ``` from boxsdk import Client, OAuth2 oauth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', access_token='ACCESS_TOKEN', refresh_token='REFRESH_TOKEN', ) client = Client(oauth) user = client.user().get() ``` This will retrieve the current user! From here you can use the client you created to start making calls. ## Other Auth Options For advanced uses of the SDK, three additional auth classes are provided: `CooperativelyManagedOAuth2`: Allows multiple auth instances to share tokens. `RemoteOAuth2`: Allows use of the SDK on clients without access to your application's client secret. Instead, you provide a `retrieve_access_token` callback. That callback should perform the token refresh, perhaps on your server that does have access to the client secret. `RedisManagedOAuth2`: Stores access and refresh tokens in Redis. This allows multiple processes (possibly spanning multiple machines) to share access tokens while synchronizing token refresh. This could be useful for a multiprocess web server, for example. # Usage Documentation Full documentation of the available functionality with example code is available in the SDK documentation pages, and there is also method-level documentation available on [ReadTheDocs](https://box-python-sdk.readthedocs.io/en/stable/index.html). ## Making API Calls Manually The Box API is continually evolving. As such, there are API endpoints available that are not specifically supported by the SDK. You can still use these endpoints by using the `make_request` method of the `Client`. ``` # https://developer.box.com/en/reference/get-metadata-templates-id/ # Returns a Python dictionary containing the result of the API request json_response = client.make_request( 'GET', client.get_url('metadata_templates', 'enterprise', 'customer', 'schema'), ).json() ``` `make_request()` takes two parameters: - `method` - an HTTP verb like `GET` or `POST` - `url` - the URL of the requested API endpoint The `Client` class and Box objects have a `get_url` method. Pass it an endpoint to get the correct URL for use with that object and endpoint. For API calls which require body or query params, you can use `**kwargs` to pass extra params: - `data` - takes a jsonified dictionary of body parameters - `params` - takes a dictionary of query parameters ``` # https://developer.box.com/reference/post-folders/ # Creates a new folder # JSONify the body body = json.dumps({ 'name': 'test-subfolder', 'parent': { 'id': '0', } }) client.make_request( 'POST', client.get_url('folders'), params={'fields': 'name,id'}, data=body ) ``` # Other Client Options ## Logging Client For more insight into the network calls the SDK is making, you can use the `LoggingClient` class. This class logs information about network requests and responses made to the Box API. ``` >>> from boxsdk import LoggingClient >>> client = LoggingClient() >>> client.user().get() GET https://api.box.com/2.0/users/me {'headers': {u'Authorization': u'Bearer ---------------------------kBjp', u'User-Agent': u'box-python-sdk-1.5.0'}, 'params': None} {"type":"user","id":"..","name":"Jeffrey Meadows","login":"..",..} <boxsdk.object.user.User at 0x10615b8d0> ``` ## Developer Token Client The Box Developer Console allows for the creation of short-lived developer tokens. The SDK makes it easy to use these tokens. Use the `get_new_token_callback` parameter to control how the client will get new developer tokens as needed. The default is to prompt standard input for a token. ## Development Client For exploring the Box API, or to quickly get going using the SDK, the `DevelopmentClient` class combines the `LoggingClient` with the `DeveloperTokenClient`. # Customization ## Custom Subclasses Custom object subclasses can be defined: ``` from boxsdk import Client from boxsdk import Folder class MyFolderSubclass(Folder): pass client = Client(oauth) client.translator.register('folder', MyFolderSubclass) folder = client.folder('0') >>> print folder >>> <Box MyFolderSubclass - 0> ``` If an object subclass is registered in this way, instances of this subclass will be returned from all SDK methods that previously returned an instance of the parent. See `BaseAPIJSONObjectMeta` and `Translator` to see how the SDK performs dynamic lookups to determine return types. # FIPS 140-2 Compliance The Python SDK allows the use of FIPS 140-2 validated SSL libraries, such as OpenSSL 3.0. However, some actions are required to enable this functionality. Currently, the latest distributions of Python default to OpenSSL v1.1.1, which is not FIPS compliant. Therefore, if you want to use OpenSSL 3.0 in your network communication, you need to ensure that Python uses a custom SSL library. One way to achieve this is by creating a custom Python distribution with the ssl module replaced. If you are using JWT for authentication, it is also necessary to ensure that the cryptography library, which is one of the extra dependencies for JWT, uses OpenSSL 3.0. To enable FIPS mode for the `cryptography` library, you need to install a FIPS-compliant version of OpenSSL during the installation process of cryptography using the `pip` command. # Versions We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. See [version strategy](https://developer.box.com/27a720aa01575cc19988821a8bfea27a/VERSIONS.md) for details which is effective from 30 July 2022. ## Supported Version Only the current MAJOR version of SDK is supported. New features, functionality, bug fixes, and security updates will only be added to the current MAJOR version. A current release is on the leading edge of our SDK development, and is intended for customers who are in active development and want the latest and greatest features. Instead of stating a release date for a new feature, we set a fixed minor or patch release cadence of maximum 2-3 months (while we may release more often). At the same time, there is no schedule for major or breaking release. Instead, we will communicate one quarter in advance the upcoming breaking change to allow customers to plan for the upgrade. We always recommend that all users run the latest available minor release for whatever major version is in use. We highly recommend upgrading to the latest SDK major release at the earliest convenient time and before the EOL date. ## Version schedule | Version | Supported Environments | State | First Release | EOL/Terminated | | --- | --- | --- | --- | --- | | 3 | Python 3.6+ | Supported | 17 Jan 2022 | TBD | | 2 | | EOL | 01 Nov 2018 | 17 Jan 2022 | | 1 | | EOL | 10 Feb 2015 | 01 Nov 2018 | # Contributing See [CONTRIBUTING.md](https://github.com/box/box-python-sdk/blob/main/CONTRIBUTING.md). ## Developer Setup Create a virtual environment and install packages - ``` mkvirtualenv boxsdk pip install -r requirements-dev.txt ``` ## Testing Run all tests using - ``` tox ``` The tox tests include code style checks via pep8 and pylint. The tox tests are configured to run on Python 3.6, 3.7, 3.8, 3.9, 3.10, 3.11, 3.12, 3.13. # Questions, Bugs, and Feature Requests? Need to contact us directly? Browse the issues tickets! Or, if that doesn't work, file a new one and we will get back to you. If you have general questions about the Box API, you can post to the Box Developer Forum. # Copyright and License ``` Copyright 2019 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 3.14.0 (2025-0… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## 3.14.0 (2025-04-09) ### New Features and Enhancements: - Add `stream_file_content` parameter to upload methods ([#890](https://github.com/box/box-python-sdk/issues/890)) ([0e63c00](https://github.com/box/box-python-sdk/commit/0e63c002ee17618c08200c12caae4bb3890b1e90)) ## 3.13.0 (2024-08-22) ### New Features and Enhancements: - Add support for get AI agent default ([#883](https://github.com/box/box-python-sdk/issues/883)) ([c1010e0](https://github.com/box/box-python-sdk/commit/c1010e0349847586a9f00046570e975ec48eb0c5)) ## 3.12.0 (2024-08-06) ### New Features and Enhancements: - add create sign request function with different required parameters ([#878](https://github.com/box/box-python-sdk/issues/878)) ([d972f54](https://github.com/box/box-python-sdk/commit/d972f54dcf9962c6b911422793a682d8f6289f9e)) - Support Box AI features ([#877](https://github.com/box/box-python-sdk/issues/877)) ([3026d2a](https://github.com/box/box-python-sdk/commit/3026d2ab9932cd07aa9ff15a3ac3c3c14d3089b0)) ## 3.11.0 (2024-06-07) ### New Features and Enhancements: - Use upload session `urls` for chunk upload ([#875](https://github.com/box/box-python-sdk/issues/875)) ([c67b03c](https://github.com/box/box-python-sdk/commit/c67b03c7d88533773d62d72f0b626031805d61eb)) ## 3.10.0 (2024-05-22) ### New Features and Enhancements: - Transition to stable status ([#872](https://github.com/box/box-python-sdk/issues/872)) ([6203606](https://github.com/box/box-python-sdk/commit/620360607a51ee302cde61401db1424c9bf48d81)) ### Bug Fixes: - Change exception type for missing location header ([#871](https://github.com/box/box-python-sdk/issues/871)) ([8c5e0ec](https://github.com/box/box-python-sdk/commit/8c5e0eca7e494baa8138dceededa2009abc1717b)) - fix annnotation of oauths access_token ([#855](https://github.com/box/box-python-sdk/issues/855)) ([804780e](https://github.com/box/box-python-sdk/commit/804780e4c8d410590fa20cdb6dd35224d59d2ec0)) - Fix retention policy integration test ([#867](https://github.com/box/box-python-sdk/issues/867)) ([8e0d640](https://github.com/box/box-python-sdk/commit/8e0d6406f26be87799838b0aa57acd62c79d59a2)) - Remove delete classification ([#861](https://github.com/box/box-python-sdk/issues/861)) ([393cfef](https://github.com/box/box-python-sdk/commit/393cfefa57e729f34221a4e5923a4a50532f4013)) - Update exception file get download URL ([#866](https://github.com/box/box-python-sdk/issues/866)) ([94dcbcd](https://github.com/box/box-python-sdk/commit/94dcbcd490d98ff19afd38c9880de8022ad2ec89)) ### 3.9.2 (2023-10-18) ### Bug Fixes: - Remove restriction to version <2 of `urllib3` library ([#851](https://github.com/box/box-python-sdk/issues/851)) ([1dcd82e](https://github.com/box/box-python-sdk/commit/1dcd82e93267bfc68e3a7f8068b3c45ab7e86daf)) ### 3.9.1 (2023-09-14) ### Bug Fixes: - do not retry creating a ZIP when response code is 202 ([#845](https://github.com/box/box-python-sdk/issues/845)) ([3f6ed4e](https://github.com/box/box-python-sdk/commit/3f6ed4e1053a494ed9f2b79828850e059d0a1617)), closes [#844](https://github.com/box/box-python-sdk/issues/844) ## 3.9.0 (2023-09-06) ### New Features and Enhancements: - adds get sign template and get sign templates methods on Client ([#835](https://github.com/box/box-python-sdk/issues/835)) ([fbc783d](https://github.com/box/box-python-sdk/commit/fbc783d5af2e75f883f1a0051613c513139f68fb)) - Support create sign request with template ID ([#834](https://github.com/box/box-python-sdk/issues/834)) ([4f11d75](https://github.com/box/box-python-sdk/commit/4f11d7596488194fc740936fe987f42864003d41)) ### Bug Fixes: - ChunkedUploader Resume Not Closing ThreadPoolExecutor Instances ([#840](https://github.com/box/box-python-sdk/issues/840)) ([f210f00](https://github.com/box/box-python-sdk/commit/f210f00ad823d7755309f2e8804641e0debf8197)) ### 3.8.1 (2023-08-01) ### Bug Fixes: - Fix JSON response validation retry strategy ([#831](https://github.com/box/box-python-sdk/issues/831)) ([69834eb](https://github.com/box/box-python-sdk/commit/69834eb4c91a5aa4bc294a9fa49ecf753979d029)) ## 3.8.0 (2023-07-25) ### New Features and Enhancements: - Support updating all fields of `collaboration` ([#829](https://github.com/box/box-python-sdk/issues/829)) ([6dc7ecc](https://github.com/box/box-python-sdk/commit/6dc7ecc6f9c94e7531c4147a3645927b85928b2c)) ### 3.7.3 (2023-07-07) ### Bug Fixes: - Stop processing data for logging when logging is disabled and cache response `json` ([#824](https://github.com/box/box-python-sdk/issues/824)) ([3079171](https://github.com/box/box-python-sdk/commit/3079171f8dfc1a4c85f8587e8ce90e8fbd826ee4)) ### 3.7.2 (2023-05-26) ### Bug Fixes: - Use the older version of `urllib3` ([#815](https://github.com/box/box-python-sdk/issues/815)) ([ee29aa3](https://github.com/box/box-python-sdk/commit/ee29aa3fcf9ac71e9866913a87414cf625c0b805)) ### 3.7.1 (2023-04-18) ### Bug Fixes: - Rename filter date parameters in legal hold creation according to the documentation ([#810](https://github.com/box/box-python-sdk/issues/810)) ([f52c66a](https://github.com/box/box-python-sdk/commit/f52c66a8a8399a776493537f692460ace2995e40)) ## 3.7.0 (2023-03-08) ### New Features and Enhancements: - Update `retention_policies` and `retention_policy_assignments` ([#803](https://github.com/box/box-python-sdk/issues/803)) ([8b72f7e](https://github.com/box/box-python-sdk/commit/8b72f7e992bce676723a40ac12bde06c8cca3bfb)) - Use multiple threading for chunked upload ([#800](https://github.com/box/box-python-sdk/issues/800)) ([506ce0d](https://github.com/box/box-python-sdk/commit/506ce0d1e72ab4eeb6c5933a32c753e232a2f624)) ### 3.6.2 (2023-02-07) ### Bug Fixes: - Retry `Connection broken` and `Connection reset` requests errors ([#794](https://github.com/box/box-python-sdk/issues/794)) ([f1a0aa4](https://github.com/box/box-python-sdk/commit/f1a0aa434369f06e80654a9f5c4b796100881aa6)) ### 3.6.1 (2023-01-09) ### Bug Fixes: - Retry CCG and JWT auth requests on connection reset error ([#790](https://github.com/box/box-python-sdk/issues/790)) ([205997d](https://github.com/box/box-python-sdk/commit/205997db9870395b9dd042854c4201338dcf925f)), closes [#789](https://github.com/box/box-python-sdk/issues/789) ## 3.6.0 (2023-01-03) ### New Features and Enhancements: - Add support marker in trash get items ([#781](https://github.com/box/box-python-sdk/issues/781)) ([e2d1846](https://github.com/box/box-python-sdk/commit/e2d1846818aeccfcba2a2f09a5cd924c9f6cd534)) - Sanitize proxy credentials ([#782](https://github.com/box/box-python-sdk/issues/782)) ([97fb5aa](https://github.com/box/box-python-sdk/commit/97fb5aa2ed72008570abb327269ecec150632af9)) ### Bug Fixes: - Fix index error when getting an empty list of user term of service statuses ([#780](https://github.com/box/box-python-sdk/issues/780)) ([23d763a](https://github.com/box/box-python-sdk/commit/23d763ac4ba592131c43eb0319929db25d041c30)) - Specify which exceptions should be retried ([#784](https://github.com/box/box-python-sdk/issues/784)) ([833cd46](https://github.com/box/box-python-sdk/commit/833cd46bafe774f19925f78600df90477bf07055)) ### 3.5.1 (2022-11-30) ### Bug Fixes: - Renew connection when Connection reset error occurs ([#771](https://github.com/box/box-python-sdk/issues/771)) ([bcaab27](https://github.com/box/box-python-sdk/commit/bcaab277c3cabba498076d066366abbaa5507904)), closes [#756](https://github.com/box/box-python-sdk/issues/756) [#757](https://github.com/box/box-python-sdk/issues/757) [#763](https://github.com/box/box-python-sdk/issues/763) [#765](https://github.com/box/box-python-sdk/issues/765) [#766](https://github.com/box/box-python-sdk/issues/766) [#770](https://github.com/box/box-python-sdk/issues/770) - Retry JWT auth when got error: required unique `jti` claim. ([#768](https://github.com/box/box-python-sdk/issues/768)) ([878e958](https://github.com/box/box-python-sdk/commit/878e958abfb01740656aaff42492777753e4c8ea)) - Update `pyjtw` dependency to work with Python 3.10 ([#772](https://github.com/box/box-python-sdk/issues/772)) ([b13c5cd](https://github.com/box/box-python-sdk/commit/b13c5cd34105d3f774d3f6d35db7aaf51dd3e247)) ## 3.5.0 (2022-09-23) ### New Features and Enhancements: - Add `redirect_url` and `declined_redirect_url` fields to Sign Request ([#752](https://github.com/box/box-python-sdk/issues/752)) ([5d1f609](https://github.com/box/box-python-sdk/commit/5d1f609ed4c2ddb24bd88ffac256a2809a012698)) - Add support for modifiable retention policies & enable deleting retention policy assignment ([#759](https://github.com/box/box-python-sdk/issues/759)) ([847301b](https://github.com/box/box-python-sdk/commit/847301b43be335365858a80420459dffaada4302)) - Support file request APIs ([#747](https://github.com/box/box-python-sdk/issues/747)) ([71895e3](https://github.com/box/box-python-sdk/commit/71895e33ff7cf339fd8e095a5393f04b86791d5a)) ### Bug Fixes: - Do not log the content of downloaded file ([#760](https://github.com/box/box-python-sdk/issues/760)) ([5d26431](https://github.com/box/box-python-sdk/commit/5d264314f949c1f4d9136efd5cf8f13dd5897c05)) - Fix closing file after chunked upload ([#761](https://github.com/box/box-python-sdk/issues/761)) ([b433692](https://github.com/box/box-python-sdk/commit/b433692ecc07d62d011785a557128c1780ea1647)) ## 3.4.0 (2022-07-06) ### New Features and Enhancements: - Add support for editable shared links for files ([#737](https://github.com/box/box-python-sdk/issues/737)) ([1396200](https://github.com/box/box-python-sdk/commit/1396200c24bf62de63f9cb7949af5997593b9fac)) - Support uploading and deleting user avatar ([#743](https://github.com/box/box-python-sdk/issues/743)) ([fe00a9e](https://github.com/box/box-python-sdk/commit/fe00a9eb3434ee14bc4f01332d54c0272ed5f2d3)) ## 3.3.0 (2022-04-28) ### New Features and Enhancements: - Add support for multiple date time formats ([#722](https://github.com/box/box-python-sdk/issues/722)) ([92364de](https://github.com/box/box-python-sdk/commit/92364de1e7c1eee1e85857546af65c307ca863a0)) ### Bug Fixes: - Add missing fields to metadata template field ([#719](https://github.com/box/box-python-sdk/issues/719)) ([9e574a3](https://github.com/box/box-python-sdk/commit/9e574a3e56f72c0e78a31ddda78bc11d36ff3516)), closes [#717](https://github.com/box/box-python-sdk/issues/717) - Upload session commit return None on 202 ([#718](https://github.com/box/box-python-sdk/issues/718)) ([86a1856](https://github.com/box/box-python-sdk/commit/86a185630e6cce8f742123c7340da08267621313)), closes [#715](https://github.com/box/box-python-sdk/issues/715) ## 3.2.0 (2022-03-11) ### New Features and Enhancements: - Add setting `disposition_at` field for files under retention ([#710](https://github.com/box/box-python-sdk/issues/710)) ([91b1373](https://github.com/box/box-python-sdk/commit/91b13730a0beef2cf2a8a8c71087b11557fa5982)) - Add support for Client Credentials Grant authentication method ([#705](https://github.com/box/box-python-sdk/issues/705)) ([d33d16d](https://github.com/box/box-python-sdk/commit/d33d16db656cb5578f057a7e24f5396d635b5361)) ### Bug Fixes: - Add missing `box_sign` object to `__all__` list ([#708](https://github.com/box/box-python-sdk/issues/708)) ([5d80481](https://github.com/box/box-python-sdk/commit/5d8048116640fa672d6a1d700a6c1111faf87bb9)) - Fix `jwt` import errors ([#711](https://github.com/box/box-python-sdk/issues/711)) ([ee7bb6f](https://github.com/box/box-python-sdk/commit/ee7bb6f1dc5aa65dbf6ffeb18ee130f765f7b49b)) ## 3.1.0 (2022-02-16) ### New Features and Enhancements: - Add support for Python 3.10 ([#692](https://github.com/box/box-python-sdk/issues/692)) ([d4aed82](https://github.com/box/box-python-sdk/commit/d4aed82831af97305bace9a4588d27b23856c306)) - Add support for Python 3.8, Python 3.9, `pypy-3.7` and `pypy-3.8`. ([#689](https://github.com/box/box-python-sdk/issues/689)) ([0aa94cc](https://github.com/box/box-python-sdk/commit/0aa94cc8a5c4db0fc204b27a60690b73c98a89cb)) - Deprecate `use_index` parameter from `MDQ` of files/folders ([#666](https://github.com/box/box-python-sdk/issues/666)) ([2595720](https://github.com/box/box-python-sdk/commit/25957204b82c878e15dc3d118505a741171e9772)) - Replace external package `mock` with Python standard library `unittest.mock` ([#697](https://github.com/box/box-python-sdk/issues/697)) ([6fd6366](https://github.com/box/box-python-sdk/commit/6fd63667aa7da4c794b4fb880d5c2949efe0073f)) - Upgrade cryptography library to the most recent version. ([#668](https://github.com/box/box-python-sdk/issues/668)) ([9c94d08](https://github.com/box/box-python-sdk/commit/9c94d0878515dc75c1f267e2fb1f189a852772b6)), closes [#667](https://github.com/box/box-python-sdk/issues/667) ### Bug Fixes: - `UploadSession.commit` returns `None` when retry limit was reached ([#696](https://github.com/box/box-python-sdk/issues/696)) ([9456fe0](https://github.com/box/box-python-sdk/commit/9456fe0124f4ac4e9c8a7bcc49039f07f310c477)) - Add missing `api_call` decorator for `create_upload_session` ([#686](https://github.com/box/box-python-sdk/issues/686)) ([3510d3a](https://github.com/box/box-python-sdk/commit/3510d3ac085767205854014ecef80fd078d71773)) - Fix chunked upload ([#673](https://github.com/box/box-python-sdk/issues/673)) ([2605fd7](https://github.com/box/box-python-sdk/commit/2605fd782396ad6e42bd11c10f846e771634b7a0)), closes [#671](https://github.com/box/box-python-sdk/issues/671) ## [3.0.1] (2022-01-26) ### Bug Fixes: Move sphinx to test requirements ([#662](https://github.com/box/box-python-sdk/pull/662)) ## [3.0.0] (2022-01-17) ### ⚠ Breaking Changes: Drop support for python 2.7 ([#645](https://github.com/box/box-python-sdk/pull/645)) Add missing parameter `stream_position` to `get_admin_events` method ([#648](https://github.com/box/box-python-sdk/pull/648)) Drop support for python 3.5 ([#654](https://github.com/box/box-python-sdk/pull/654)) Remove deprecated code using insensitive language ([#651](https://github.com/box/box-python-sdk/pull/651)) Enforcing usage of keyword-only arguments in some functions ([#656](https://github.com/box/box-python-sdk/pull/656)) ### New Features and Enhancements: Remove `six` library and `__future__` imports ([#646](https://github.com/box/box-python-sdk/pull/646)) Add type hints to method parameters ([#650](https://github.com/box/box-python-sdk/pull/650)) ### Bug Fixes: Add missing `api_call` decorators on `multiput` calls ([#653](https://github.com/box/box-python-sdk/pull/653)) Added `py.typed` file for `mypy` to recognise type hints ([#657](https://github.com/box/box-python-sdk/pull/657)) ## [2.14.0] (2021-12-08) ### New Features and Enhancements: Add `admin_logs_streaming` support for events stream ([#623](https://github.com/box/box-python-sdk/pull/623)) Add `vanity_name` parameter for creating shared link to a file or folder ([#637](https://github.com/box/box-python-sdk/pull/637)) Add getting files and file versions under retention for a retention policy assignment ([#633](https://github.com/box/box-python-sdk/pull/633)) Support base item operations for WebLink class ([#639](https://github.com/box/box-python-sdk/pull/639)) ### Bug Fixes: Limit cryptography to version <3.5.0 ([#636](https://github.com/box/box-python-sdk/pull/636)) Avoid raising 404 when a thumbnail cannot be generated for a file ([#642](https://github.com/box/box-python-sdk/pull/642)) ## [2.13.0] (2021-09-30) ### New Features and Enhancements: Sensitive language replacement ([#609](https://github.com/box/box-python-sdk/pull/609)) Add BoxSign support ([#617](https://github.com/box/box-python-sdk/pull/617)) ### Bug Fixes: Upgrade cryptography to version 3 ([#620](https://github.com/box/box-python-sdk/pull/620)) ## [2.12.1] (2021-06-16) ### Bug Fixes: Fix bug when thumbnail representations are not found ([#597](https://github.com/box/box-python-sdk/pull/597)) ## [2.12.0] (2021-04-16) ### New Features and Enhancements: Add metadata query functionality ([#574](https://github.com/box/box-python-sdk/pull/574)) Add folder lock functionality ([#581](https://github.com/box/box-python-sdk/pull/581)) Add search query support for the `include_recent_shared_links` field ([#582](https://github.com/box/box-python-sdk/pull/582)) Update `get_groups()` to use documented parameter to filter by name ([#586](https://github.com/box/box-python-sdk/pull/586)) ## [2.11.0] (2021-01-11) ### New Features and Enhancements: Deprecate and add method for getting a thumbnail ([#572](https://github.com/box/box-python-sdk/pull/572)) ## [2.10.0] (2020-10-02) ### New Features and Enhancements: Add support for `copyInstanceOnItemCopy` field for metadata templates ([#546](https://github.com/box/box-python-sdk/pull/546)) Allow creating tasks with the `action` and `completion_rule` parameters ([#544](https://github.com/box/box-python-sdk/pull/544)) Add zip functionality ([#539](https://github.com/box/box-python-sdk/pull/539)) ### Bug Fixes: Fix bug with updating a collaboration role to owner ([#536](https://github.com/box/box-python-sdk/pull/536)) Allow ints to be passed in as item IDs ([#530](https://github.com/box/box-python-sdk/pull/530)) ## [2.9.0] (2020-06-23) - Fix exception handling for OAuth - Fix path parameter sanitization ## [2.8.0] (2020-04-24) - Added support for token exchange using shared links - Added the ability to pass in a SHA1 value for file uploads ## [2.7.1] (2020-01-21) Fixed bug in `_get_retry_request_callable` introduced in release 2.7.0 which caused chunked uploads to fail ## [2.7.0] (2020-01-16) Fixed bug in `get_admin_events` function which caused errors when the optional `event_types` parameter was omitted. - Add marker based pagination for listing users. Added support for more attribute parameters when uploading new files and new versions of existing files. Combined preflight check and lookup of accelerator URL into a single request for uploads. - Fixed JWT retry logic so a new JTI claim is generated on each retry. Fixed bug where JWT authentication requests returned incorrect error codes. Fixed retry logic so when a `Retry-After` header is passed back from the API, the SDK waits for the amount of time specified in the header before retrying. ## [2.6.1] (2019-10-24) - Added `api_call` decorator for copy method. ## [2.6.0] (2019-08-29) Added a new get events function with created_before, created_after, and event_type parameters ## [2.5.0] (2019-06-20) Allowed passing `None` to clear configurable_permission field in the add_member() method. ## [2.4.1] (2019-05-16) - Patch release for issues with v2.4.0. ## [2.4.0] (2019-05-16) Added ability to set metadata on a [file](https://github.com/box/box-python-sdk/blob/main/docs/usage/files.md#set-metadata) or a [folder](https://github.com/box/box-python-sdk/blob/main/docs/usage/folders.md#set-metadata) ## [2.3.2] (2019-03-29) - Fixing an issue in v2.3.1 where package could not be installed. ## [2.3.1] (2019-03-29) - Fixing an issue in v2.3.0 where package could not be installed. ## [2.3.0] (2019-03-28) Added the ability to set file description upon upload Added support for basic authenticated proxy and unauthenticated proxy ## [2.2.2] (2019-03-14) - Updated requests-toolbelt dependency restriction. ## [2.2.1] (2019-02-15) - Fixing an issue in v2.2.0 where package could not be installed. ## [2.2.0] (2019-02-14) Added abilty for user to retrieve an avatar for a user. Changed retry strategy to use exponential backoff with randomized jitter. ## [2.1.0] (2019-02-07) Added ability for user to chunk upload files and resume uploads for interrupted uploads. Added ability to verify webhook message. Added ability for user to add metadata classification to [files](https://github.com/box/box-python-sdk/blob/main/docs/usage/files.md#set-a-classification) and [folders](https://github.com/box/box-python-sdk/blob/main/docs/usage/folders.md#set-a-classification). Bugfix where calling `.response_object()` method on an API object could throw. ## [2.0.0] ### ⚠ Breaking Changes Python 2.6 is no longer supported. Python 3.3 is no longer supported. `client.search()` now returns a `Search` object that exposes a `query()` method to call the Search API. Use `client.search().query(**search_params)` instead of `client.search(**search_params)`. `client.get_memberships(...)` has a change in signature. The limit and offset parameters have swapped positions to keep consistency with the rest of the SDK. `client.groups(...)` has been changed to `client.get_groups`. The limit and offset parameters have swapped positions. The `unshared_at` parameter for `item.create_shared_link(...)` and `file.get_shared_link_download_url(...)` now takes an [https://tools.ietf.org/html/rfc3339#section-5.8](https://tools.ietf.org/html/rfc3339#section-5.8) `unicode` string instead of a `datetime.date`. Users migrating from v1.x can pass the value of `date.isoformat()` instead of the `date` object itself. `Events.get_events(...)` now returns a list of `Event` instances rather than a list of `dict` representing events. `Event` inherits from `Mapping` but will not have all the same capabilities as `dict`. Your code is affected if you use `Events.get_events(...)` and expect a list of `dict` rather than a list of `Mapping`. For example, if you use `__setitem__` (`event['key'] = value`), `update()`, `copy()`, or if your code depends on the `str` or `repr` of the `Event`. Use of `__getitem__` (`event['key']`), `get()`, and other `Mapping` methods is unaffected. See [https://docs.python.org/2.7/library/collections.html#collections-abstract-base-classes](https://docs.python.org/2.7/library/collections.html#collections-abstract-base-classes) for methods supported on `Mapping` instances. Migration: If you still need to treat an `Event` as a `dict`, you can get a deepcopy of the original `dict` using the new property on `BaseAPIJSONObject`, `response_object`. `LoggingNetwork` has been removed. Logging calls are now made from the `DefaultNetwork` class. In addition, the logging format strings in this class have changed in a way that will break logging for any applications that have overridden any of these strings. They now use keyword format placeholders instead of positional placeholders. All custom format strings will now have to use the same keyword format placeholders. Though this is a breaking change, the good news is that using keyword format placeholders means that any future changes will be automatically backwards-compatibile (as long as there aren't any changes to change/remove any of the keywords). `File.update_contents()` and `File.update_contents_with_stream()` now correctly return a `File` object with the correct internal JSON structure. Previously it would return a `File` object where the file JSON is hidden inside `file['entries'][0]`. This is a bugfix, but will be a breaking change for any clients that have already written code to handle the bug. Comparing two objects (e.g. a `File` and a `Folder`) that have the same Box ID but different types with `==` will now correctly return `False`. The following methods now return iterators over the entire collection of returned objects, rather than a single page: - `client.users()` - `client.groups()` - `client.search().query()` - `folder.get_items()` Since `folder.get_items()` now returns an iterator, `folder.get_items_limit_offset()` and `folder.get_items_marker()` have been removed. To use marker based paging with `folder.get_items()`, pass the `use_marker=True` parameter and optionally specify a `marker` parameter to begin paging from that point in the collection. Additionally, `group.membership()` has been renamed to `group.get_memberships()`, and returns an iterator of membership objects. This method no longer provides the option to return tuples with paging information. The `Translator` class has been reworked; `translator.get(...)` still returns the constructor for the object class corresponding to the passed in type, but `translator.translate(...)` now takes a `Session` and response object directly and produces the translated object. This method will also translate any nested objects found. This change obviates the need for `GroupMembership` to have a custom constructor; it now uses the default `BaseObject` constructor. ### Features All publicly documented API endpoints and parameters should now be supported by the SDK Added more flexibility to the object translation system: Can create non-global `Translator` instances, which can extend or not-extend the global default `Translator`. - Can initialize `BoxSession` with a custom `Translator`. Can register custom subclasses on the `Translator` which is associated with a `BoxSession` or a `Client`. All translation of API responses now use the `Translator` that is referenced by the `BoxSession`, instead of directly using the global default `Translator`. - Nested objects are now translated by `translator.translate()` When the `auto_session_renewal` is `True` when calling any of the request methods on `BoxSession`, if there is no access token, `BoxSession` will renew the token before making the request. This saves an API call. Auth objects can now be closed, which prevents them from being used to request new tokens. This will also revoke any existing tokens (though that feature can be disabled by passing `revoke=False`). Also introduces a `closing()` context manager method, which will auto-close the auth object on exit. Various enhancements to the `JWTAuth` baseclass: The `authenticate_app_user()` method is renamed to `authenticate_user()`, to reflect that it may now be used to authenticate managed users as well. See the method docstring for details. `authenticate_app_user()` is now an alias of `authenticate_user()`, in order to not introduce an unnecessary backwards-incompatibility. The `user` argument to `authenticate_user()` may now be either a user ID string or a `User` instance. Before it had to be a `User` instance. The constructor now accepts an optional `user` keyword argument, which may be a user ID string or a `User` instance. When this is passed, `authenticate_user()` and can be called without passing a value for the `user` argument. More importantly, this means that `refresh()` can be called immediately after construction, with no need for a manual call to `authenticate_user()`. Combined with the aforementioned improvement to the `auto_session_renewal` functionality of `BoxSession`, this means that authentication for `JWTAuth` objects can be done completely automatically, at the time of first API call. The constructor now supports passing the RSA private key in two different ways: by file system path (existing functionality), or by passing the key data directly (new functionality). The `rsa_private_key_file_sys_path` parameter is now optional, but it is required to pass exactly one of `rsa_private_key_file_sys_path` or `rsa_private_key_data`. Document that the `enterprise_id` argument to `JWTAuth` is allowed to be `None`. `authenticate_instance()` now accepts an `enterprise` argument, which can be used to set and authenticate as the enterprise service account user, if `None` was passed for `enterprise_id` at construction time. Authentications that fail due to the expiration time not falling within the correct window of time are now automatically retried using the time given in the Date header of the Box API response. This can happen naturally when the system time of the machine running the Box SDK doesn't agree with the system time of the Box API servers. Added an `Event` class. Moved `metadata()` method to `Item` so it's now available for `Folder` as well as `File`. The `BaseAPIJSONObject` baseclass (which is a superclass of all API response objects) now supports `__contains__` and `__iter__`. They behave the same as for `Mapping`. That is, `__contains__` checks for JSON keys in the object, and `__iter__` yields all of the object's keys. Added a `RecentItem` class. Added `client.get_recent_items()` to retrieve a user's recently accessed items on Box. Added support for the `can_view_path` parameter when creating new collaborations. Added `BoxObjectCollection` and subclasses `LimitOffsetBasedObjectCollection` and `MarkerBasedObjectCollection` to more easily manage paging of objects from an endpoint. These classes manage the logic of constructing requests to an endpoint and storing the results, then provide `__next__` to easily iterate over the results. The option to return results one by one or as a `Page` of results is also provided. Added a `downscope_token()` method to the `Client` class. This generates a token that has its permissions reduced to the provided scopes and for the optionally provided `File` or `Folder`. Added methods for configuring `JWTAuth` from config file: `JWTAuth.from_settings_file` and `JWTAuth.from_settings_dictionary`. Added `network_response` property to `BoxOAuthException`. API Configuration can now be done per `BoxSession` instance. ### Other - Added extra information to `BoxAPIException`. - Added `collaboration()` method to `Client`. Reworked the class hierarchy. Previously, `BaseEndpoint` was the parent of `BaseObject` which was the parent of all smart objects. Now `BaseObject` is a child of both `BaseEndpoint` and `BaseAPIJSONObject`. `BaseObject` is the parent of all objects that are a part of the REST API. Another subclass of `BaseAPIJSONObject`, `APIJSONObject`, was created to represent pseudo-smart objects such as `Event` that are not directly accessible through an API endpoint. Added `network_response_constructor` as an optional property on the `Network` interface. Implementations are encouraged to override this property, and use it to construct `NetworkResponse` instances. That way, subclass implementations can easily extend the functionality of the `NetworkResponse`, by re-overriding this property. This property is defined and used in the `DefaultNetwork` implementation. Move response logging to a new `LoggingNetworkResponse` class (which is made possible by the aforementioned `network_response_constructor` property). Now the SDK decides whether to log the response body, based on whether the caller reads or streams the content. Add more information to the request/response logs from `LoggingNetwork`. - Add logging for request exceptions in `LoggingNetwork`. Bugfix so that the return value of `JWTAuth.refresh()` correctly matches that of the auth interface (by returning a tuple of ((access token), (refresh token or None)), instead of just the access token). In particular, this fixes an exception in `BoxSession` that always occurred when it tried to refresh any `JWTAuth` object. Fixed an exception that was being raised from `ExtendableEnumMeta.__dir__()`. - CPython 3.6 support. - Increased required minimum version of six to 1.9.0. ## [1.5.3] (2016-05-26) Bugfix so that `JWTAuth` opens the PEM private key file in `'rb'` mode. ## [1.5.2] (2016-05-19) Bugfix so that `OAuth2` always has the correct tokens after a call to `refresh()`. ## [1.5.1] (2016-03-23) Added a `revoke()` method to the `OAuth2` class. Calling it will revoke the current access/refresh token pair. ## [1.5.0] (2016-03-17) Added a new class, `LoggingClient`. It's a `Client` that uses the `LoggingNetwork` class so that requests to the Box API and its responses are logged. Added a new class, `DevelopmentClient` that combines `LoggingClient` with the existing `DeveloperTokenClient`. This client is ideal for exploring the Box API or for use when developing your application. Made the `oauth` parameter to `Client` optional. The constructor now accepts new parameters that it will use to construct the `OAuth2` instance it needs to auth with the Box API. Changed the default User Agent string sent with requests to the Box API. It is now 'box-python-sdk-<version>'. Box objects have an improved `__repr__`, making them easier to identify during debugging sessions. Box objects now implement `__dir__`, making them easier to explore. When created with a Box API response, these objects will now include the API response fields as attributes. ## [1.4.2] (2016-02-23) Make sure that `__all__` is only defined once, as a list of `str`. Some programs (e.g. PyInstaller) naively parse __init__.py files, and if `__all__` is defined twice, the second one will be ignored. This can cause `__all__` to appear as a list of `unicode` on Python 2. Create wheel with correct conditional dependencies and license file. Change the `license` meta-data from the full license text, to just a short string, as specified in [1][2]. [1] <[https://docs.python.org/3.5/distutils/setupscript.html#additional-meta-data](https://docs.python.org/3.5/distutils/setupscript.html#additional-meta-data)> [2] <[https://www.python.org/dev/peps/pep-0459/#license](https://www.python.org/dev/peps/pep-0459/#license)> Include entire test/ directory in source distribution. test/__init__.py was previously missing. Update documentation. ## [1.4.1] (2016-02-11) - Files now support getting a direct download url. ## [1.4.0] (2016-01-05) - Added key id parameter to JWT Auth. ## [1.3.3] (2016-01-04) ### Bugfixes Fixed import error for installations that don't have redis installed. Fixed use of `raw_input` in the developer token auth for py3 compatibility. ## [1.3.3] (2015-12-22) Added a new class, `DeveloperTokenClient` that makes it easy to get started using the SDK with a Box developer token. It uses another new class, `DeveloperTokenAuth` for auth. ### Bugfixes Added limit, offset, and filter_term parameters to `client.users()` to match up with the Box API. ## [1.3.2] (2015-11-16) - Fix `boxsdk.util.log.setup_logging()` on Python 3. ## [1.3.1] (2015-11-06) Add requests-toolbelt to setup.py (it was accidentally missing from 1.3.0). ## [1.3.0] (2015-11-05) - CPython 3.5 support. - Support for cryptography>=1.0 on PyPy 2.6. - Travis CI testing for CPython 3.5 and PyPy 2.6.0. - Added a logging network class that logs requests and responses. Added new options for auth classes, including storing tokens in Redis and storing them on a remote server. - Stream uploads of files from disk. ## [1.2.2] (2015-07-22) - The SDK now supports setting a password when creating a shared link. ## [1.2.1] (2015-07-22) ### Bugfixes Fixed an ImportError for installs that didn't install the [jwt] extras. ## [1.2.0] (2015-07-13) Added support for Box Developer Edition. This includes JWT auth (auth as enterprise or as app user), and `create_user` functionality. - Added support for setting shared link expiration dates. - Added support for setting shared link permissions. Added support for 'As-User' requests. See [https://developer.box.com/en/guides/authentication/oauth2/as-user/](https://developer.box.com/en/guides/authentication/oauth2/as-user/) Improved support for accessing shared items. Items returned from the `client.get_shared_item` method will remember the shared link (and the optionally provided shared link password) so methods called on the returned items will be properly authorized. ## [1.1.7] (2015-05-28) - Add context_info from failed requests to BoxAPIException instances. ### Bugfixes `Item.remove_shared_link()` was trying to return an incorrect (according to its own documentation) value, and was also attempting to calculate that value in a way that made an incorrect assumption about the API response. The latter problem caused invocations of the method to raise TypeError. The method now handles the response correctly, and correctly returns type `bool`. ## [1.1.6] (2015-04-17) - Added support for the Box accelerator API for premium accounts. ## [1.1.5] (2015-04-03) - Added support for preflight check during file uploads and updates. ## [1.1.4] (2015-04-01) - Added support to the search endpoint for metadata filters. Added support to the search endpoint for filtering based on result type and content types. ## [1.1.3] (2015-03-26) Added support for the /shared_items endpoint. `client.get_shared_item` can be used to get information about a shared link. See [https://developers.box.com/docs/#shared-items](https://developers.box.com/docs/#shared-items) ## [1.1.2] (2015-03-20) ### Bugfixes Certain endpoints (e.g. search, get folder items) no longer raise an exception when the response contains items that are neither files nor folders. ## [1.1.1] (2015-03-11) A minor change to namespacing. The `OAuth2` class can now be imported directly from `boxsdk`. Demo code has been updated to reflect the change. ## [1.1.0] (2015-03-02) ### Features The SDK now supports Box metadata. See the metadata docs for more information. The object paging API has been improved. SDK extensions that need fine-grained control over when the next "page" of API results will be fetched can now do that. ### Example Code The example code has been improved to be more robust and to work with all Python versions supported by the SDK (CPython 2.6-2.7, CPython 3.3-3.4, and PyPy). The example code has an example on how to use the new metadata feature. - The README has improved code examples. ### Bugfixes Oauth2 redirect URIs containing non-ASCII characters are now supported. --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - if you want to contribute code. Please be sure to file an issue first. ## Pull request best practices We want to accept your pull requests. Please follow these steps: ### Step 1: File an issue Before writing any code, please file an issue stating the problem you want to solve or the feature you want to implement. This allows us to give you feedback before you spend any time writing code. There may be a known limitation that can't be addressed, or a bug that has already been fixed in a different way. The issue allows us to communicate and figure out if it's worth your time to write a bunch of code for the project. ### Step 2: Fork this repository in GitHub This will create your own copy of our repository. ### Step 3: Add the upstream source The upstream source is the project under the Box organization on GitHub. To add an upstream source for this project, type: ``` git remote add upstream git@github.com:box/box-python-sdk.git ``` This will come in useful later. ### Step 4: Create a feature branch Create a branch with a descriptive name, such as `add-search`. ### Step 5: Push your feature branch to your fork We use [semantic-versioning](https://semver.org/) and the [conventional commit message format](https://www.conventionalcommits.org/en/v1.0.0/). Keep a separate feature branch for each issue you want to address. As you develop code, continue to push code to your remote feature branch. Example: ``` tag: short description longer description here if necessary. ``` The message summary should be a one-sentence description of the change, and it must be 72 characters in length or shorter. For a list of tags, please [click here](https://github.com/commitizen/conventional-commit-types/blob/master/index.json). Note that you must include the `!` for breaking changes (e.g. `feat!: removed old apis`). Shown below are examples of the release type that will be done based on a commit message. #### Commit Types "Semantic versioning" means that changes to the version number of the package (e.g. `3.42.11` to `3.43.0`) are done according to rules that indicate how the change will affect consumers. Read more on the [semver page](https://semver.org/). The version number is broken into 3 positions — `Major.Minor.Patch`. In semantic release terms, changes to the numbers follow `Breaking.Feature.Fix`. The `release` script parses commit messages and decides what type of release to make based on the types of commits detected since the last release. The rules for commit types are: - Anything that changes or removes an API, option, or output format is a breaking change denoted by `!`. - Anything that adds new functionality in a backwards-compatible way is a feature (`feat`). Consumers have to upgrade to the new version to use the feature, but nothing will break if they do so. - Bugfixes (`fix`) for existing behavior are a patch. Consumers don't have to do anything but upgrade. - Other prefixes, such as `docs` or `chore`, don't trigger releases and don't appear in the changelog. These tags signal that there are **no external changes to *any* APIs** (including non-breaking ones). In most cases, commits will be a `feat` or `fix`. Make sure to include the `!` in the title if there are non-backwards-compatible changes in the commit. | Commit message | Release type | New version | | --- | --- | --- | | feat!: remove old files endpoints | Major ("breaking") | X+1.0.0 | | feat: add new file upload endpoint | Minor ("feature") | X.Y+1.0 | | fix: file streaming during download | Patch ("fix") | X.Y.Z+1 | | docs: document files api | No release | X.Y.Z | | chore: remove commented code from file upload | No release | X.Y.Z | | refactor: rename a variable (invisible change) | No release | X.Y.Z | ### Step 6: Rebase Before sending a pull request, rebase against upstream, such as: ``` git fetch upstream git rebase upstream/main ``` This will add your changes on top of what's already in upstream, minimizing merge issues. ### Step 7: Run the tests Make sure that all tests are passing before submitting a pull request. ### Step 8: Send the pull request Send the pull request from your feature branch to us. Be sure to include a description that lets us know what work you did. Keep in mind that we like to see one issue addressed per pull request, as this helps keep our git history clean and we can more easily track down issues. In addition, feel free to add yourself to AUTHORS.md if you aren't already listed. --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Integration Tests Running integration tests locally Create Platform Application To run integration tests locally you will need a Custom App… # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created at [https://cloud.app.box.com/developers/console](https://cloud.app.box.com/developers/console) with `Server Authentication (with JWT)` selected as authentication method. Once created you can edit properties of the application: - In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. - In section `Advanced Features` enable `Make API calls using the as-user header` and `Generate user access tokens`. Now select `Authorization` and submit application to be reviewed by account admin. ### Export configuration There are two ways to set up JWT configuration: 1. First method: Select `Configuration` tab and in the bottom in the section `App Settings` download your app configuration settings as JSON. - Specify the path to the JWT config file in `integration_tests.cfg`, e.g. `ConfigFilePath = /Users/me/jwt-config.json` - Specify id of admin user account in `integration_tests.cfg`, e.g. `AdminUserID = 13855142101` 1. Alternatively: Select `Configuration` tab and in the bottom in the section `App Settings` download your app configuration settings as JSON. - Encode configuration file to Base64, e.g. using command: `base64 -i path_to_json_file` - Set environment variable: `JWT_CONFIG_BASE_64` with base64 encoded jwt configuration file - Set environment variable: `ADMIN_USER_ID` with id of admin user account ### Running Tests You can run all tests (unit in all supported python environments and integration) using command: ``` tox ``` To run only integration tests, you can run: ``` tox -e integration-tests ``` --- ## Untitled *Type: page* Getting raw json response The response returned by an API endpoint is being automatically translated to the corresponding object basing on… # Getting raw json response The response returned by an API endpoint is being automatically translated to the corresponding object basing on the value of the `type` field. If you want to get the raw response object, you can access response dict using `response_object` property. Example below will print the raw json response returned by the Get file information endpoint. ``` file = client.file('1122334455').get() print(json.dumps(file.response_object)) ``` --- ## Untitled *Type: page* AI AI allows to send an intelligence request to supported large language models and returns an answer based on the provided prompt and items… # AI AI allows to send an intelligence request to supported large language models and returns an answer based on the provided prompt and items. - [Send AI request](#send-ai-request) - [Send AI text generation request](#send-ai-text-generation-request) - [Get AI agent default configuration](#get-ai-agent-default-configuration) ## Send AI request Calling the [`client.send_ai_question(items, prompt, mode, ai_agent)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.send_ai_question) method will send an AI request to the supported large language models. The `items` parameter is a list of items to be processed by the LLM, often files. The `prompt` provided by the client to be answered by the LLM. The prompt's length is limited to 10000 characters. The `mode` specifies if this request is for a single or multiple items. If you select `single_item_qa` the items array can have one element only. Selecting `multiple_item_qa` allows you to provide up to 25 items. The `ai_agent` specifies the AI agent which will be used to handle queries. ``` items = [{ "id": "1582915952443", "type": "file", "content": "More information about public APIs" }] ai_agent = { 'type': 'ai_agent_ask', 'basic_text_multi': { 'model': 'openai__gpt_3_5_turbo' } } answer = client.send_ai_question( items=items, prompt="What is this file?", mode="single_item_qa", ai_agent=ai_agent ) print(answer) ``` NOTE: The AI endpoint may return a 412 status code if you use for your request a file which has just been updated to the box. It usually takes a few seconds for the file to be indexed and available for the AI endpoint. ## Send AI text generation request Calling the [`client.send_ai_text_gen(dialogue_history, items, prompt, ai_agent)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.send_ai_text_gen) method will send an AI text generation request to the supported large language models. The `dialogue_history` parameter is history of prompts and answers previously passed to the LLM. This provides additional context to the LLM in generating the response. The `items` parameter is a list of items to be processed by the LLM, often files. The `prompt` provided by the client to be answered by the LLM. The prompt's length is limited to 10000 characters. The `ai_agent` specifies the AI agent which will be used for generating text. ``` items = [{ "id": "1582915952443", "type": "file", "content": "More information about public APIs" }] dialogue_history = [{ "prompt": "Make my email about public APIs sound more professional", "answer": "Here is the first draft of your professional email about public APIs", "created_at": "2013-12-12T10:53:43-08:00" }, { "prompt": "Can you add some more information?", "answer": "Public API schemas provide necessary information to integrate with APIs...", "created_at": "2013-12-12T11:20:43-08:00" }] ai_agent = { 'type': 'ai_agent_text_gen', 'basic_gen': { 'model': 'openai__gpt_3_5_turbo_16k' } } answer = client.send_ai_text_gen( dialogue_history=dialogue_history, items=items, prompt="Write an email to a client about the importance of public APIs.", ai_agent=ai_agent ) print(answer) ``` ## Get AI agent default configuration To get an AI agent default configuration call the [`client.get_ai_agent_default_config(mode, language, model)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_ai_agent_default_config) method. The `mode` parameter filters the agent configuration to be returned. It can be either `ask` or `text_gen`. The `language` parameter specifies the ISO language code to return the agent config for. If the language is not supported, the default agent configuration is returned. The `model` parameter specifies the model for which the default agent configuration should be returned. ``` config = client.get_ai_agent_default_config( mode='text_gen', language='en', model='openai__gpt_3_5_turbo' ) print(config) ``` --- ## Untitled *Type: page* Authentication The Box API uses OAuth2 for authentication, which can be difficult to implement. The SDK makes it easier by providing classes… # Authentication The Box API uses OAuth2 for authentication, which can be difficult to implement. The SDK makes it easier by providing classes that handle obtaining tokens and automatically refreshing them when possible. See the [OAuth 2 overview](https://developer.box.com/en/guides/authentication/) for a detailed overview of how the Box API handles authentication. [Ways to Authenticate](#ways-to-authenticate) - [Developer Token](#developer-token) - [Server Auth with JWT](#server-auth-with-jwt) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) [Traditional 3-Legged OAuth2](#traditional-3-legged-oauth2) - [Redirect to Authorization URL](#redirect-to-authorization-url) - [Authenticate (Get Token Pair)](#authenticate-get-token-pair) - [Initialize a Client Given Access and Refresh Token](#initialize-a-client-given-access-and-refresh-token) [Box View Authentication with App Tokens](#box-view-authentication-with-app-tokens) [As-User](#as-user) [Downscoping token](#downscoping-token) [Revoking Tokens](#revoking-tokens) ## Ways to Authenticate ### Developer Token The fastest way to get started using the API is with developer tokens. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. For manual testing in a Python REPL, you can interactively create a [`DevelopmentClient`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#module-boxsdk.client.development_client). This client will prompt for a new developer token any time the current one expires, and will automatically log API requests and responses for testing and debugging. ``` >>> from boxsdk import DevelopmentClient >>> client = DevelopmentClient() Enter developer token: <ENTER DEVELOPER TOKEN HERE> >>> me = client.user().get() GET https://api.box.com/2.0/users/me {'headers': {'Authorization': '---wXyZ', 'User-Agent': 'box-python-sdk-2.0.0', 'X-Box-UA': 'agent=box-python-sdk/2.0.0; env=python/3.6.5'}, 'params': None} "GET https://api.box.com/2.0/users/me" 200 454 {'Date': 'Tue, 30 Oct 2018 20:57:36 GMT', 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Strict-Transport-Security': 'max-age=31536000', 'Cache-Control': 'no-cache, no-store', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'BOX-REQUEST-ID': '0dnjcjpu1krfunto6s7mrpal2ba', 'Age': '0'} {'address': '', 'avatar_url': 'https://cloud.app.box.com/api/avatar/large/33333', 'created_at': '2012-06-07T11:14:50-07:00', 'id': '33333', 'job_title': '', 'language': 'en', 'login': 'user@example.com', 'max_upload_size': 16106127360, 'modified_at': '2018-10-29T12:13:57-07:00', 'name': 'Example User', 'phone': '', 'space_amount': 1000000000000000.0, 'space_used': 14330011102, 'status': 'active', 'timezone': 'America/Los_Angeles', 'type': 'user'} >>> ``` To create a [`Client`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client) non-interactively with a developer token, construct an [`OAuth2`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.oauth2.OAuth2) object with the `access_token` set to the developer token and construct the client with that. ``` from boxsdk import Client, OAuth2 auth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', access_token='DEVELOPER_TOKEN_GOES_HERE', ) client = Client(auth) me = client.user().get() print(f'My user ID is {me.id}') ``` ### Server Auth with JWT Authenticating with a JWT requires some extra dependencies. To get them, simply ``` pip install "boxsdk[jwt]" ``` Server auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/en/guides/authentication/user-types/app-users/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. If you generated your public and private keys automatically through the [Box Developer Console](https://app.box.com/developers/console), you can use the JSON file created there to configure your SDK instance and create a client to make calls as the Service Account by calling the appropriate static [`JWTAuth`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.jwt_auth.JWTAuth) method: ``` from boxsdk import JWTAuth, Client auth = JWTAuth.from_settings_file('/path/to/settings.json') client = Client(auth) service_account = client.user().get() print(f'Service Account user ID is {service_account.id}') ``` Otherwise, you'll need to provide the necessary configuration fields directly to the [`JWTAuth`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.jwt_auth.JWTAuth) constructor: ``` from boxsdk import JWTAuth, Client service_account_auth = JWTAuth( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', enterprise_id='YOUR_ENTERPRISE_ID', jwt_key_id='YOUR_JWT_KEY_ID', rsa_private_key_file_sys_path='CERT.PEM', rsa_private_key_passphrase='PASSPHRASE', store_tokens=your_store_tokens_callback_method, ) access_token = auth.authenticate_instance() service_account_client = Client(auth) ``` App auth applications also often have associated App Users, which are [created and managed directly by the application](https://developer.box.com/en/guides/authentication/user-types/app-users/) — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user to make calls as that user. See the [API documentation](https://developer.box.com/) for detailed instructions on how to use app auth. Clients for making calls as an App User can be created with the same [`JWTAuth`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.jwt_auth.JWTAuth) constructor as in the above examples, similarly to creating a Service Account client. Simply pass the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) object for the app user instead of an `enterprise_id` when constructing the auth instance: ``` app_user = service_account_client.user(user_id='APP_USER_ID') app_user_auth = JWTAuth( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', user=app_user, jwt_key_id='YOUR_JWT_KEY_ID', rsa_private_key_file_sys_path='CERT.PEM', rsa_private_key_passphrase='PASSPHRASE', store_tokens=your_store_tokens_callback_method, ) app_user_auth.authenticate_user() app_user_client = Client(app_user_auth) ``` ### Client Credentials Grant Allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using a service or user account. You can use `CCGAuth` to initialize a client object the same way as for other authentication types: ``` auth = CCGAuth( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user="YOUR_USER_ID" ) client = Client(auth) print(f'Id of the authenticated user is: {client.user().get().id}') ``` Obtained token is valid for specified amount of time, it will be refreshed automatically by default. #### Obtaining Service Account token The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID with client id and secret: ``` auth = CCGAuth( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", enterprise_id="YOUR_ENETRPRISE_ID" ) ``` Remember that you can still make calls on behalf of managed users, which are part of your enterprise, by using [As-User](#as-user) bahaviour. #### Obtaining User token To obtain user account you will have to provide user ID with client id and secret ``` auth = CCGAuth( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user="YOUR_USER_ID" ) ``` In order to enable obtaining user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/console). In`Configuration` tab, in section `Advanced Features` select `Generate user access tokens`. Do not forget to re-authorize application if it was already authorized. ### Traditional 3-Legged OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/en/guides/authentication/oauth2/). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code. After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirect_uri` which will contain an auth code. This auth code can then be used along with your client ID and client secret to establish an API connection. #### Redirect to Authorization URL The first step in the process is to redirect the user to the Box Authorize URL, which you can generate (along with a CSRF token) by calling [`oauth.get_authorization_url(redirect_url)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.oauth2.OAuth2.get_authorization_url) with your application's redirect URL. ``` from boxsdk import OAuth2 oauth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', store_tokens=your_store_tokens_callback_method, ) auth_url, csrf_token = oauth.get_authorization_url('http://YOUR_REDIRECT_URL') # Redirect user to auth_url, where they will enter their Box credentials ``` The SDK will keep the tokens in memory for the duration of the Python script run, so you don't always need to pass `store_tokens`. #### Authenticate (Get Token Pair) If you navigate the user to the auth_url, the user will be redirected to `https://YOUR_REDIRECT_URL?code=YOUR_AUTH_CODE&state=CSRF_TOKEN` after they log in to Box. After getting the auth code, you will be able to exchange it for an access token and refresh token. The SDK handles all the work for you; all you need to do is call [`oauth.authenticate(auth_code)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.oauth2.OAuth2.authenticate) with the auth code pulled from the query parameters of the incoming URL: ``` from boxsdk import Client # Make sure that the csrf token you get from the `state` parameter # in the final redirect URI is the same token you get from the # get_authorization_url method to protect against CSRF vulnerabilities. assert 'THE_CSRF_TOKEN_YOU_GOT' == csrf_token access_token, refresh_token = oauth.authenticate('YOUR_AUTH_CODE') client = Client(oauth) ``` #### Initialize a Client Given Access and Refresh Token You can also instantiate a client given the access and refresh token. You first need to construct an [OAuth2](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.oauth2.OAuth2) object with the access and refresh token passed in. Once you have created the oauth object you then pass it into your [Client](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client) object to instantiate your client. Finally, you can begin making calls with your client. ``` from boxsdk import Client, OAuth2 oauth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', access_token='ACCESS_TOKEN', refresh_token='REFRESH_TOKEN', ) client = Client(oauth) user = client.user().get() print(f'User ID is {user.id}') ``` ### Box View Authentication with App Tokens [Box View](https://developer.box.com/en/guides/embed/box-view/) uses a long-lived access token that is generated from the [Box Developer Console](https://app.box.com/developers/console) to make API calls. These access tokens cannot be automatically refreshed from the SDK, and must be manually changed in your application code. To use the primary or secondary access token generated in the Developer Console, simply create a [`Client`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client) with that token: ``` from boxsdk import Client, OAuth2 auth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='', access_token='APP_ACCESS_TOKEN_GOES_HERE' ) client = Client(auth) ``` ## As-User The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an `As-User: USER-ID` header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). The following examples assume that the `client` has been instantiated with an access token belonging to an admin-level user or Service Account with appropriate privileges to make As-User calls. Calling the [`client.as_user(user)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.cloneable.Cloneable.as_user) method with the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) creates a new client to impersonate the provided user. All calls made with the new client will be made in context of the impersonated user, leaving the original client unmodified. ``` user_to_impersonate = client.user(user_id='USER_ID_GOES_HERE') user_client = client.as_user(user_to_impersonate) ``` ## Downscoping token You can downscope a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). This is useful if you want to use the [Box UI Elements](https://developer.box.com/en/guides/embed/ui-elements/), since they generally do not need full read/write permissions to run. To exchange the token held by a client for a new token with only `item_preview` scope, restricted to a single file, suitable for the [Content Preview UI Element](https://developer.box.com/en/guides/embed/ui-elements/preview/), call [`client.downscope_token(scopes, item=None, additional_data=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.downscope_token) with the scope(s) needed. This method returns a [`TokenResponse`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.oauth2.TokenResponse) object with the downscoped token information. ``` target_file = client.file(file_id='FILE_ID_HERE') token_info = client.downscope_token(['item_preview'], target_file) downscoped_client = Client( OAuth2( client_id=None, client_secret=None, access_token=token_info.access_token ) ) ``` But bear in mind that there is no way of refreshing this token, and you will need to add you own logic to do that. ## Revoking Tokens To revoke the tokens contained in an [`OAuth2`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.oauth2.OAuth2) instance, removing the ability to call the Box API, call [`oauth.revoke()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.auth.html#boxsdk.auth.oauth2.OAuth2.revoke). ``` oauth.revoke() ``` --- ## Untitled *Type: page* Collaborations Collaborations are used to share folders between users or groups. They also define what permissions a user has for a folder… # Collaborations Collaborations are used to share folders between users or groups. They also define what permissions a user has for a folder. - [Add a Collaboration](#add-a-collaboration) - [Edit a Collaboration](#edit-a-collaboration) - [Remove a Collaboration](#remove-a-collaboration) - [Get a Collaboration's Information](#get-a-collaborations-information) - [List Collaborations on a Folder or File](#list-collaborations-on-a-folder-or-file) - [List Pending Collaborations](#list-pending-collaborations) - [Accept or Reject a Pending Collaboration](#accept-or-reject-a-pending-collaboration) ## Add a Collaboration You can add a collaboration on a folder or a file by calling [`item.collaborate(accessible_by, role, can_view_path=None, notify=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.collaborate). Pass the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) or [`Group`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group) to collaborate the item with as the `accessible_by` parameter. The `role` parameter determines what permissions the collaborator will have on the folder. This method returns a [`Collaboration`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration) object representing the new collaboration on the item. ``` from boxsdk.object.collaboration import CollaborationRole user = client.user(user_id='11111') collaboration = client.folder(folder_id='22222').collaborate(user, CollaborationRole.VIEWER) collaborator = collaboration.accessible_by item = collaboration.item has_accepted = 'has' if collaboration.status == 'accepted' else 'has not' print(f'{collaborator.name} {has_accepted} accepted the collaboration to folder "{item.name}"') ``` Alternatively, you can also invite a user with their email address. ``` from boxsdk.object.collaboration import CollaborationRole email_of_invitee = 'testuser@example.com' collaboration = client.folder(folder_id='22222').collaborate_with_login(email_of_invitee, CollaborationRole.VIEWER) ``` Or, you can invite a group using the group id ``` from boxsdk.object.collaboration import CollaborationRole group = client.group(group_id='11111') collaboration = client.folder(folder_id='22222').collaborate(group, CollaborationRole.VIEWER) collaborator = collaboration.accessible_by item = collaboration.item has_accepted = 'has' if collaboration.status == 'accepted' else 'has not' print(f'{collaborator.name} {has_accepted} accepted the collaboration to folder "{item.name}"') ``` **Note:** The `can_view_path` parameter is currently only available for collaborations on folders. ## Edit a Collaboration A collaboration can be edited by calling [`collaboration.update_info(*, data=None, role=None, status=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration.update_info). Note that `role` fields is always required when updating a collaboration. This method returns an updated [`Collaboration`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration) object, leaving the original unmodified. ``` from boxsdk.object.collaboration import CollaborationRole collaboration_update = {'role': CollaborationRole.EDITOR, 'can_view_path': False} collaboration = client.collaboration(collab_id='12345') updated_collaboration = collaboration.update_info(data=collaboration_update) ``` ## Remove a Collaboration A collaboration can be removed by calling [`collaboration.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This will generally cause the user or group associated with the collaboration to lose access to the item. This method returns `True` to indicate that removal succeeded. ``` collaboration_id = '1111' client.collaboration(collaboration_id).delete() ``` ## Get a Collaboration's Information To get information about a specific collaboration, call [`collaboration.get()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get). This method returns a new [`Collaboration`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration) with fields populated by data from the API. ``` collaboration = client.collaboration(collab_id='12345').get() ``` ## List Collaborations on a Folder or File To retrieve all collaborations on a specified [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) or [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File), call [`item.get_collaborations(limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.get_collaborations). This method returns a `BoxObjectCollection` that you can use to iterate over all [`Collaboration`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration) objects in the collection. ``` collaborations = client.folder(folder_id='22222').get_collaborations() for collab in collaborations: target = collab.accessible_by print(f'{target.type.capitalize()} {target.name} is collaborated on the folder') ``` ``` collaborations = client.file(file_id='11111').get_collaborations() for collab in collaborations target = collab.accessible_by print(f'{target.type.capitalize()} {target.name} is collaborated on the file') ``` ## List Pending Collaborations To retrieve all pending collaborations for the current user, call [`client.get_pending_collaborations(limit=None, offset=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_pending_collaborations). The user can accept or reject these collaborations. This method returns a `BoxObjectCollection` that you can use to iterate over all pending [`Collaboration`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration) objects in the collection. ``` pending_collaborations = client.get_pending_collaborations() for pending_collaboration in pending_collaborations: print(f'Collaboration {pending_collaboration.id} is pending') ``` ## Accept or Reject a Pending Collaboration To accept or reject a pending collaboration, call [`collaboration.accept()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration.accept) or [`collaboration.reject()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration.reject). These methods both return the updated [`Collaboration`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration) object, leaving the original unmodified. ``` accepted_collab = client.collaboration(collab_id='12345').accept() rejected_collab = client.collaboration(collab_id='98765').reject() ``` --- ## Untitled *Type: page* Collections Collections allow users to mark specific files, folders and web links to make it easier to find them. Get a User's Collections… # Collections Collections allow users to mark specific files, folders and web links to make it easier to find them. - [Get a User's Collections](#get-a-users-collections) - [Get the Items in a Collection](#get-the-items-in-a-collection) - [Add an Item to a Collection](#add-an-item-to-a-collection) - [Remove an Item from a Collection](#remove-an-item-from-a-collection) ## Get a User's Collections To get all collections belonging to a user, call [`client.collections(limit=None, offset=0, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.collections). This method returns a `BoxObjectCollection` that you can use to iterate over all the [`Collection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collection.Collection) objects in the set. ``` collections = client.collections() for collection in collections: print(f'Collection "{collection.name}" has ID {collection.id}') ``` ## Get the Items in a Collection To retrieve a list of items contained in a collection, call [`collection.get_items(limit=None, offset=0, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collection.Collection.get_items). This method returns a `BoxObjectCollection` that you can use to iterate over all the [`BaseItem`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem) objects in the collection. [`BaseItem`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem) is a super class for files, folders and web links. ``` items = client.collection(collection_id='12345').get_items() for item in items: print(f'{item.type.capitalize()} "{item.name}" is in the collection') ``` ## Add an Item to a Collection To add an [`BaseItem`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem) to a collection, call [`item.add_to_collection(collection)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.add_to_collection) with the [`Collection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collection.Collection) you want to add the item to. This method returns the updated [`BaseItem`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem) object. ``` collection = client.collection(collection_id='12345') updated_file = client.file(file_id='11111').add_to_collection(collection) print(f'File "{updated_file.name}" added to collection!') ``` ## Remove an Item from a Collection To remove an [`BaseItem`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem) from a collection, call [`item.remove_from_collection(collection)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.remove_from_collection) with the [`Collection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collection.Collection) you want to remove the item from. This method returns the updated [`BaseItem`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem) object. ``` collection = client.collection(collection_id='12345') updated_file = client.file(file_id='11111').remove_from_collection(collection) print(f'File "{updated_file.name}" removed from collection!') ``` --- ## Untitled *Type: page* Classifications Classifications are a type of metadata that allows users and applications to define and assign a content classification to… # Classifications Classifications are a type of metadata that allows users and applications to define and assign a content classification to files and folders. Classifications use the metadata APIs to add and remove classifications, and assign them to files. For more details on metadata templates please see the [metadata documentation](https://developer.box.com/4b82910df764450d235d9ae5068029b3/metadata.md). - [Add initial classifications](#add-initial-classifications) - [List all classifications](#list-all-classifications) - [Add another classification](#add-another-classification) - [Update a classification](#update-a-classification) - [Delete a classification](#delete-a-classification) - [Delete all classifications](#delete-all-classifications) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Get classification on file](#get-classification-on-file) - [Remove classification from file](#remove-classification-from-file) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Get classification on folder](#get-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Add initial classifications If an enterprise does not already have a classification defined, the first classification(s) can be added with the `client.create_metadata_template(display_name, fields, template_key=None, hidden=False, scope='enterprise')`]([https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_metadata_template](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_metadata_template)) method. ``` from boxsdk.object.metadata_template import MetadataField, MetadataFieldType fields = [ MetadataField(MetadataFieldType.ENUM, 'Classification', key='Box__Security__Classification__Key', options=['Top Secret']) ] template = client.create_metadata_template('Classification', fields, template_key='securityClassification-6VMVochwUWo') ``` ## List all classifications To retrieve a list of all the classifications in an enterprise call the [`client.metadata_template(scope, template_key)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.metadata_template) method to get the classifications template, which will contain a list of all the classifications. ``` template = client.metadata_template('enterprise', 'securityClassification-6VMVochwUWo').get() ``` ## Add another classification To add another classification, call the [`template.start_update()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate.start_update) API to start making changes to the template, and then call the [`template.update_info(updates=new_updates)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate.update_info) with the changes to apply to the template. ``` template = client.metadata_template('enterprise', 'securityClassification-6VMVochwUWo') new_updates = template.start_update() new_updates.add_enum_option('Box__Security__Classification__Key', 'Sensitive') updated_template = template.update_info(updates=new_updates) ``` ## Update a classification To update a classification, call the [`template.start_update()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate.start_update) API to start making changes to the template, and then call the [`template.update_info(updates=new_updates)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate.update_info) with the classification to change on the template. ``` template = client.metadata_template('enterprise', 'securityClassification-6VMVochwUWo') new_updates = template.start_update() new_updates.edit_enum_option('Box__Security__Classification__Key', 'Sensitive', 'Very Sensitive') updated_template = template.update_info(updates=new_updates) ``` ## Add classification to file To add a classification to a file, call [`file.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) with the name of the classification template, as well as the details of the classification to add to the file. ``` classification = { 'Box__Security__Classification__Key': 'Sensitive', } applied_metadata = client.file(file_id='11111').metadata(scope='enterprise', template='securityClassification-6VMVochwUWo').set(classification) ``` ## Update classification on file To update a classification on a file, call [`file.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) with the name of the classification template, as well as the details of the classification to add to the file. ``` classification = { 'Box__Security__Classification__Key': 'Sensitive', } applied_metadata = client.file(file_id='11111').metadata(scope='enterprise', template='securityClassification-6VMVochwUWo').set(classification) ``` ## Get classification on file Retrieve the classification on a file by calling [`file.metadata(scope='global', template='properties').get()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.get) on a file. ``` metadata = client.file(file_id='11111').metadata(scope='enterprise', template='securityClassification-6VMVochwUWo').get() ``` ## Remove classification from file A classification can be removed from a file by calling [`file.metadata(scope='global', template='properties').delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.delete). ``` client.file(file_id='11111').metadata(scope='securityClassification-6VMVochwUWo', template='myMetadata').delete() ``` ## Add classification to folder To add a classification to a folder, call [`folder.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) with the name of the classification template, as well as the details of the classification to add to the folder. ``` classification = { 'Box__Security__Classification__Key': 'Sensitive', } applied_metadata = client.folder(folder_id='11111').metadata(scope='enterprise', template='securityClassification-6VMVochwUWo').set(classification) ``` ## Update classification on folder To update a classification on a folder, call [`folder.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) with the name of the classification template, as well as the details of the classification to add to the folder. ``` classification = { 'Box__Security__Classification__Key': 'Sensitive', } applied_metadata = client.folder(folder_id='11111').metadata(scope='enterprise', template='securityClassification-6VMVochwUWo').set(classification) ``` ## Get classification on folder Retrieve the classification on a folder by calling [`folder.metadata(scope='global', template='properties').get()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.get) on a folder. ``` metadata = client.folder(folder_id='11111').metadata(scope='enterprise', template='securityClassification-6VMVochwUWo').get() ``` ## Remove classification from folder A classification can be removed from a folder by calling [`folder.metadata(scope='global', template='properties').delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.delete). ``` client.folder(folder_id='11111').metadata(scope='securityClassification-6VMVochwUWo', template='myMetadata').delete() ``` --- ## Untitled *Type: page* Collaboration Allowlist The Collaboration Allowlist API allows you to manage a set of approved domains (i.e. a allowlist) that can… # Collaboration Allowlist The Collaboration Allowlist API allows you to manage a set of approved domains (i.e. a allowlist) that can collaborate with your enterprise. You can also manage whether the allowlisted domains are approved for outbound or inbound collaboration. It is important to note that the collaboration allowlist functionality is only available to customers with Box Governance. - [List Collaboration Allowlist Entries](#list-collaboration-allowlist-entries) - [Get Information for Collaboration Allowlist Entry](#get-information-for-collaboration-allowlist-entry) - [Allowlist a Domain for Collaboration](#allowlist-a-domain-for-collaboration) - [Remove a Domain from Allowlist](#remove-a-domain-from-allowlist) - [List Exempt Users](#list-exempt-users) - [Get Exempt User Information](#get-exempt-user-information) - [Exempt User from Allowlist](#exempt-user-from-allowlist) - [Remove User Exemption](#remove-user-exemption) ## List Collaboration Allowlist Entries To retrieve a list of collaboration allowlist entries, call [`collaboration_allowlist.get_entries(limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist.CollaborationAllowlist.get_entries). This method returns a `BoxObjectCollection` which can iterate over the [`CollaborationAllowlistEntry`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist_entry.CollaborationAllowlistEntry) objects in the collection. ``` allowlist_entries = client.collaboration_allowlist().get_entries() for entry in allowlist_entries: direction = entry.direction if entry.direction != 'both' else 'bidirectional' print(f'Domain {entry.domain} is allowlisted for {direction} collaboration') ``` ## Get Information for Collaboration Allowlist Entry To get information about a collaboration allowlist entry, use [`collaboration_allowlist_entry.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get). This method returns a [`CollaborationAllowlistEntry`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist_entry.CollaborationAllowlistEntry) object with fields populated by data form the API. ``` allowlist_entry = client.collaboration_allowlist_entry(entry_id='11111').get() ``` ## Allowlist a Domain for Collaboration To allowlist a domain for collaboration, call [`collaboration_allowlist.add_domain(domain, direction)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist.CollaborationAllowlist.add_domain) with the domain to allowlist and the direction(s) collaboration should be allowed in. This method returns a [`CollaborationAllowlistEntry`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist_entry.CollaborationAllowlistEntry) object representing the newly-allowlisted domain. You can determine the direction of the allowlist by passing in 'outbound', 'inbound', or 'both'. Outbound collaboration is defined as a user in your enterprise collaborating on content owned by someone outside your enterprise. Inbound collaboration is defined as a user outside of your enterprise collaborating on content owned by your enterprise. ``` from boxsdk.object.collaboration_allowlist import AllowlistDirection domain = 'example.com' allowlist_entry = client.collaboration_allowlist().add_domain(domain, direction=AllowlistDirection.INBOUND) ``` ## Remove a Domain from Allowlist To remove a collaboration allowlisted domain, call [`collaboration_allowlist_entry.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This will remove the domain from the allowlist, restricting collaboration to and from users in that domain. This method returns `True` to indicate that deletion was successful. ``` client.collaboration_allowlist_entry(entry_id='11111').delete() ``` ## List Exempt Users To get all exempt users from the collaboration allowlist, call [`collaboration_allowlist.get_exemptions(limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist.CollaborationAllowlist.get_exemptions). This method returns a `BoxObjectCollection` that allows you to iterate over each [`CollaborationAllowlistExemptTarget`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist_exempt_target.CollaborationAllowlistExemptTarget) in the collection. ``` exemptions = client.collaboration_allowlist().get_exemptions() for exemption in exemptions: print(f'{exemption.user.name} (ID: {exemption.user.id}) is exempt from the collaboration allowlist') ``` ## Get Exempt User Information To get information about an exempted user, call [`collaboration_allowlist_exempt_target.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get). This method will return a [`CollaborationAllowlistExemptTarget](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist_exempt_target.CollaborationAllowlistExemptTarget) with fields populated by data from the API. ``` exemption_id = '11111' exemption = client.collaboration_allowlist_exempt_target(exemption_id).get() ``` ## Exempt User from Allowlist To exempt a user from the collaboration allowlist, call [`collaboration_allowlist.add_exemption(user)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist.CollaborationAllowlist.add_exemption) with the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) to exempt from the allowlist. This user will no longer be subject to the collaboration allowlist, and will be permitted to collaborate with users from any other domain. This method returns a [`CollaborationAllowlistExemptTarget`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration_allowlist_exempt_target.CollaborationAllowlistExemptTarget) object representing the exempted user. ``` user = client.user(user_id='11111') exemption = client.collaboration_allowlist().add_exemption(user) ``` ## Remove User Exemption To remove a user exemption from the collaboration allowlist, call [`collaboration_allowlist_exempt_target.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This will remove the exemption and make the user subject to the collaboration allowlist again. This method returns `True` to indicate that deletion was successful. ``` client.collaboration_allowlist_exempt_target(exemption_id='22222').delete() ``` --- ## Untitled *Type: page* Device Pins Device pinning is a feature that allows enterprise admins to pin their user’s corporate-managed Box account to a particular… # Device Pins Device pinning is a feature that allows enterprise admins to pin their user’s corporate-managed Box account to a particular mobile device or Box Sync client. - [List Enterprise Device Pins](#list-enterprise-device-pins) - [Get Device Pin Information](#get-device-pin-information) - [Delete Device Pin](#delete-device-pin) ## List Enterprise Device Pins To retrieve all device pins for an enterprise, call [`client.device_pinners(enterprise=None, limit=None, marker=None, direction=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.device_pinners). If an `enterprise` is not specified, this defaults to the current enterprise. This method returns a `BoxObjectCollection` that allows you to iterate over the [`DevicePinner`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.device_pinner.DevicePinner) objects in the collection. ``` device_pins = client.device_pinners() for pin in device_pins: print(f'Pinned {pin.product_name} device for {pin.owned_by.name}') ``` ## Get Device Pin Information To get information about a specific device pin, call [`device_pinner.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get). This method returns a new [`DevicePinner`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.device_pinner.DevicePinner) object with fields populated by data from the API. ``` device_pin_id = '1111' device_pin = client.device_pinner(device_pin_id).get() print(f'{pin.product_name} device for {pin.owned_by.name} is pinned') ``` ## Delete Device Pin To delete a specific device pin, call [`device_pinner.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion was successful. ``` device_pin_id = '1111' client.device_pin(device_pin_id).delete() print('Device pin deleted!') ``` --- ## Untitled *Type: page* Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. Get Information About a Comment… # Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. - [Get Information About a Comment](#get-information-about-a-comment) - [Get the Comments on a File](#get-the-comments-on-a-file) - [Add a Comment to a File](#add-a-comment-to-a-file) - [Reply to a Comment](#reply-to-a-comment) - [Edit a Comment](#edit-a-comment) - [Delete a Comment](#delete-a-comment) ## Get Information About a Comment To get a specific comment object, first call `[client.comment(comment_id)`][comment](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.comment) to construct the appropriate [`Comment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.comment.Comment) object, and then call [`comment.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) to retrieve the data about the comment. The latter method returns a new [`Comment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.comment.Comment) object with fields populated by data from the API, leaving the original unmodified. ``` comment = client.comment(comment_id='55555').get() print(f'The comment says "{comment.message}"') ``` ## Get the Comments on a File To retrieve the comment left on a file, call [`file.get_comments(limit=None, offset=0, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_comments). This method returns a `BoxObjectCollection` that you can use to iterate over all the [`Comment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.comment.Comment) objects in the set. ``` comments = client.file(file_id='11111').get_comments() for comment in comments: print(f'Comment was left by {comment.created_by.name} at {comment.created_at}') ``` ## Add a Comment to a File To leave a comment on a file, call [`file.add_comment(message)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.add_comment) with the message to leave in the comment. ``` comment = client.file(file_id='11111').add_comment('When should I have this done by?') ``` You can at-mention other users by adding special tags within the message, in the format `@[USER_ID:USER_NAME]`. For example, to at-mention John Doe, whose user ID is `"33333"`: `@[33333:John Doe]`. ``` comment = client.file(file_id='11111').add_comment('Hey @[44444:boss], when should I have this done by?') ``` This method returns a [`Comment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.comment.Comment) object representing the newly-created comment. ## Reply to a Comment To reply to a comment, call [`comment.reply(message)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.comment.Comment.reply) with the message to leave in the comment. ``` reply_comment = client.comment(comment_id='12345').reply('If possible, please finish this by the end of the week!') ``` You can at-mention other users by adding special tags within the message, in the format `@[USER_ID:USER_NAME]`. For example, to at-mention John Doe, whose user ID is `"33333"`: `@[33333:John Doe]`. ``` reply_comment = client.comment(comment_id='12345').reply('@[33333:John Doe], if possible, please finish this by the end of the week!') ``` This method returns a [`Comment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.comment.Comment) object representing the newly-created comment. ## Edit a Comment To edit a comment and change its message, call [`comment.edit(message)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.comment.Comment.edit) with the message to leave in the comment. You can at-mention other users by adding special tags within the message, in the format `@[USER_ID:USER_NAME]`. For example, to at-mention John Doe, whose user ID is `"33333"`: `@[33333:John Doe]`. This method returns an updated [`Comment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.comment.Comment) object, leaving the original unmodified. ``` edited_comment = client.comment(comment_id='98765').edit('If possible, please finish this by Friday!') ``` ## Delete a Comment To delete a comment, call [`comment.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This will remove the comment from the file. This method returns `True` to indicate that the deletion succeeded. ``` client.comment(comment_id='12345').delete() ``` --- ## Untitled *Type: page* Configuration The Python SDK has helpful custom config that you can set for a variety of use cases. Proxy Unauthenticated Proxy Basic… # Configuration The Python SDK has helpful custom config that you can set for a variety of use cases. [Proxy](#proxy) - [Unauthenticated Proxy](#unauthenticated-proxy) - [Basic Authentication Proxy](#basic-authentication-proxy) [Configure URLs](#configure-urls) - [Base URL](#base-url) - [OAUTH2 URLs](#oauth2-urls) - [Upload URL](#upload-url) [Max retry attmepts](#max-retry-attmepts) ## Proxy ### Unauthenticated Proxy In order to set up configuration for basic proxy with the Python SDK, simply specify the proxy address for the `Proxy.URL` field. ``` from boxsdk.config import Proxy Proxy.URL = 'http://example-proxy-address.com' ``` ### Basic Authentication Proxy The Python SDK also lets you set an authenticated proxy. To do this, specify the `user` and `password` fields and pass set that on the `Proxy.AUTH` field. ``` from boxsdk.config import Proxy Proxy.AUTH = { 'user': 'test_user', 'password': 'test_password', } ``` ## URLs configuration ### Base URL The default base URL used for making API calls to Box can be changed by setting the value of the `API.BASE_API_URL` field. ``` from boxsdk.config import API API.BASE_API_URL = 'https://new-base-url.com' ``` ### OAUTH2 URLs The default URLs used to authorize a user and obtain OAuth2 authorization tokens can be modified by overwriting `API.OAUTH2_API_URL` and `API.OAUTH2_AUTHORIZE_URL` constants. ``` from boxsdk.config import API API.OAUTH2_API_URL = 'https://my-company.com/oauth2' API.OAUTH2_AUTHORIZE_URL = 'https://my-company.com/authorize' ``` ### Upload URL The default URL used when uploading files to Box can be changed by assigning a new value to the `API.UPLOAD_URL` field. If this variable is ever changed from default value, the SDK will alwayse use this URL to upload files to Box, even if `use_upload_session_urls` is set to `True` while creating an upload session for a chunked upload. ``` from boxsdk.config import API API.UPLOAD_URL = 'https://my-company-upload-url.com' ``` ## Max retry attmepts The default maximum number of retries in case of failed API call is 5 (usually 202, 429 and >= 500 response codes are retried). To change this number you can set `API.MAX_RETRY_ATTEMPTS` field. ``` from boxsdk.config import API API.MAX_RETRY_ATTEMPTS = 6 ``` --- ## Untitled *Type: page* Events It is possible to poll the Box API for events, in order to get information about activity within Box as it happens. The Box API… # Events It is possible to poll the Box API for events, in order to get information about activity within Box as it happens. The Box API supports two types of event streams: one for the events specific to a particular user and one for all of the events in an enterprise. [User Events](#user-events) - [Listening to the Event Stream](#listening-to-the-event-stream) - [Get the Current Stream Position](#get-the-current-stream-position) - [Get Events Manually](#get-events-manually) [Enterprise Events](#enterprise-events) - [Get Events Manually](#get-events-manually-1) ## User Events The Box API provides an events endpoint that utilizes long-polling to send events in real-time. The SDK provides a generator that automatically handles long-polling and deduplicating events. ### Listening to the Event Stream To automatically receive events as they happen, call [`events.generate_events_with_long_polling(stream_position=None, stream_type=UserEventsStreamType.ALL)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.events.Events.generate_events_with_long_polling) and iterate over the results. By default, this will start listening for events from the current time onward; to get all available events, pass a `stream_position` of `0`. The generator yields [`Event`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.event.Event) objects representing each event. ``` events = client.events().generate_events_with_long_polling() for event in events: print(f'Got {event.event_type} event') ``` ### Get the Current Stream Position It is possible to get the current stream position, which can later be used to fetch events from that point in time forward, by calling [`events.get_latest_stream_position(stream_type=UserEventsStreamType.ALL)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.events.Events.get_latest_stream_position). This method returns the current stream position value as an `int`. ``` stream_position = client.events().get_latest_stream_position() print(f'The current stream position is {stream_position}') ``` ### Get Events Manually To manually retrieve a set of events, call [`events.get_events(limit=100, stream_position=0, stream_type=UserEventsStreamType.ALL)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.events.Events.get_events). By default, this will fetch the first available events chronologically; you can pass a specific `stream_position` to get events from a particular time. This method returns a `dict` with the relevant [`Event`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.event.Event) objects in a `list` under the `entries` key and the next stream position value under the `next_stream_position` key. ``` stream_position = 0 events = client.events().get_events(stream_position=stream_position) stream_position = events['next_stream_position'] for event in events['entries']: print(f'Got {event.event_type} event that occurred at {event.created_at}') ``` ## Enterprise Events Currently, the SDK only provides a manual interface for retrieving Enterprise (or Admin) Events. ### Get Events Manually To manually retrieve a set of admin events, call [`events.get_events(limit=100, stream_position=0, stream_type=UserEventsStreamType.ALL)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.events.Events.get_events) with `stream_type` set to `EnterpriseEventsStreamType.ADMIN_LOGS`. By default, this will fetch the first available events chronologically; you can pass a specific `stream_position` to get events from a particular time. This method returns a `dict` with the relevant [`Event`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.event.Event) objects in a `list` under the `entries` key and the next stream position value under the `next_stream_position` key. ``` from boxsdk.object.events import EnterpriseEventsStreamType stream_position = 0 events = client.events().get_events(stream_type=EnterpriseEventsStreamType.ADMIN_LOGS, stream_position=stream_position) stream_position = events['next_stream_position'] for event in events['entries']: print(f'Got {event.event_type} event that occurred at {event.created_at}') ``` ### Get Admin Events The SDK also allows you to retrieve enterprise events. Use [`events.get_admin_events_streaming(self, limit=None, stream_position=0, event_types=None)`] for live monitoring (events up to two weeks, low latency) and [`events.get_admin_events(self, limit=None, stream_position=0, created_after=None, created_before=None, event_types=None)`] for historical querying (events up to one year, higher latency). If `limit` param is set to None, then default API value (limit=100) will be used. Live monitoring example ``` events = client.events() .get_admin_events_streaming() for event in events['entries']: print(f'Got {event.event_type} event that occurred at {event.created_at}') ``` Addditionally, a list of event types can be passed along to filter down the returned events. ``` events = client.events() .get_admin_events_streaming(event_types=['ITEM_CREATE']) for event in events['entries']: print(f'Got {event.event_type} event that occurred at {event.created_at}') ``` When using historical querying you can specify before and after a certain datetime and the types of events to retrieve with the `event_type` by calling [`events.get_admin_events(self, limit=None, stream_position=0, created_after=None, created_before=None, event_types=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.events.Events.get_admin_events). If `limit` param is set to None, then default API value (limit=100) will be used. The format for the `created_after` and `created_before` fields are supported by [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) and look something like this: 2019-08-12T09:12:36-00:00. For more information on the date format please see [here](https://developer.box.com/en/guides/api-calls/types-and-formats/#date-and-times). This method returns a `dict` with the relevant [`Event`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.event.Event) objects in a `list` under the `entries` key and the next stream position value under the `next_stream_position` key. ``` events = client.events() .get_admin_events(created_after='2019-07-01T22:02:24-07:00') for event in events['entries']: print(f'Got {event.event_type} event that occurred at {event.created_at}') ``` Addditionally, a list of event types can be passed along to filter down the returned events. ``` events = client.events() .get_admin_events(created_after='2019-07-01T22:02:24-07:00', event_types=['ITEM_CREATE']) for event in events['entries']: print(f'Got {event.event_type} event that occurred at {event.created_at}') ``` --- ## Untitled *Type: page* File Requests File request objects represent a file request associated with a folder. Get a File Request's Information Copy a File Request's… # File Requests File request objects represent a file request associated with a folder. - [Get a File Request's Information](#get-a-file-requests-information) - [Copy a File Request's Information](#copy-a-file-requests-information) - [Update a File Request's Information](#update-a-file-requests-information) - [Delete a File Request](#delete-a-file-request) ## Get a File Request's Information To get a file request object, first call [`client.file_request(file_request_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.file_request) to construct the appropriate [`FileRequest`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_request.FileRequest) object, and then calling [`file_request.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`FileRequest`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_request.FileRequest) object populated with data from the API, leaving the original object unmodified. ``` file_request = client.file_request(file_request_id='123456').get() print(f'File request {file_request.id} on folder {file_request.folder.name}') ``` ## Copy a File Request's Information To copy a file request, first call [`client.file_request(file_request_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.file_request) to construct the appropriate [`FileRequest`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_request.FileRequest) object, and then calling [`file_request.copy(folder, description=None, title=None, expires_at=None, require_description=None, require_email=None, status=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_request.FileRequest.copy). It will return the [`FileRequest`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_request.FileRequest) object populated with data new created file request from the API. ``` file_request = client.file_request(file_request_id='123456') folder = client.folder(folder_id='123456789') new_file_request = file_request.copy(folder=folder, title="Copied file request") ``` ## Update a File Request's Information To update a file request object, call [`file_request.update_info(data=file_request_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the file request. This method returns a newly updated [`FileRequest`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_request.FileRequest) object, leaving the original object unmodified. ``` from boxsdk.object.file_request import StatusState update_data = { "description": 'Updated description', "is_email_required": True, "status": StatusState.ACTIVE } file_request.update_info(data=update_data) ``` ## Delete a File Request To delete a file request, call [`file_request.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete), it deletes a file request permanently. ``` file_request = client.file_request(file_request_id='123456') file_request.delete() ``` --- ## Untitled *Type: page* Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a… # Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a folder with another user or group, and perform other common folder operations (move, copy, delete, etc.). - [Get Information About a Folder](#get-information-about-a-folder) - [Get the User's Root Folder](#get-the-users-root-folder) - [Get the Items in a Folder](#get-the-items-in-a-folder) - [Update a Folder](#update-a-folder) - [Create a Folder](#create-a-folder) - [Copy a Folder](#copy-a-folder) - [Move a Folder](#move-a-folder) - [Rename a File](#rename-a-file) - [Delete a Folder](#delete-a-folder) - [Find a Folder for a Shared Link](#find-a-folder-for-a-shared-link) - [Create or update a Shared Link](#create-or-update-a-shared-link) - [Get a Shared Link](#get-a-shared-link) - [Remove a Shared Link](#remove-a-shared-link) - [Set Metadata](#set-metadata) - [Get Metadata](#get-metadata) - [Remove Metadata](#remove-metadata) - [Get All Metadata](#get-all-metadata) - [Get Metadata For Folder Items](#get-metadata-for-folder-items) - [Set a Classification](#set-a-classification) - [Retrieve a Classification](#retrieve-a-classification) - [Remove a Classification](#remove-a-classification) - [Create a Folder Lock](#create-a-folder-lock) - [Get Folder Locks](#get-folder-locks) - [Delete a Folder Lock](#delete-a-folder-lock) ## Get Information About a Folder To retrieve information about a folder, first call [`client.folder(folder_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.folder) to initialize the [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object. Then, call [`folder.get(*, fields=None, etag=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.get) to retrieve data about the folder. This method returns a new [`Folder](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object with fields populated by data from the API, leaving the original object unmodified. You can pass a list of `fields` to retrieve from the API in order to filter to just the necessary fields or add ones not returned by default. ``` folder = client.folder(folder_id='22222').get() print(f'Folder "{folder.name}" has {folder.item_collection["total_count"]} items in it') ``` ## Get the User's Root Folder To get the current user's root folder, call [`client.root_folder()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.root_folder) to initialize the appropriate [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object. ``` root_folder = client.root_folder().get() ``` ## Get the Items in a Folder To retrieve the items in a folder, call [`folder.get_items(limit=None, offset=0, marker=None, use_marker=False, sort=None, direction=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.get_items). This method returns a `BoxObjectCollection` that allows you to iterate over all the [`Item`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item) objects in the collection. ``` items = client.folder(folder_id='22222').get_items() for item in items: print(f'{item.type.capitalize()} {item.id} is named "{item.name}"') ``` ## Update a Folder To update a folder's information, call [`folder.update_info(*, data, etag=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.update_info) with a `dict` of properties to update on the folder. This method returns a new updated [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object, leaving the original object unmodified. ``` updated_folder = client.folder(folder_id='22222').update_info(data={ 'name': '[ARCHIVED] Planning documents', 'description': 'Old planning documents', }) print('Folder updated!') ``` ## Create a Folder A folder can be created by calling [`folder.create_subfolder(name)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.create_subfolder) on the parent folder with the name of the subfolder to be created. This method returns a new [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) representing the created subfolder. ``` subfolder = client.folder('0').create_subfolder('My Stuff') print(f'Created subfolder with ID {subfolder.id}') ``` ## Copy a Folder A folder can be copied into a new parent folder by calling [`folder.copy(parent_folder, name=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.copy) with the destination folder and an optional new name for the file in case there is a name conflict in the destination folder. This method returns a new [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object representing the copy of the folder in the destination folder. ``` folder_id = '22222' destination_folder_id = '44444' folder_to_copy = client.folder(folder_id) destination_folder = client.folder(destination_folder_id) folder_copy = folder_to_copy.copy(parent_folder=destination_folder) print(f'Folder "{folder_copy.name}" has been copied into folder "{folder_copy.parent.name}"') ``` ## Move a Folder To move a folder from one parent folder into another, call [`folder.move(parent_folder, name=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.move) with the destination folder to move the folder into. You can optionally provide a `name` parameter to automatically rename the folder in case of a name conflict in the destination folder. This method returns the updated [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object in the new folder. ``` folder_id = '11111' destination_folder_id = '44444' folder_to_move = client.folder(folder_id) destination_folder = client.folder(destination_folder_id) moved_folder = folder_to_move.move(parent_folder=destination_folder) print(f'Folder "{moved_folder.name}" has been moved into folder "{moved_folder.parent.name}"') ``` ## Rename a File A folder can be renamed by calling [`folder.rename(name)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.rename). This method returns the updated [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object with a new name. ``` folder = client.folder(folder_id='11111') renamed_folder = folder.rename("new-name") print(f'Folder was renamed to "{renamed_folder.name}"') ``` ## Delete a Folder Calling the [`folder.delete(recursive=True, etag=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.delete) method will delete the folder. Depending on enterprise settings, this will either move the folder to the user's trash or permanently delete the folder. This method returns `True` to signify that the deletion was successful. By default, the method will delete the folder and all of its contents; to fail the deletion if the folder is not empty, set the `recursive` parameter to `False`. ``` client.folder(folder_id='22222').delete() ``` ## Find a Folder for a Shared Link To find a folder given a shared link, use the [`client.get_shared_item`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html?highlight=get_shared_item#boxsdk.client.client.Client.get_shared_item) method. ``` folder = client.get_shared_item('https://app.box.com/s/gjasdasjhasd', password='letmein') ``` ## Create or update a Shared Link A shared link for a folder can be generated or updated by calling [`folder.get_shared_link(access=None, etag=None, unshared_at=None, allow_download=None, allow_preview=None, password=None, vanity_name=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.get_shared_link). This method returns a `unicode` string containing the shared link URL. ``` folder_id = '11111' url = client.folder(folder_id).get_shared_link(access='open', allow_download=False) print(f'The folder shared link URL is: {url}') ``` ## Get a Shared Link To check for an existing shared link on a folder, simply call `folder.shared_link` This method returns a `unicode` string containing the shared link URL. ``` folder_id = '11111' shared_link = client.folder(folder_id).get().shared_link url = shared_link['url'] ``` ## Remove a Shared Link A shared link for a folder can be removed by calling [`folder.remove_shared_link(etag=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.remove_shared_link). ``` folder_id = '11111' client.folder(folder_id).remove_shared_link() ``` ## Set Metadata To set metadata on a folder call the [`folder.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) to specify the scope and template key of the metadata template to attach. Then, call the [`metadata.set(data)`][metadata_set] method with the key/value pairs to attach. This method returns a `dict` containing the applied metadata instance. Note: This method will unconditionally apply the provided metadata, overwriting the existing metadata for the keys provided. To specifically create or update metadata, see the `create()` or `update()` methods. ``` metadata = { 'foo': 'bar', } applied_metadata = client.folder(folder_id='11111').metadata(scope='enterprise', template='testtemplate').set(metadata) print(f'Set metadata in instance ID {applied_metadata["$id"]}') ``` Metadata can be added to a folder either as free-form key/value pairs or from an existing template. To add metadata to a folder, first call [`folder.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) to specify the scope and template key of the metadata template to attach (or use the default values to attach free-form keys and values). Then, call [`metadata.create(data)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.create) with the key/value pairs to attach. This method can only be used to attach a given metadata template to the folder for the first time, and returns a `dict` containing the applied metadata instance. Note: This method will only succeed if the provided metadata template is not currently applied to the folder, otherwise it will fail with a Conflict error. ``` metadata = { 'foo': 'bar', 'baz': 'quux', } applied_metadata = client.folder(folder_id='22222').metadata().create(metadata) print(f'Applied metadata in instance ID {applied_metadata["$id"]}') ``` Updating metadata values is performed via a series of discrete operations, which are applied atomically against the existing folder metadata. First, specify which metadata will be updated by calling [`folder.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata). Then, start an update sequence by calling [`metadata.start_update()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.start_update) and add update operations to the returned [`MetadataUpdate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.MetadataUpdate). Finally, perform the update by calling [`metadata.update(metadata_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.update). This final method returns a `dict` of the updated metadata instance. Note: This method will only succeed if the provided metadata template has already been applied to the folder; If the folder does not have existing metadata, this method will fail with a Not Found error. This is useful you know the file will already have metadata applied, since it will save an API call compared to `set()`. ``` folder = client.folder(folder_id='22222') folder_metadata = folder.metadata(scope='enterprise', template='myMetadata') updates = folder_metadata.start_update() updates.add('/foo', 'bar') updates.update('/baz', 'murp', old_value='quux') # Ensure the old value was "quux" before updating to "murp" updated_metadata = folder_metadata.update(updates) print('Updated metadata on folder!') print(f'foo is now {updated_metadata["foo"]} and baz is now {updated_metadata["baz"]}') ``` ## Get Metadata To retrieve the metadata instance on a folder for a specific metadata template, first call [`folder.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) to specify the scope and template key of the metadata template to retrieve, then call [`metadata.get()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.get) to retrieve the metadata values attached to the folder. This method returns a `dict` containing the applied metadata instance. ``` metadata = client.folder(folder_id='22222').metadata(scope='enterprise', template='myMetadata').get() print(f'Got metadata instance {metadata["$id"]}') ``` ## Remove Metadata To remove a metadata instance from a folder, call [`folder.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) to specify the scope and template key of the metadata template to remove, then call [`metadata.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.delete) to remove the metadata from the folder. This method returns `True` to indicate that the removal succeeded. ``` client.folder(folder_id='11111').metadata(scope='enterprise', template='myMetadata').delete() ``` ## Get All Metadata To retrieve all metadata attached to a folder, call [`folder.get_all_metadata()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.get_all_metadata). This method returns a [`BoxObjectCollection`][box_object_collection] that can be used to iterate over the `dict`s representing each metadata instance attached to the folder. ``` folder_metadata = client.folder(folder_id='22222').get_all_metadata() for instance in folder_metadata: if 'foo' in instance: print(f'Metadata instance {instance["id"]} has value "{instance["foo"]}" for foo') ``` ## Get Metadata For Folder Items When fetching folder items, you may wish to retrieve metadata for the items simultaneously to avoid needing to make an API call for each item. You can retrieve up to 3 metadata instances per item by passing the special `metadata.<scope>.<templateKey>` field to [`folder.get_items(limit=None, offset=0, marker=None, use_marker=False, sort=None, direction=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.get_items). The metadata is available as a multi-level `dict` on the returned [`Item`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item) objects. ``` fields = [ 'type', 'id', 'name', 'metadata.enterprise.vendorContract', ] items = client.folder(folder_id='22222').get_items(fields=fields) for item in items: if item.metadata: metadata = item.metadata['enterprise']['vendorContract'] print(f'{item.type.capitalize()} {item.id} is a vendor contract with vendor name {metadata["vendorName"]}') ``` ## Set a Classification It is important to note that this feature is available only if you have Governance. To add classification to a [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder), call [`folder.set_classification(classification)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.set_classification). This method returns the classification type on the [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object. If a classification already exists then this call will update the existing classification with the new [`ClassificationType`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.ClassificationType). ``` from boxsdk.object.item import ClassificationType classification = client.folder(folder_id='11111').set_classification(ClassificationType.PUBLIC) print(f'Classification Type is: {classification}') ``` The set method will always work no matter the state your [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) is in. For cases already where a classification value already exists [`set_classification(classification)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.set_classification) may make multiple API calls. Alternatively, if you already know you have a classification and you are simple updating it, you can use the [`update_classification(classification)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.update_classification). This will ultimately help you save one extra API call. ``` classification = client.folder(folder_id='11111').update_classification(ClassificationType.NONE) print(f'Classification Type is: {classification}') ``` ## Retrieve a Classification To retrieve a classification from a [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder), call [`folder.get_classification()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.get_classification). This method returns the classification type on the [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object. ``` classification = client.folder(folder_id='11111').get_classification() print(f'Classification Type is: {classification}') ``` ## Remove a Classification To remove a classification from a [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder), call [`folder.remove_classification()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.remove_classification). ``` client.folder(folder_id='11111').remove_classification() ``` ## Create a Folder Lock To lock a folder, call [`client.folder(folder_id).create_lock()`][create-folder-lock] with the ID of the folder. This prevents the folder from being moved and/or deleted. ``` lock = client.folder(folder_id).create_lock() print(f'Created a lock with ID {lock.folder.id}') ``` ## Get Folder Locks To retrieve a list of the locks on a folder, call [`client.folder(folder_id).get_locks()][get-folder-locks] with the ID of the folder. Currently only one lock can exist per folder. Folder locks define access restrictions placed by folder owners to prevent specific folders from being moved or deleted. ``` locks = client.folder(folder_id).get_locks() lock = locks.next() print(f'A lock on a folder with ID {lock.folder.id}') ``` ## Delete a Folder Lock To remove a folder lock, call [`client.folder_lock(folder_lock_id).delete()`][delete-folder-lock] with the ID of the folder lock. ``` client.folder_lock(folder_lock_id='22222').delete() ``` --- ## Untitled *Type: page* Groups Groups are sets of users that can be used in collaborations. List Groups Create a Group Get Information about a Group Update a Group… # Groups Groups are sets of users that can be used in collaborations. - [List Groups](#list-groups) - [Create a Group](#create-a-group) - [Get Information about a Group](#get-information-about-a-group) - [Update a Group](#update-a-group) - [Delete a Group](#delete-a-group) - [Get a Group's Collaborations](#get-a-groups-collaborations) - [Add User to Group](#add-user-to-group) - [Get Information about a Group Membership](#get-information-about-a-group-membership) - [Update Group Membership](#update-group-membership) - [Remove User from Group](#remove-user-from-group) - [List Group Members](#list-group-members) - [List Memberships for User](#list-memberships-for-user) ## List Groups Calling [`client.get_groups(name=None, limit=None, offset=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_groups) will return a `BoxObjectCollection` that allows you to iterate over the [`Group`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group) objects representing groups in the enterprise. ``` groups = client.get_groups() for group in groups: print(f'Group "{group.name}" has ID "{group.id}"') ``` Alternatively, you can set a filter on the name of the groups by passing the `name` parameter: ``` group_name = 'Example Group' groups = client.get_groups(group_name) for group in groups: print(f'Group {group.id} has a name matching {group_name}') ``` ## Create a Group To create a new group, call [`client.create_group(name, provenance=None, external_sync_identifier=None, description=None, invitability_level=None, member_viewability_level=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_group) with the name of the group and any optional group properties you want to set. This method returns a [`Group`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group) object representing the created group. You can read more about the optional parameters in the [Create Group API documentation](https://developer.box.com/en/reference/post-groups/). ``` created_group = client.create_group('Example Group') print(f'Created group with ID {created_group.id}') ``` ## Get Information about a Group To retrieve information about a group, first call [`client.group(group_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.group) to initialize a [`Group`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group) object. Then, call [`group.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) to retrieve the data about that group. This method returns a new [`Group`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group) object with fields populated by data form the API, leaving the original object unmodified. ``` group = client.group(group_id='11111').get() print(f'Got group {group.name}') ``` You can optionally specify a list of `fields` to retrieve from the API, in order to filter out fields you don't need or add fields that are not returned from the API by default: ``` group = client.group(group_id='11111').get(['name', 'description', 'provenance']) print(f'The "{group.name}" group ({group.description}) came from {group.provenance}') ``` ## Update a Group To update a group, call [`group.update_info(data=group_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of the group properties to update. This method returns a new [`Group`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group) object with the updates applied, leaving the original object unmodified. ``` group_update = {'name': 'New Group Name'} updated_group = client.group(group_id='11111').update_info(data=group_update) print(f'Changed the name of group {updated_group.id} to "{updated_group.name}"') ``` ## Delete a Group To delete a group, call [`group.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion was successful. ``` client.group(group_id='11111').delete() print('The group was deleted!') ``` ## Get a Group's Collaborations To retrieve all collaborations for a group, call [`group.get_collaborations(limit=None, offset=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group.get_collaborations). This method returns a `BoxObjectCollection` that allows you to iterate over the [`Collaboration`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.collaboration.Collaboration) objects in the collection. ``` collaborations = client.group(group_id='11111').get_collaborations() for collaboration in collaborations: print(f'The group is collaborated on {collaboration.item.type} {collaboration.item.id}') ``` ## Add User to Group To add a new member to the group, call [`group.add_member(user, role='member', configurable_permissions=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group.add_member) with the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) to add to the group. This method returns a new [`GroupMembership`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group_membership.GroupMembership) object representing the presence of the user in the group. You can optionally specify the user's `role` in the group, and for users with an admin role you can configure which permissions they have in the group by passing a `dict` of [group permissions](https://developer.box.com/en/reference/resources/group-membership/) to `configurable_permissions`. ``` user = client.user('1111') membership = client.group(group_id='11111').add_member(user) print(f'Added {membership.user.name} to the {membership.group.name} group!') ``` ## Get Information about a Group Membership To retrieve information about a group membership, first call [`client.group_membership(group_membership_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.group_membership) to initialize the [`GroupMembership`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group_membership.GroupMembership) object. Then, call [`group_membership.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) to retrieve data about the group membership from the API. This returns a new [`GroupMembership`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group_membership.GroupMembership) object with fields populated by data from the API, leaving the original object unmodified. ``` membership_id = '11111' membership = client.group_membership(membership_id).get() print(f'User "{membership.user.name}" is a member of the {membership.group.name} group') ``` ## Update Group Membership To update a group membership, call [`membership.update_info(data=membership_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the membership object. This method returns a new [`GroupMembership`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group_membership.GroupMembership) object with the changes applied, leaving the original object unmodified. ``` membership_id = '1234' membership_update = {'role': 'admin'} updated_membership = client.group_membership(membership_id).update_info(data=membership_update) print(f'Updated {updated_membership.user.name}\'s group role to {updated_membership.role}') ``` ## Remove User from Group To remove a user from a group, delete their associated group membership by calling [`group_membership.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion was successful. ``` membership_id = '1234' client.group_membership(membership_id).delete() print('The membership was deleted!') ``` ## List Group Members To retrieve all of the memberships for a given group, call [`group.get_memberships(limit=None, offset=0, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group.Group.get_memberships). This method returns a `BoxObjectCollection` that allows you to iterate over all of the [`GroupMembership`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group_membership.GroupMembership) objects in the collection. ``` group_memberships = client.group(group_id='11111').get_memberships() for membership in group_memberships: print(f'{membership.user.name} is a {membership.role} of the {membership.group.name} group') ``` ## List Memberships for User To retrieve all of the groups a user belongs to, get a list of their associated group memberships by calling [`user.get_group_memberships(limit=None, offset=0, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User.get_group_memberships). This method returns a `BoxObjectCollection` that allows you to iterate over the [`GroupMembership`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.group_membership.GroupMembership) objects in the collection. ``` user_memberships = client.user(user_id='33333').get_group_memberships() for membership in user_memberships: print(f'User is in the {membership.group.name} group') ``` --- ## Untitled *Type: page* Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other… # Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other common file operations (move, copy, delete, etc.). [Files](#files) - [Get a File's Information](#get-a-files-information) - [Update a File's Information](#update-a-files-information) - [Download a File](#download-a-file) - [Get Download URL](#get-download-url) - [Upload a File](#upload-a-file) [Chunked Upload](#chunked-upload) [Automatic Uploader](#automatic-uploader) - [Upload new file](#upload-new-file) - [Upload new file version](#upload-new-file-version) - [Preflight check before upload](#preflight-check-before-upload) - [Resume Upload](#resume-upload) - [Abort Chunked Upload](#abort-chunked-upload) [Manual Process](#manual-process) - [Create Upload Session for File Version](#create-upload-session-for-file-version) - [Create Upload Session for File](#create-upload-session-for-file) - [Upload Part](#upload-part) - [Commit Upload Session](#commit-upload-session) - [Abort Upload Session](#abort-upload-session) - [List Upload Parts](#list-upload-parts) [Move a File](#move-a-file) [Copy a File](#copy-a-file) [Rename a File](#rename-a-file) [Delete a File](#delete-a-file) [Get Previous Versions of a File](#get-previous-versions-of-a-file) [Upload a New Version of a File](#upload-a-new-version-of-a-file) [Promote a Previous Version of a File](#promote-a-previous-version-of-a-file) [Delete a Previous Version of a File](#delete-a-previous-version-of-a-file) [Lock a File](#lock-a-file) [Unlock a File](#unlock-a-file) [Create a Shared Link Download URL](#create-a-shared-link-download-url) [Find a File for a Shared Link](#find-a-file-for-a-shared-link) [Create or update a Shared Link](#create-or-update-a-shared-link) [Get a Shared Link](#get-a-shared-link) [Remove a Shared Link](#remove-a-shared-link) [Get an Embed Link](#get-an-embed-link) [Get File Representations](#get-file-representations) [Get Thumbnail (Deprecated)](#get-thumbnail-deprecated) [Get Thumbnail](#get-thumbnail) [Set Metadata](#set-metadata) [Get Metadata](#get-metadata) [Remove Metadata](#remove-metadata) [Get All Metadata](#get-all-metadata) [Set a Classification](#set-a-classification) [Retrieve a Classification](#retrieve-a-classification) [Remove a Classification](#remove-a-classification) [Set retention policy expiration date](#set-retention-policy-expiration-date) ## Get a File's Information Calling [`file.get(*, fields=None, etag=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) on a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) retrieves information about the file from the API. This method returns a new [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object populated with the information retrieved. You can specify an `Iterable` of fields to retrieve from the API in the `fields` parameter. ``` file_id = '11111' file_info = client.file(file_id).get() print(f'File "{file_info.name}" has a size of {file_info.size} bytes') ``` ## Update a File's Information To update fields on the [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object, call [`file.update_info(data=data_to_update)`][update_info] with a `dict` of fields to update. This method returns the updated [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object, leaving the original it was called on unmodified. ``` file_id = '11111' updated_file = client.file(file_id).update_info(data={'description': 'My file'}) ``` ## Download a File A file can be downloaded in two ways: by returning the entire contents of the file as `bytes` or by providing an output stream to which the contents of the file will be written. For both methods, you can optionally download a specific version of the file by passing the desired [`FileVersion`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_version.FileVersion) in the `file_version` parameter. You may also wish to download only a certain chunk of the file by passing a tuple of byte offsets via the `byte_range` parameter — the lower and upper bounds you wish to download. To get the entire contents of the file as `bytes`, call [`file.content(file_version=None, byte_range=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.content). ``` file_id = '11111' file_content = client.file(file_id).content() ``` For users with premium accounts, previous versions of a file can be downloaded. ``` file_id = '11111' file_version = client.file_version('12345') version_content = client.file(file_id).content(file_version=file_version) ``` Additonally, only a part of the file can be downloaded by specifying a byte range. ``` file_id = '11111' beginning_of_file_content = client.file(file_id).content(byte_range=(0,99)) ``` To download the file contents to an output stream, call [`file.download_to(writeable_stream, file_version=None, byte_range=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.download_to) with the stream. ``` file_id = '11111' # Write the Box file contents to disk with open('file.pdf', 'wb') as output_file: client.file(file_id).download_to(output_file) ``` ## Get Download URL To get a download URL suitable for passing to a web browser or other application, which will allow someone to download the file, call [`file.get_download_url(file_version=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_download_url). The will return a `unicode` string containing the file's download URL. You can optionally pass a [`FileVersion`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_version.FileVersion) via the `file_version` parameter to get a download URL for a specific version of the file. ``` file_id = '11111' download_url = client.file(file_id).get_download_url() print(f'The file\'s download URL is: {download_url}') ``` ## Upload a File Files are uploaded to a folder in one of two ways: by providing a path to a file on disk, or via a readable stream containing the file contents. To upload a file from a path on disk, call the [`folder.upload(file_path, file_name=None, file_description=None,preflight_check=False, preflight_expected_size=0)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.upload) method on the [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) you want to upload the file into. By default, the file uploaded to Box will have the same file name as the one on disk; you can override this by passing a different name in the `file_name` parameter. You can, optionally, also choose to set a file description upon upload by using the `file_description` parameter. This method returns a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object representing the newly-uploaded file. ``` folder_id = '22222' new_file = client.folder(folder_id).upload('/home/me/document.pdf') print(f'File "{new_file.name}" uploaded to Box with file ID {new_file.id}') ``` To upload a file from a readable stream, call [`folder.upload_stream(file_stream, file_name, file_description=None, preflight_check=False, preflight_expected_size=0)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.upload_stream) with the stream and a name for the file. This method returns a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object representing the newly-uploaded file. ``` file_name = 'file.pdf' stream = open('/path/to/file.pdf', 'rb') folder_id = '22222' new_file = client.folder(folder_id).upload_stream(stream, file_name) print(f'File "{new_file.name}" uploaded to Box with file ID {new_file.id}') ``` **NOTE:** Both methods `folder.upload()` and `folder.upload_stream()` include the `stream_file_content` parameter, which controls how the file content is uploaded. If you are uploading a large file, you may want to stream the request to avoid excessive memory usage. According to `requests'` library [docs](https://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file), by default, the `requests` library does not support streaming uploads, and all the data must be read into memory before being sent to the server. However, the `requests-toolbelt` package includes a `MultipartEncoder` class, which enables file uploads without loading the entire file into memory. This approach is the default in the Box Python SDK. That said, handling 307 Temporary Redirects presents a challenge with streamed file uploads. 307 redirect requires that both the request method and body remain unchanged. This can be problematic when uploading a file stream because the stream will already be exhausted when the redirect occurs. To address this issue, the `stream_file_content` parameter has been introduced in upload methods. This allows you to choose between: Streaming the file (`stream_file_content=True`): Optimizes memory usage but may cause issues with redirects. Using the default `requests'` library behavior (`stream_file_content=False`): Ensures the file can be re-read if a redirect occurs but may consume more memory. This is especially important when working with proxy servers. ## Chunked Upload For large files or in cases where the network connection is less reliable, you may want to upload the file in parts. This allows a single part to fail without aborting the entire upload, and failed parts can then be retried. Since box-python-sdk 3.11.0 release, by default the SDK uses upload urls provided in response when creating a new upload session. This allowes to always upload your content to the closest Box data center and can significantly improve upload speed. You can always disable this feature and always use base upload url by setting `use_upload_session_urls` flag to `False` when creating upload session. ### Automatic Uploader Since box-python-sdk 3.7.0 release, automatic uploader uses multiple threads, which significantly speeds up the upload process. By default, automatic chunked uploader will use 5 threads. You can change this number by setting `API.CHUNK_UPLOAD_THREADS` to a new number. ``` from boxsdk.config import API API.CHUNK_UPLOAD_THREADS = 6 ``` #### Upload new file The SDK provides a method of automatically handling a chunked upload. First get a folder you want to upload the file to. Then call [`folder.get_chunked_uploader(file_path, rename_file=False, use_upload_session_urls=True)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.get_chunked_uploader) to retrieve a [`ChunkedUploader`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.chunked_uploader.ChunkedUploader) object. Setting `use_upload_session_urls` to `True` inilializes the uploader that utlizies urls returned by the `Create Upload Session` endpoint response unless a custom API.UPLOAD_URL was set in the config. Setting `use_upload_session_urls` to `False` inilializes the uploader that uses always base upload urls. Calling the method [`chunked_upload.start()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.chunked_uploader.ChunkedUploader.start) will kick off the chunked upload process and return the [File](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object that was uploaded. ``` # uploads large file to a root folder chunked_uploader = client.folder('0').get_chunked_uploader(file_path='/path/to/file.txt', file_name='new_name.txt') uploaded_file = chunked_uploader.start() print(f'File "{uploaded_file.name}" uploaded to Box with file ID {uploaded_file.id}') ``` You can also upload file stream by creating a [`UploadSession`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession) first. This can be done by calling [`folder.create_upload_session(file_size, file_name=None, use_upload_session_urls=True)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.create_upload_session) method. `use_upload_session_urls` flag is used to determine if the upload session should use urls returned by the `Create Upload Session` endpoint or should it always use base upload urls. Then you can call method [`upload_session.get_chunked_uploader_for_stream(content_stream, file_size)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession.get_chunked_uploader_for_stream). ``` test_file_path = '/path/to/large_file.mp4' with open(test_file_path, 'rb') as content_stream: total_size = os.stat(test_file_path).st_size upload_session = client.folder('0').create_upload_session(file_size=total_size, file_name='large_file.mp4') chunked_uploader = upload_session.get_chunked_uploader_for_stream(content_stream=content_stream, file_size=total_size) uploaded_file = chunked_uploader.start() print(f'File "{uploaded_file.name}" uploaded to Box with file ID {uploaded_file.id}') ``` #### Upload new file version To upload a new file version for a large file, first get a file you want to replace. Then call [`file.get_chunked_uploader(file_path, rename_file=False, use_upload_session_urls=True)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_chunked_uploader) to retrieve a [`ChunkedUploader`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.chunked_uploader.ChunkedUploader) object. Calling the method [`chunked_upload.start()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.chunked_uploader.ChunkedUploader.start) will kick off the chunked upload process and return the updated [File](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File). ``` # uploads new large file version chunked_uploader = client.file('existing_big_file_id').get_chunked_uploader(file_path='/path/to/file') uploaded_file = chunked_uploader.start() print(f'File "{uploaded_file.name}" uploaded to Box with file ID {uploaded_file.id}') # the uploaded_file.id will be the same as 'existing_big_file_id' ``` #### Preflight check before upload To check if a file can be uploaded with given name to a specific folder call [`folder.preflight_check(size, name)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.preflight_check). If the check did not pass, this method will raise an exception including some details on why it did not pass. ``` file_name = 'large_file.mp4' test_file_path = '/path/to/large_file.mp4' total_size = os.stat(test_file_path).st_size destination_folder_id = '0' try: client.folder(destination_folder_id).preflight_check(size=total_size, name=file_name) except BoxAPIException as e: print(f'File {file_name} cannot be uploaded to folder with id: {destination_folder_id}. Reason: {e.message}') ``` #### Resume Upload Sometimes an upload can be interrupted, in order to resume uploading where you last left off, simply call the [`chunked_uploader.resume()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.chunked_uploader.ChunkedUploader.resume) method. This will return the [File](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object that was uploaded. ``` chunked_uploader = client.file('12345').get_chunked_uploader('/path/to/file') try: uploaded_file = chunked_uploader.start() except: uploaded_file = chunked_uploader.resume() print(f'File "{uploaded_file.name}" uploaded to Box with file ID {uploaded_file.id}') ``` #### Abort Chunked Upload To abort a running upload, which cancels all currently uploading chunks and aborts the upload session, call the method [`chunked_uploader.abort()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession.abort). ``` from boxsdk.exception import BoxNetworkException test_file_path = '/path/to/large_file.mp4' content_stream = open(test_file_path, 'rb') total_size = os.stat(test_file_path).st_size chunked_uploader = client.file('existing_big_file_id').get_chunked_uploader(file_path='/path/to/file') try: uploaded_file = chunked_uploader.start() except BoxNetworkException: chunked_uploader.abort() ``` ### Manual Process For more complicated upload scenarios, such as those being coordinated across multiple processes or when an unrecoverable error occurs with the automatic uploader, the endpoints for chunked upload operations are also exposed directly. For example, this is roughly how a chunked upload is done manually: ``` import hashlib import os test_file_path = '/path/to/large_file.mp4' total_size = os.stat(test_file_path).st_size sha1 = hashlib.sha1() content_stream = open(test_file_path, 'rb') upload_session = client.folder(folder_id='11111').create_upload_session(file_size=total_size, file_name='test_file_name.mp4') part_array = [] for part_num in range(upload_session.total_parts): copied_length = 0 chunk = b'' while copied_length < upload_session.part_size: bytes_read = content_stream.read(upload_session.part_size - copied_length) if bytes_read is None: # stream returns none when no bytes are ready currently but there are # potentially more bytes in the stream to be read. continue if len(bytes_read) == 0: # stream is exhausted. break chunk += bytes_read copied_length += len(bytes_read) uploaded_part = upload_session.upload_part_bytes(chunk, part_num*upload_session.part_size, total_size) part_array.append(uploaded_part) updated_sha1 = sha1.update(chunk) content_sha1 = sha1.digest() uploaded_file = upload_session.commit(content_sha1=content_sha1, parts=part_array) print(f'File ID: {uploaded_file.id} and File Name: {uploaded_file.name}') ``` The individual endpoint methods are detailed below: #### Create Upload Session for File Version To create an upload session for uploading a large version, call [`file.create_upload_session(file_size, file_name=None, use_upload_session_urls=True)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.create_upload_session) with the size of the file to be uploaded. You can optionally specify a new `file_name` to rename the file on upload. `use_upload_session_urls` flag is used to determine if the upload session should use urls returned by the `Create Upload Session` endpoint or should it always use base upload urls. This method returns an [`UploadSession`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession) object representing the created upload session. ``` file_size = 26000000 upload_session = client.file('11111').create_upload_session(file_size) print(f'Created upload session {upload_session.id} with chunk size of {upload_session.part_size} bytes') ``` #### Create Upload Session for File To create an upload session for uploading a new large file, call [`folder.create_upload_session(file_size, file_name, use_upload_session_urls=True)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.create_upload_session) with the size and filename of the file to be uploaded. `use_upload_session_urls` flag is used to determine if the upload session should use urls returned by the `Create Upload Session` endpoint or should it always use base upload urls. This method returns an [`UploadSession`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession) object representing the created upload session. ``` file_size = 26000000 file_name = 'test_file.pdf' upload_session = client.folder('22222').create_upload_session(file_size, file_name) print(f'Created upload session {upload_session.id} with chunk size of {upload_session.part_size} bytes') ``` #### Upload Part To upload a part of the file to this session, call [`upload_session.upload_part_bytes(part_bytes, offset, total_size, part_content_sha1=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession.upload_part_bytes) with the `bytes` to be uploaded, the byte offset within the file (which should be a multiple of the upload session `part_size`), and the total size of the file being uploaded. This method returns a `dict` for the part record; these records should be kept for the commit operation. **Note:** The number of bytes uploaded for each part must be exactly `upload_sesion.part_size`, except for the last part (which just includes however many bytes are left in the file). ``` upload_session = client.upload_session('11493C07ED3EABB6E59874D3A1EF3581') offset = upload_session.part_size * 3 total_size = 26000000 part_bytes = b'abcdefgh' part = upload_session.upload_part_bytes(part_bytes, offset, total_size) print(f'Successfully uploaded part ID {part["part_id"]}') ``` #### Commit Upload Session After uploading all parts of the file, commit the upload session to Box by calling [`upload_session.commit(content_sha1, parts=None, file_attributes=None, etag=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession.commit) with the SHA1 hash of the entire file. For best consistency guarantees, you should also pass an `Iterable` of the parts `dict`s via the `parts` parameter; otherwise, the list of parts will be retrieved from the API. You may also pass a `dict` of `file_attributes` to set on the new file. ``` import hashlib sha1 = hashlib.sha1() # sha1 should have been updated with all the bytes of the file file_atributes = { 'description': 'A file uploaded via Chunked Upload', } upload_session = client.upload_session('11493C07ED3EABB6E59874D3A1EF3581') uploaded_file = upload_session.commit(sha1.digest(), file_atributes=file_atributes) print(f'Successfully uploaded file {uploaded_file.id} with description {uploaded_file.description}') ``` #### Abort Upload Session To abort a chunked upload and lose all uploaded file parts, call [`upload_session.abort()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession.abort). This method returns `True` to indicate that the deletion succeeded. ``` client.upload_session('11493C07ED3EABB6E59874D3A1EF3581').abort() print('Upload was successfully canceled') ``` #### List Upload Parts To return the list of parts uploaded so far, call [`upload_session.get_parts(limit=None, offset=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.upload_session.UploadSession.get_parts). This method returns a `BoxObjectCollection` that allows you to iterate over the part `dict`s in the collection. ``` parts = client.upload_session('11493C07ED3EABB6E59874D3A1EF3581').get_parts() for part in parts: print(f'Part {part["part_id"]} at offset {part["offset"]} has already been uploaded') ``` ## Move a File To move a file from one folder into another, call [`file.move(parent_folder, name=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.move) with the destination folder to move the file into. You can optionally provide a `name` parameter to automatically rename the file in case of a name conflict in the destination folder. This method returns the updated [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object in the new folder. ``` file_id = '11111' destination_folder_id = '44444' file_to_move = client.file(file_id) destination_folder = client.folder(destination_folder_id) moved_file = file_to_move.move(parent_folder=destination_folder) print(f'File "{moved_file.name}" has been moved into folder "{moved_file.parent.name}"') ``` ## Copy a File A file can be copied to a new folder by calling [`file.copy(*, parent_folder, name=None, file_version=None, **_kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.copy) with the destination folder and an optional new name for the file in case there is a name conflict in the destination folder. This method returns a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object representing the copy of the file in the destination folder. ``` file_id = '11111' destination_folder_id = '44444' file_to_copy = client.file(file_id) destination_folder = client.folder(destination_folder_id) file_copy = file_to_copy.copy(parent_folder=destination_folder) print(f'File "{file_copy.name}" has been copied into folder "{file_copy.parent.name}"') ``` ## Rename a File A file can be renamed by calling [`file.rename(name)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.rename). This method returns the updated [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object with a new name. Remeber to provide also extension of the file along with the new name. ``` file = client.file(file_id='11111') renamed_file = file.rename("new-name.pdf") print(f'File was renamed to "{renamed_file.name}"') ``` ## Delete a File Calling the [`file.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.delete) method will delete the file. Depending on enterprise settings, this will either move the file to the user's trash or permanently delete the file. This method returns `True` to signify that the deletion was successful. ``` client.file(file_id='11111').delete() ``` ## Get Previous Versions of a File Previous versions of a file can be retrieved with the [`file.get_previous_versions(limit=None, offset=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_previous_versions) method. This method returns a [`BoxObjectCollection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.pagination.html#boxsdk.pagination.box_object_collection.BoxObjectCollection) that can iterate over the [`FileVersion`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_version.FileVersion) objects in the collection. ``` file_id = '11111' file_versions = client.file(file_id).get_previous_versions() for version in file_versions: print(f'File version {version.id} was created at {version.created_at}') ``` ## Upload a New Version of a File New versions of a file can be uploaded in one of two ways: by providing a path to a file on disk, or via a readable stream containing the file contents. To upload a new file version from a path on disk, call the [`file.update_contents(file_path, etag=None, preflight_check=False, preflight_expected_size=0)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.update_contents) method. This method returns a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object representing the updated file. ``` file_id = '11111' file_path = '/path/to/file.pdf' updated_file = client.file(file_id).update_contents(file_path) print(f'File "{updated_file.name}" has been updated') ``` To upload a file version from a readable stream, call [`file.update_contents_with_stream(file_stream, etag=None, preflight_check=False, preflight_expected_size=0)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.update_contents_with_stream) with the stream. This method returns a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object representing the newly-uploaded file. ``` file_id = '11111' stream = open('/path/to/file.pdf', 'rb') updated_file = client.file(file_id).update_contents_with_stream(stream) print(f'File "{updated_file.name}" has been updated') ``` ## Promote a Previous Version of a File A previous version of a file can be promoted by calling the [`file.promote_version(file_version)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.promote_version) method to become the current version of the file with the [`FileVersion`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_version.FileVersion) to promote. This create a copy of the old file version and puts it on the top of the versions stack. This method returns the new copy [`FileVersion`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_version.FileVersion) object. ``` file_id = '11111' file_version_id = '12345' version_to_promote = client.file_version(file_version_id) new_version = client.file(file_id).promote_version(version_to_promote) print(f'Version {file_version_id} promoted; new version {new_version.id} created') ``` ## Delete a Previous Version of a File A version of a file can be deleted and moved to the trash by calling [`file.delete_version(file_version, etag=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.delete_version) with the [`FileVersion`] to delete. ``` file_id = '11111' version_id = '12345' version_to_delete = client.file_version(version_id) client.file(file_id).delete_version(version_to_delete) ``` ## Lock a File A locked file cannot be modified by any other user until it is unlocked. This is useful if you want to "check out" a file while you're working on it, to ensure that other collaborators do not make changes while your changes are in progress. To lock a file, call [`file.lock(prevent_download=False, expire_time=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.lock). You can optionally prevent other users from downloading the file while it is locked by passing `True` for the `prevent_download` parameter. You can also set an expiration time for the lock, which will automatically release the lock at the specified time. The expiration time is formatted as an [RFC3339 datetime](https://tools.ietf.org/html/rfc3339#section-5.8). This method returns the updated [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object. ``` file_id = '11111' updated_file = client.file(file_id).lock(expiration_time='2020-01-01T00:00:00-08:00') print(f'File "{updated_file.name}" has been locked!') ``` ## Unlock a File A locked file can be unlocked by calling [`file.unlock()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.unlock). This method returns the updated [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object. ``` file_id = '11111' updated_file = client.file(file_id).unlock() print(f'File "{updated_file.name}" has been unlocked!') ``` ## Create a Shared Link Download URL A shared link for a file can be generated by calling [`file.get_shared_link_download_url(access=None, etag=None, unshared_at=None, allow_preview=None, password=None, vanity_name=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_shared_link_download_url). This method returns a `unicode` string containing the shared link URL. ``` file_id = '11111' url = client.file(file_id).get_shared_link_download_url(access='collaborators', vanity_name="my-unique-vanity-name") print(f'The file shared link download URL is: {url}') ``` ## Find a File for a Shared Link To find a file given a shared link, use the [`client.get_shared_item`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html?highlight=get_shared_item#boxsdk.client.client.Client.get_shared_item) method. ``` file = client.get_shared_item('https://app.box.com/s/gjasdasjhasd', password='letmein') ``` ## Create or update a Shared Link A shared link for a file can be generated or updated by calling [`file.get_shared_link(*, access=None, etag=None, unshared_at=None, allow_download=None, allow_preview=None, allow_edit=None, password=None, vanity_name=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_shared_link). This method returns a `unicode` string containing the shared link URL. ``` file_id = '11111' url = client.file(file_id).get_shared_link(access='open', allow_download=True, allow_edit=True) print(f'The file shared link URL is: {url}') ``` ## Get a Shared Link To check for an existing shared link on a file, simply call `file.shared_link` This method returns a `unicode` string containing the shared link URL. ``` file_id = '11111' shared_link = client.file(file_id).get().shared_link url = shared_link['url'] ``` ## Remove a Shared Link A shared link for a file can be removed by calling [`file.remove_shared_link(*, etag=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.remove_shared_link). ``` file_id = '11111' client.file(file_id).remove_shared_link() ``` ## Get an Embed Link A file embed URL can be generated by calling [`file.get_embed_url()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_embed_url). This method returns a `unicode` string containing a URL suitable for embedding in an `<iframe>` to embed the a file viewer in a web page. ``` file_id = '11111' embed_url = client.file(file_id).get_embed_url() print(f'<iframe src="{embed_url}"></iframe>') ``` ## Get File Representations To get the preview representations of a file, call the [`file.get_representation_info(rep_hints=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_representation_info) method with the [representation hints](https://developer.box.com/en/reference/get-files-id/#param-X-Rep-Hints) to fetch — if no hints are provided, limited information about all available representations will be returned. This method returns a `list` of `dict`s containing the information about the requested [representations](https://developer.box.com/en/reference/resources/representations). Note that this method only provides information about a set of available representations; your application will need to handle checking the status of the representations and downloading them via the provided content URL template. ``` file_id = '11111' rep_hints = '[pdf][extracted_text]' representations = client.file(file_id).get_representation_info(rep_hints) for rep in representations: print(f'{rep["representation"]} representation has status {rep["status"]["state"]}') print(f'Info URL for this representation is: {rep["info"]["url"]}') print(f'Content URL template is: {rep["content"]["url_template"]}') ``` ## Get Thumbnail (Deprecated) A thumbnail for a file can be retrieved by calling [`file.get_thumbnail(extension='png', min_width=None, min_height=None, max_width=None, max_height=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_thumbnail). This method returns the `bytes` of the thumbnail image. ``` file_id = '11111' thumbnail = client.file(file_id).get_thumbnail(extension='jpg') ``` ## Get Thumbnail A thumbnail for a file can now be retrieved by calling [`file.get_thumbnail_representation(dimensions, extension='png')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_thumbnail_representation). This method returns the `bytes` of the thumbnail image. You must pass in a dimension that is valid for the extension you pass in for this file. To find valid dimensions, you must first make a call with [`file.get_representation_info(rep_hints=None)`]. This will return a `dict` of all available representations with their extensions and dimensions. More details about can be found on our developer docs [here](https://developer.box.com/guides/representations/list-all-representations/). ``` file_id = '11111' thumbnail = client.file(file_id).get_thumbnail_representation('92x92', extension='jpg') ``` ## Set Metadata To set metadata on a file call the [`file.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) to specify the scope and template key of the metadata template to attach. Then, call the [`metadata.set(data)`][metadata_set] method with the key/value pairs to attach. This method returns a `dict` containing the applied metadata instance. Note: This method will unconditionally apply the provided metadata, overwriting the existing metadata for the keys provided. To specifically create or update metadata, see the `create()` or `update()` methods. ``` metadata = { 'foo': 'bar', } applied_metadata = client.file(file_id='11111').metadata(scope='enterprise', template='testtemplate').set(metadata) print(f'Set metadata in instance ID {applied_metadata["$id"]}') ``` Metadata can be added to a file either as free-form key/value pairs or from an existing template. To add metadata to a file, first call [`file.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) to specify the scope and template key of the metadata template to attach (or use the default values to attach free-form keys and values). Then, call [`metadata.create(data)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.create) with the key/value pairs to attach. This method can only be used to attach a given metadata template to the file for the first time, and returns a `dict` containing the applied metadata instance. Note: This method will only succeed if the provided metadata template is not currently applied to the file, otherwise it will fail with a Conflict error. ``` metadata = { 'foo': 'bar', 'baz': 'quux', } applied_metadata = client.file(file_id='11111').metadata().create(metadata) print(f'Applied metadata in instance ID {applied_metadata["$id"]}') ``` Updating metadata values is performed via a series of discrete operations, which are applied atomically against the existing file metadata. First, specify which metadata will be updated by calling [`file.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata). Then, start an update sequence by calling [`metadata.start_update()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.start_update) and add update operations to the returned [`MetadataUpdate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.MetadataUpdate). Finally, perform the update by calling [`metadata.update(metadata_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.update). This final method returns a `dict` of the updated metadata instance. Note: This method will only succeed if the provided metadata template has already been applied to the file; If the file does not have existing metadata, this method will fail with a Not Found error. This is useful you know the file will already have metadata applied, since it will save an API call compared to `set()`. ``` file_obj = client.file(file_id='11111') file_metadata = file_obj.metadata(scope='enterprise', template='myMetadata') updates = file_metadata.start_update() updates.add('/foo', 'bar') updates.update('/baz', 'murp', old_value='quux') # Ensure the old value was "quux" before updating to "murp" updated_metadata = file_metadata.update(updates) print('Updated metadata on file!') print(f'foo is now {updated_metadata["foo"]} and baz is now {updated_metadata["baz"]}') ``` ## Get Metadata To retrieve the metadata instance on a file for a specific metadata template, first call [`file.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) to specify the scope and template key of the metadata template to retrieve, then call [`metadata.get()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.get) to retrieve the metadata values attached to the file. This method returns a `dict` containing the applied metadata instance. ``` metadata = client.file(file_id='11111').metadata(scope='enterprise', template='myMetadata').get() print(f'Got metadata instance {metadata["$id"]}') ``` ## Remove Metadata To remove a metadata instance from a file, call [`file.metadata(scope='global', template='properties')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.metadata) to specify the scope and template key of the metadata template to remove, then call [`metadata.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata.Metadata.delete) to remove the metadata from the file. This method returns `True` to indicate that the removal succeeded. ``` client.file(file_id='11111').metadata(scope='enterprise', template='myMetadata').delete() ``` ## Get All Metadata To retrieve all metadata attached to a file, call [`file.get_all_metadata()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.get_all_metadata). This method returns a [`BoxObjectCollection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.pagination.html#boxsdk.pagination.box_object_collection.BoxObjectCollection) that can be used to iterate over the `dict`s representing each metadata instance attached to the file. ``` file_metadata = client.file(file_id='11111').get_all_metadata() for instance in file_metadata: if 'foo' in instance: print(f'Metadata instance {instance["id"]} has value "{instance["foo"]}" for foo') ``` ## Set a Classification It is important to note that this feature is only available if you have Governance. To add classification to a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File), call [`file.set_classification(classification)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.set_classification). This method returns the classification type on the [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object. If a classification already exists then this call will update the existing classification with the new [`ClassificationType`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.ClassificationType). ``` from boxsdk.object.item import ClassificationType classification = client.file(file_id='11111').set_classification(ClassificationType.PUBLIC) print(f'Classification Type is: {classification}') ``` The set method will always work no matter the state your [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) is in. For cases already where a classification value already exists [`set_classification(classification)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.set_classification) may make multiple API calls. Alternatively, if you already know you have a classification and you are simple updating it, you can use the [`update_classification(classification)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.update_classification). This will ultimately help you save one extra API call. ``` classification = client.file(file_id='11111').update_classification(ClassificationType.NONE) print(f'Classification Type is: {classification}') ``` ## Retrieve a Classification To retrieve a classification from a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File), call [`file.get_classification()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.get_classification). This method returns the classification type on the [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File) object. ``` classification = client.file(file_id='11111').get_classification() print(f'Classification Type is: {classification}') ``` ## Remove a Classification To remove a classification from a [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File), call [`file.remove_classification()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item.remove_classification). ``` client.file(file_id='11111').remove_classification() ``` ## Set retention policy expiration date To set new retention policy expiration date for the file, call [`set_disposition_at(date_time)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.set_disposition_at). This method will only work for files under retention with `permanently_delete` disposition action set. Remember that disposition date can't be shortened once set on a file. As the `date_time` parameter you can use either datetime string, e.g. '2035-03-04T10:14:24+14:00' or `datetime.datetime` object. ``` import datetime, pytz new_disposition_date = datetime.datetime(year=2029, month=3, day=4, hour=10, minute=14, second=24, tzinfo=pytz.timezone('US/Alaska')) client.file(file_id='11111').set_disposition_at(date_time=new_disposition_date) ``` If `datetime.datetime` object doesn't have timezone specified, the local timezone will be used. To get the current disposition date you can use the snippet below. ``` disposition_date = client.file(file_id='11111').get(fields=('disposition_at',)).disposition_at ``` --- ## Untitled *Type: page* Legal Hold Policies A legal hold policy blocks permanent deletion of content during ongoing litigation. Admins can create legal hold… # Legal Hold Policies A legal hold policy blocks permanent deletion of content during ongoing litigation. Admins can create legal hold policies and then later assign them to specific folders, files, or users. Legal Hold Policy information describes the basic characteristics of the Policy, such as name, description, and filter dates. It is important to note that the legal hold object contains no information about what this policy applies to. If an order of discovery is received or the customer is part of an ongoing litigation, a legal hold policy can be created to keep track of everything that needs to be held. The actual holding is done via Legal Hold Assignments. - [Get Information About a Legal Hold Policy](#get-information-about-a-legal-hold-policy) - [List Legal Hold Policies](#list-legal-hold-policies) - [Create New Legal Hold Policy](#create-new-legal-hold-policy) - [Update Legal Hold Policy](#update-legal-hold-policy) - [Delete Legal Hold Policy](#delete-legal-hold-policy) - [Assign Legal Hold Policy](#assign-legal-hold-policy) - [List Legal Hold Policy Assignments](#list-legal-hold-policy-assignments) - [Get Information About a Legal Hold Assignment](#get-information-about-a-legal-hold-assignment) - [Delete Legal Hold Assignment](#delete-legal-hold-assignment) - [List File Version Legal Holds](#list-file-version-legal-holds) - [Get Information about a File Version Legal Hold](#get-information-about-a-file-version-legal-hold) ## Get Information About a Legal Hold Policy To retrieve information about a legal hold policy, first call [`client.legal_hold_policy(policy_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.legal_hold_policy) to initialize the [`LegalHoldPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy.LegalHoldPolicy) and then call [`legal_hold_policy.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) to retrieve data from the API. This method returns a new [`LegalHoldPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy.LegalHoldPolicy) object with fields populated by data form the API, leaving the original object unmodified. ``` legal_hold_policy = client.legal_hold_policy(policy_id='12345').get() print(f'The "{legal_hold_policy.policy_name}" policy is {legal_hold_policy.status}') ``` ## List Legal Hold Policies To get the legal hold policies available in the enterprise, call [`client.get_legal_hold_policies(policy_name=None, limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_legal_hold_policies). You can optionally pass a `policy_name` value to filter the results to include only policies that are a case-insensitive prefix match by name. This method returns a `BoxObjectCollection` that allows you to iterate over the [`LegalHoldPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy.LegalHoldPolicy) objects in the collection. ``` policies = client.get_legal_hold_policies() for policy in policies: print(f'Legal Hold Policy "{policy.name}" has ID {policy.id}') ``` ## Create New Legal Hold Policy To create a new legal hold policy, call [`client.create_legal_hold_policy(policy_name, description=None, filter_starting_at=None, filter_ending_at=None, is_ongoing=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_legal_hold_policy) with the name for the policy. You can optionally include a human-readable `description`, as well as parameters describing which time period the policy applies to. You must specify either `filter_starting_at` and `filter_ending_at` dates, or `is_ongoing=True`. This method returns a new [`LegalHoldPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy.LegalHoldPolicy) object representing the created policy. ``` new_policy = client.create_legal_hold_policy('New Policy', is_ongoing=True) print(f'Created legal hold policy with ID {new_policy.id}') ``` ## Update Legal Hold Policy To update an existing legal hold policy, call [`legal_hold_policy.update_info(data=policy_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the policy. This method returns a new [`LegalHoldPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy.LegalHoldPolicy) object with the updates applied, leaving the original object unmodified. ``` policy_update = {'description': 'New Description', 'release_notes': 'Example Notes'} updated_policy = client.legal_hold_policy(policy_id='12345').update_info(data=policy_update) ``` ## Delete Legal Hold Policy To delete a legal hold policy, call [`legal_hold_policy.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion request was successful. **Note:** This is an asynchronous process - the policy assignment may not be fully deleted yet when the response comes back. ``` client.legal_hold_policy(policy_id='12345').delete() print('Legal hold policy was deleted!') ``` ## Assign Legal Hold Policy To assign a legal hold policy, call [`legal_hold_policy.assign(assignee)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy.LegalHoldPolicy.assign). You can assign a legal hold policy to a [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder), [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File), [`FileVersion`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_version.FileVersion), or [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User). This will cause the associated items to be held and unable to be deleted. ``` folder_to_assign = client.folder(folder_id='22222') assignment = client.legal_hold_policy(policy_id'12345').assign(folder_to_assign) print(f'Applied policy "{assignment.legal_hold_policy.policy_name}" to {assignment.assigned_to.type} {assignment.assigned_to.id}') ``` ## List Legal Hold Policy Assignments To get the assignments for a specific legal hold policy, call [`legal_hold_policy.get_assignments(assign_to_type=None, assign_to_id=None, limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy.LegalHoldPolicy.get_assignments). This method returns a `BoxObjectCollection` that allows you to iterate over the [`LegalHoldPolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy_assignment.LegalHoldPolicyAssignments) objects in the collection. ``` assignments = client.legal_hold_policy(policy_id='12345').get_assignments() for assignment in assignments: print(f'Found policy assignment with ID {assignment.id}') ``` To filter by the assignee `type` and/or `id` you can use pass in the `assign_to_type` and `assign_to_id` filter. ``` folder_id = '1111' assignments = client.legal_hold_policy('1234').get_assignments('folder', folder_id) for assignment in assignments: print(f'Found policy assignment with ID {assignment.id}') ``` ## Get Information About a Legal Hold Assignment To retrieve information about a legal hold policy assignment, first call [`client.legal_hold_policy_assignment(policy_assignment_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.legal_hold_policy_assignment) to initialize the [`LegalHoldPolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy_assignment.LegalHoldPolicyAssignments) and then call [`legal_hold_policy_assignment.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) to retrieve data about the assignment from the API. This method returns a new [`LegalHoldPolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy_assignment.LegalHoldPolicyAssignments) with fields populated by data from the API, leaving the original object unmodified. ``` assignment_id = '98765' assignment = client.legal_hold_policy_assignment(assignment_id).get() print(f'Policy {assignment.legal_hold_policy.id} is assigned to {assignment.assigned_to.type} {assignment.assigned_to.id}') ``` ## Delete Legal Hold Assignment To delete an existing legal hold policy assignment, call [`legal_hold_policy_assignment.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion request was successful. **Note:** This is an asynchronous process - the policy assignment may not be fully deleted yet when the response comes back. ``` assignment_id = '1111' client.legal_hold_policy_assignment(assignment_id).delete() ``` ## List File Version Legal Holds To get the actual hold records associated with a policy, call [`legal_hold_policy.get_file_version_legal_holds()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold_policy.LegalHoldPolicy.get_file_version_legal_holds). This method returns a `BoxObjectCollection` that allows you to iterate over the [`LegalHold`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold.LegalHold) objects in the collection. ``` legal_holds = client.legal_hold_policy(policy_id='12345').get_file_version_legal_holds() for legal_hold in legal_holds: print(f'Got file version legal hold with ID {legal_hold.id}') ``` ## Get Information about a File Version Legal Hold To retrieve information about a file version legal hold, call [`legal_hold.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get). This method returns a new [`LegalHold`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.legal_hold.LegalHold) with fields populated by data from the API, leaving the original object unmodified. ``` file_version_legal_hold_id = '55555' legal_hold = client.legal_hold(file_version_legal_hold_id).get() print(f'Version {legal_hold.file_version.id} of file {legal_hold.file.id} is held by {len(legal_hold.legal_hold_policy_assignments)} assignment(s)') ``` --- ## Untitled *Type: page* Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of… # Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of key:value pairs that belong to files/folders. For example, an important contract may have key:value pairs of `"clientNumber":"820183"` and `"clientName":"bioMedicalCorp"`. Metadata that belongs to a file/folder is grouped by templates. Templates allow the metadata service to provide a multitude of services, such as pre-defining sets of key:value pairs or schema enforcement on specific fields. Each file/folder can have multiple distinct template instances associated with it, and templates are also grouped by scopes. Currently, the only scopes support are `enterprise` and `global`. Enterprise scopes are defined on a per enterprises basis, whereas global scopes are Box application-wide. In addition to `enterprise` scoped templates, every file on Box has access to the `global` `properties` template. The Properties template is a bucket of free form key:value string pairs, with no additional schema associated with it. Properties are ideal for scenarios where applications want to write metadata to file objects in a flexible way, without pre-defined template structure. - [Create Metadata Template](#create-metadata-template) [Get Metadata Template](#get-metadata-template) - [Get by scope and template key](#get-by-scope-and-template-key) - [Get by template ID](#get-by-template-id) [Update Metadata Template](#update-metadata-template) [Get Enterprise Metadata Templates](#get-enterprise-metadata-templates) [Delete Metadata Template](#delete-metadata-template) ## Create Metadata Template To create a new metadata template, call [`client.create_metadata_template(display_name, fields, template_key=None, hidden=False, scope='enterprise', copy_instance_on_item_copy=False)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_metadata_template) with the human-readable name of the template and the [`MetadataField`s](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataField) the template should have. You can optionally specify a key for the template, otherwise one will be derived from the display name. At the current time, only `enterprise` scope templates are supported. This method returns a [`MetadataTemplate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate) object representing the created template. ``` from boxsdk.object.metadata_template import MetadataField, MetadataFieldType fields = [ MetadataField(MetadataFieldType.STRING, 'Name'), MetadataField(MetadataFieldType.DATE, 'Birthday', 'bday'), MetadataField(MetadataFieldType.ENUM, 'State', options=['CA', 'TX', 'NY']) ] template = client.create_metadata_template('Employee Record', fields, hidden=True) print(f'Metadata template ID {template.scope}/{template.templateKey} created!') ``` ## Get Metadata Template ### Get by scope and template key To retrieve a specific template by scope and template key, first use [`client.metadata_template(scope, template_key)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.metadata_template) to construct the appropriate [`MetadataTemplate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate) object, and then call [`template.get()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) to retrieve data about the template. This method returns a new [`MetadataTemplate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate) object with fields populated by data from the API, leaving the original object unmodified. ``` template = client.metadata_template('enterprise', 'employeeRecord').get() print(f'The {template.displayName} template has {len(template.fields)} fields') ``` ### Get by template ID To retrieve a template by ID, call [`client.get_metadata_template_by_id(template_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_metadata_template_by_id) with the ID of the metadata template. This method returns a [`MetadataTemplate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate) object with fields populated by data from the API. ``` template = client.metadata_template_by_id(template_id='abcdef-fba434-ace44').get() print(f'The {template.displayName} template has {len(template.fields)} fields') ``` ## Update Metadata Template To make changes to a metadata template, first call [`template.start_update()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate.start_update) to create a [`MetadataTemplateUpdate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplateUpdate) to track updates. Call the methods on this object to add the necessary update operations, and then call [`template.update_info(*, updates, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate.update_info) with the updates object to apply the changes to the metadata template. This method returns an updated [`MetadataTemplate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate) object with the changes applied, leaving the original object unmodified. ``` template = client.metadata_template('enterprise', 'employeeRecord') updates = template.start_update() updates.add_enum_option('state', 'WI') updates.edit_template({'hidden': False}) updates.edit_template({'copyInstanceOnItemCopy': False}) updated_template = template.update_info(updates=updates) ``` ## Get Enterprise Metadata Templates Get all metadata templates for the current enterprise by calling [`client.get_metadata_templates(scope='enterprise', limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_metadata_templates). By default, this retrieves all templates scoped to the current enterprise, but you can pass the `scope` parameter to retrieve templates for a different scope. This method returns a [`BoxObjectCollection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.pagination.html#boxsdk.pagination.box_object_collection.BoxObjectCollection) that allows you to iterate over all the [`MetadataTemplate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate) objects in the collection. ``` templates = client.get_metadata_templates() for template in templates: print(f'Metadata template {template.templateKey} is in enterprise scope') ``` To return the metadata templates available to all enterprises pass in the `global` scope. ``` templates = client.get_metadata_templates(scope='global) for template in templates: print(f'Metadata template {template.templateKey} is in global scope') ``` ## Delete Metadata Template To delete a metadata template, call [`template.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate the deletion was successful. ``` client.metadata_template('enterprise', 'employeeRecord').delete() ``` --- ## Untitled *Type: page* Metadata Cascade Policies Metadata Cascade Policies allow the metadata values on a folder to be applied to the files within that folder. A… # Metadata Cascade Policies Metadata Cascade Policies allow the metadata values on a folder to be applied to the files within that folder. A cascade policy associates the folder with a specific metadata template whose instance values on the folder should be cascaded to files within the folder. **Note:** The Metadata Cascade Policy endpoints are currently in beta. Please email [betas+metadata@box.com](mailto:betas+metadata@box.com) if you would like to enable this beta feature for your enterprise. If you do not have this enabled for your enterprise, you will get a 403 error. - [Create a Metadata Cascade Policy](#create-a-metadata-cascade-policy) - [Get Information About a Metadata Cascade Policy](#get-information-about-a-metadata-cascade-policy) - [Get Cascade Policies on a Folder](#get-cascade-policies-on-a-folder) - [Force Apply Cascade Policy](#force-apply-cascade-policy) - [Remove Cascade Policy](#remove-cascade-policy) ## Create a Metadata Cascade Policy To create a metadata cascade policy on a folder, call [`folder.cascade_metadata(metadata_template)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.cascade_metadata) with the [`MetadataTemplate`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_template.MetadataTemplate) whose values should be cascaded within the folder. This method returns a [`MetadataCascadePolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_cascade_policy.MetadataCascadePolicy) object representing the newly-created policy. ``` folder = client.folder(folder_id='22222') metadata_template = client.metadata_template('enterprise', 'securityClassiciation') cascade_policy = folder.cascade_metadata(metadata_template) print(f'Folder {cascade_policy.parent.id} has a metadata cascade policy for {cascade_policy.scope} template "{cascade_policy.templateKey}"') ``` ## Get Information About a Metadata Cascade Policy To retrieve information about a metadata cascade policy, first call [`client.metadata_cascade_policy(policy_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.metadata_cascade_policy) with the ID of the cascade policy to initialize the [`MetadataCascadePolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_cascade_policy.MetadataCascadePolicy) object, then call [`cascade_policy.get()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) to retrieve data about the policy. This method returns a new [`MetadataCascadePolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_cascade_policy.MetadataCascadePolicy) object with fields populated by data from the API, leaving the original object unmodified. ``` cascade_policy = client.metadata_cascade_policy('84113349-794d-445c-b93c-d8481b223434').get() print(f'Cascade policy applies to a template owned by enterprise {cascade_policy.owner_enterprise.id}') ``` ## Get Cascade Policies on a Folder To get a list of the cascade policies applied to a folder, call [`folder.get_metadata_cascade_policies(owner_enterprise=None, limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.get_metadata_cascade_policies). You can optionally pass an [`Enterprise`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.enterprise.Enterprise) object via the `owner_enterprise` parameter to retrieve cascade policies related to templates for a specific enterprise; if not specified, this defaults to the current enterprise. This method returns a [`BoxObjectCollection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.pagination.html#boxsdk.pagination.box_object_collection.BoxObjectCollection) that allows you to iterate over the [`MetadataCascadePolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_cascade_policy.MetadataCascadePolicy) objects in the collection. ``` cascade_policies = client.folder(folder_id='22222').get_metadata_cascade_policies() for policy in cascade_policies: print(f'Metadata template {policy.templateKey} is cascaded') ``` ## Force Apply Cascade Policy A Cascade Policy can be forced to re-apply to all files in the associated folder by calling [`cascade_policy.force_apply(conflict_resolution)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.metadata_cascade_policy.MetadataCascadePolicy.force_apply) with the conflict resolution strategy to use. If files in the folder already have metadata values that conflict with the ones being force applied from the folder, you can choose to either preserve the existing values or overwrite them with the folder's values. This method returns `True` to indicate that the force application was successful. ``` from boxsdk.object.metadata_cascade_policy import CascadePolicyConflictResolution cascade_policy = client.metadata_cascade_policy(policy_id='84113349-794d-445c-b93c-d8481b223434') cascade_policy.force_apply(CascadePolicyConflictResolution.PRESERVE_EXISTING) print('Cascade policy was force applied!') ``` ## Remove Cascade Policy A metadata cascade policy can be removed from a folder by calling [`cascade_policy.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion was successful. ``` client.metadata_cascade_policy(policy_id='84113349-794d-445c-b93c-d8481b223434').delete() print('Cascade policy successfully removed') ``` --- ## Untitled *Type: page* Search Search provides a powerful way of finding items that are accessible by a single user or an entire enterprise. Search for Content… # Search Search provides a powerful way of finding items that are accessible by a single user or an entire enterprise. - [Search for Content](#search-for-content) - [Metadata Query](#metadata-query) ## Search for Content To get a list of items matching a search query, call [`search.query(query, limit=None, offset=0, ancestor_folders=None, file_extensions=None, metadata_filters=None, result_type=None, content_types=None, scope=None, created_at_range=None, updated_at_range=None, size_range=None, owner_users=None, trash_content=None, fields=None, sort=None, direction=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.Search.query) will return an `Iterable` that allows you to iterate over the [`Item`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item) objects in the collection. ``` items = client.search().query(query='TEST QUERY', limit=100, file_extensions=['pdf', 'doc']) for item in items: print(f'The item ID is {item.id} and the item name is {item.name}') ``` ### Metadata Search To filter by metadata in your search, first create [`MetadataSearchFilter`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.MetadataSearchFilter) object with the specified `template_key` and `scope` as well as adding filter, `field_key` and `value` with [`metadata_filter.add_value_based_filter(field_key, value)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.MetadataSearchFilter.add_value_based_filter). Next, create a [`MetadataSearchFilters`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.MetadataSearchFilters) object and call [`metadata_filters.add_filter(metadata_filter)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.MetadataSearchFilters.add_filter) and pass in the [`MetadataSearchFilter`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.MetadataSearchFilter) object created earlier. Finally, call [`search.query(query, metadata_filters=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.Search.query) with [`MetadataSearchFilters`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.MetadataSearchFilters) object passed in. ``` from boxsdk.object.search import MetadataSearchFilter, MetadataSearchFilters metadata_search_filter = MetadataSearchFilter(template_key='marketingCollateral', scope='enterprise') metadata_search_filter.add_value_based_filter(field_key='documentType', value='datasheet') metadata_search_filter.add_value_based_filter(field_key='clientNumber', value='a123') metadata_search_filters = MetadataSearchFilters() metadata_search_filters.add_filter(metadata_search_filter) client.search().query(None, limit=100, offset=0, metadata_filters=metadata_search_filters) ``` ### Search with Shared Link Items To get a list of items matching a search query, including items that a user might have accessed recently through a shared link, call [`search.query_with_shared_links(query, limit=None, offset=0, ancestor_folders=None, file_extensions=None, metadata_filters=None, result_type=None, content_types=None, scope=None, created_at_range=None, updated_at_range=None, size_range=None, owner_users=None, trash_content=None, fields=None, sort=None, direction=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.search.Search.query_with_shared_links). This method will return an `Iterable` that allows you to iterate over the search result objects in the collection. ``` search_results = client.search().query_with_shared_links(query='TEST QUERY', limit=100, file_extensions=['pdf', 'doc']) for search_result in search_results: print(f'The item ID is {search_result.item.id} and the item name is {search_result.item.name}') ``` ## Metadata Query To search using SQL-like syntax to return items that match specific metadata, call `search.metadata_query(from_template, ancestor_folder_id, query=None, query_params=None, use_index=None, order_by=None, marker=None, limit=None, fields=None)` **Note:** paramter `use_index` is deprecated and if provided, will be ignored. The current way to create an index is to contact the MDQ team directly via email. MDQ will now use static query analysis to use the index that is most efficient for the call. By default, this method returns only the most basic info about the items for which the query matches. To get additional fields for each item, including any of the metadata, use the fields parameter. ``` from_template = 'enterprise_12345.someTemplate' ancestor_folder_id = '5555' query = 'amount >= :arg' query_params = {'arg': 100} order_by = [ { 'field_key': 'amount', 'direction': 'asc' } ] fields = ['type', 'id', 'name', 'metadata.enterprise_67890.catalogImages.$parent'] limit = 2 marker = 'AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKs' items = client.search().metadata_query( from_template=from_template, ancestor_folder_id=ancestor_folder_id, query=query, query_params=query_params, order_by=order_by, marker=marker, limit=limit, fields=fields ) for item in items: print(f'The item ID is {item.id} and the item name is {item.name}') ``` --- ## Untitled *Type: page* Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files… # Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files and can be sent to one or more Box Sign Request Signers. - [Create Sign Request](#create-sign-request) - [Get all Sign Requests](#get-all-sign-requests) - [Get Sign Request by ID](#get-sign-request-by-id) - [Cancel Sign Request](#cancel-sign-request) - [Resend Sign Request](#resend-sign-request) ## Create Sign Request The [`client.create_sign_request_v2(signers, files=None, parent_folder_id=None, prefill_tags=None, are_reminders_enabled=None, are_text_signatures_enabled=None, days_valid=None, email_message=None, email_subject=None, external_id=None, is_document_preparation_needed=None, redirect_url=None, declined_redirect_url=None, template_id=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_sign_request) method will create a Sign Request. You need to provide at least one file and up to 10 files (from which the signing document will be created) or template_id of the sign request template. You need to include at least one signer that will receive the Sign Request. Example with files: ``` source_file = { 'id': '12345', 'type': 'file' } files = [source_file] signer = { 'name': 'John Doe', 'email': 'signer@mail.com' } signers = [signer] parent_folder_id = '123456789' new_sign_request = client.create_sign_request_v2(signers, files=files, parent_folder_id=parent_folder_id) print(f'(Sign Request ID: {new_sign_request.id})') ``` Example with sign template ``` signer = { 'name': 'John Doe', 'email': 'signer@mail.com' } new_sign_request = client.create_sign_request_v2(signers, template_id='12345') print(f'(Sign Request ID: {new_sign_request.id})') ``` If you set `isDocumentPreparationNeeded` flag to true, you need to visit `prepareUrl` before the Sign Request will be sent. For more information on `isDocumentPreparationNeeded` and the other parameters available, please refer to the [developer documentation](https://developer.box.com/guides/sign-request/). ## Get All Sign Requests Calling the [`client.get_sign_requests()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_sign_requests) will return an iterable that will page through all the Sign Requests. This method offers `limit` and `fields` parameters. The `limit` parameter specifies the maximum number of items to be returned in a single response. The `fields` parameter is used to specify what additional properties should be returned on the return object. For more information on what `fields` are available, please refer to the [developer documentation](https://developer.box.com/guides/box-sign/). ``` sign_requests = client.get_sign_requests() for sign_request in sign_requests: print(f'(Sign Request ID: {sign_request.id})') ``` ## Get Sign Request by ID Calling [`client.sign_request(sign_request_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.sign_request) will return an object containing information about the Sign Request. The `fields` parameter is used to specify what additional properties should be returned in the return object. ``` sign_request = client.sign_request(sign_request_id='12345').get() print(f'Sign Request ID is {sign_request.id}') ``` ## Cancel Sign Request Calling [`sign_requests.cancel()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.SignRequest.cancel) will cancel a created Sign Request. ``` sign_request = client.sign_request(sign_request_id='12345') cancelled_sign_request = sign_request.cancel() print(f'Cancelled Sign Request status is {cancelled_sign_request.status}') ``` ## Resend Sign Request Calling [`sign_requests.resend()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.SignRequest.resend) will resend a Sign Request to all signers that have not signed it yet. There is an 10-minute cooling-off period between re-sending reminder emails. ``` sign_request = client.sign_request(sign_request_id='12345') sign_request.resend() ``` --- ## Untitled *Type: page* Storage Policies Allows the enterprise admin to manage the Storage Policies for users in their enterprise. Used for an enterprise to decide… # Storage Policies Allows the enterprise admin to manage the Storage Policies for users in their enterprise. Used for an enterprise to decide storage location for users based on where they work/reside. - [Get Storage Policy](#get-storage-policy) - [List Available Storage Policies](#list-available-storage-policies) - [Assign a Storage Policy to a User](#assign-a-storage-policy-to-a-user) - [Get Assignment Information about a Storage Policy Assignment](#get-assignment-information-about-a-storage-policy-assignment) - [Get Assignment for User](#get-assignment-for-user) - [Delete Assignment](#delete-assignment) ## Get Storage Policy To get a storage policy object, first call [`client.storage_policy(policy_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.storage_policy) to construct the appropriate [`Storage Policy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy.StoragePolicy) object, and then calling [`storage_policy.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`StoragePolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy.StoragePolicy) object populated with data from the API. ``` storage_policy = client.storage_policy(policy_id='12345').get() print(f'Storage Policy ID is {storage_policy.id} and name is {storage_policy.name}') ``` ## List Available Storage Policies To retrieve all storage policies for an enterprise, call [`client.get_storage_policies(limit=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_storage_policies). This method returns a `BoxObjectCollection` that allows you to iterate over the [`StoragePolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy.StoragePolicy) objects in the collection. ``` storage_policies = client.get_storage_policies(limit=100) for storage_policy in storage_policies: print(f'The storage policy id is {storage_policy.id} and name is {storage_policy.name}') ``` ## Assign a Storage Policy to a User To assign a storage policy to a user, call [`storage_policy.assign(user)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy.StoragePolicy.assign) will create a [`StoragePolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy_assignment.StoragePolicyAssignment) object with data populated from the API. ``` user = client.user(user_id='12345') assignment = client.storage_policy(policy_id='56781').assign(user) print(f'Assignment ID is {assignment.id} and the assignee id is {assignment.assigned_to.id}') ``` If you know the user does not have a storage policy assigned you can directly create a storage policy assignment by calling [`storage_policy.create_assignment(user)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy.StoragePolicy.create_assignment) will create a [StoragePolicyAssignment](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy_assignment.StoragePolicyAssignment) object with data populated from the API. ``` user = client.user('56781') assignment = client.storage_policy(policy_id='12345').create_assignment(user) print(f'Storage Policy Assignment ID is {assignment.id} and the assignee ID is {assignment.assigned_to.id}') ``` If the user already has an assignment, you can call [storage_policy_assignment.update_info(data=updated_storage_policy)][update_info] with a `dict` of properties to update on the storage policy assignment. This method returns a newly update [`StoragePolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.storage_policy_assignment) object with data populated from the API, leaving the original object unmodified. ``` updated_storage_policy = {'storage_policy': {'type': 'storage_policy', 'id': '12345'}} updated_assignment = client.storage_policy_assignment(assignment_id='ZW50ZXJwcmldfgeV82MDMwMDQ=').update_info(data=updated_storage_policy) print(f'Update storage policy ID is {updated_assignment.storage_policy.id}') ``` ## Get Assignment Information about a Storage Policy Assignment To get a storage policy assignment object, first call [`client.storage_policy_assignment(assignment_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.storage_policy_assignment) to construct the appropriate [`Storage Policy Assignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy_assignment.StoragePolicyAssignment) object, and then calling [`storage_policy_assignment.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`StoragePolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy_assignment.StoragePolicyAssignment) object populated with data from the API. ``` assignment = client.storage_policy_assignment(assignment_id='12345').get() print(f'Assignment ID is {assignment.id} and the storage policy ID is {assignment.storage_policy.id}') ``` ## Get Assignment for User To get a storage policy assignment object for a user, calling [`user.get_storage_policy_assignment()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User.get_storage_policy_assignment) will return the [`StoragePolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.storage_policy_assignment.StoragePolicyAssignment) object populated with data from the API. ``` assignment = client.user(user_id='12345').get_storage_policy_assignment() print(f'Assignment ID is {assignment.id} and the storage policy ID is {assignment.storage_policy.id}') ``` ## Delete Assignment To delete a storage policy assignment, call [`storage_policy_assignment.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion was successful. ``` client.storage_policy_assignment(assignment_id='12345').delete() print('The storage policy assignment was successfully delete!') ``` --- ## Untitled *Type: page* Sign Templates Sign Templates are reusable templates that can be used to create Sign Requests. For now, Sign Templates can only be created… # Sign Templates Sign Templates are reusable templates that can be used to create Sign Requests. For now, Sign Templates can only be created through the Box web application. - [Get All Sign Templates](#get-all-sign-templates) - [Get Sign Template by ID](#get-sign-template-by-id) ## Get All Sign Templates Calling the [`client.get_sign_templates()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_sign_templates) method will return an iterable that will page through all the Sign Templates. This method offers `limit` parameter. The `limit` parameter specifies the maximum number of items to be returned in a single response. ``` sign_templates = client.get_sign_templates() for sign_template in sign_templates: print(f'(Sign Template ID: {sign_template.id})') ``` ## Get Sign Template by ID Calling the [`client.get_sign_template(template_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_sign_template) method will return a Sign Template object. ``` sign_template = client.get_sign_template('12345') print(f'(Sign Template ID: {sign_template.id})') ``` --- ## Untitled *Type: page* Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention… # Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. - [Create Retention Policy](#create-retention-policy) - [Get Retention Policy](#get-retention-policy) - [Get Retention Policies](#get-retention-policies) - [Update Retention Policy](#update-retention-policy) - [Assign Retention Policy](#assign-retention-policy) - [Get Retention Policy Assignment](#get-retention-policy-assignment) - [Get Retention Policy Assignments](#get-retention-policy-assignments) - [Get File Version Retentions](#get-file-version-retentions) (deprecated, use [Get Files under Retention for a Retention Policy Assignment](#get-files-under-retention-for-an-assignment) and [Get File Versions under Retention for a Retention Policy Assignment](#get-file-versions-under-retention-for-an-assignment) instead) - [Get Information about a File Version Retention](#get-information-about-a-file-version-retention) - [Get Files under Retention for a Retention Policy Assignment](#get-files-under-retention-for-a-retention-policy-assignment) - [Get File Versions under Retention for a Retention Policy Assignment](#get-file-versions-under-retention-for-a-retention-policy-assignment) ## Create Retention Policy To create a retention policy object, call [`client.create_retention_policy(policy_name, disposition_action, retention_length, can_owner_extend_retention=None, are_owners_notified=None, custom_notification_recipients=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_retention_policy). This will let you create a new indefinite [`RetentionPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.RetentionPolicy) object populated with data from the API. ``` policy_name = 'Test Indefinite Policy Name' disposition_action = 'remove_retention' indefinite_retention_policy = client.create_retention_policy(policy_name, disposition_action, float('inf')) print(f'Indefinite Retention Policy ID is {indefinite_retention_policy.id} and the policy name is {indefinite_retention_policy.policy_name}') ``` Alternatively, if you want to create a finite retention policy, you can do so by calling [`client.create_retention_policy(policy_name, disposition_action, retention_length=5)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_retention_policy) ``` policy_name = 'Test Finite Policy Name' disposition_action = 'remove_retention' retention_length = 5 finite_retention_policy = client.create_retention_policy(policy_name=policy_name, disposition_action=disposition_action, retention_length=retention_length) print(f'Finite Retention Policy ID is {finite_retention_policy.id} and the policy name is {finite_retention_policy.policy_name}') ``` ## Get Retention Policy To get a retention policy object, first call [`client.retention_policy(retention_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.retention_policy) to construct the appropriate [`RetentionPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.RetentionPolicy) object, and then calling [`retention_policy.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`RetentionPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.RetentionPolicy) object populated with data from the API. ``` retention_policy = client.retention_policy(retention_id='12345').get() print(f'Retention Policy ID is {retention_policy.id} and the name is {retention_policy.policy_name}') ``` ## Get Retention Policies To retrieve all retention policies for an enterprise, call [`client.get_retention_policies`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_retention_policies). This method returns a `BoxObjectCollection` that allows you to iterate over the [`Retention Policy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.RetentionPolicy) objects in the collection. ``` retention_policies = client.get_retention_policies() for policy in retention_policies: print(f'The policy ID is {policy.id} and the name is {policy.policy_name}') ``` ## Update Retention Policy To update a retention policy object, calling [`retention_policy.update_info(data=policy_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the retention policy. This method returns a newly updates [`RetentionPolicy`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.RetentionPolicy) object, leaving the original object unmodified. ``` policy_update = {'policy_name': 'New Policy Name',} updated_retention_policy = client.retention_policy(retention_id='12345').update_info(data=policy_update) print(f'Retention Policy ID is {updated_retention_policy.id} and the new policy name is {updated_retention_policy.policy_name}') ``` ## Assign Retention Policy To assign a retention policy, call [`retention_policy.assign(folder)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.RetentionPolicy.assign) will create a new [`RetentionPolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy_assignment.RetentionPolicyAssignment) object populated with data from the API. ``` folder = client.folder(folder_id='1111') assignment = client.retention_policy(retention_id='12345').assign(folder) print(f'Assignment ID is {assignment.id} and it is assigned by {assignment.assigned_by.name}') ``` ## Get Retention Policy Assignment To get a retention policy object, first call [`client.retention_policy_assignment(assignment_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.client.client.Client.retention_policy_assignment) to construct the appropriate [`Retention Policy Assignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy_assignment.RetentionPolicyAssignment) object, and then calling [`retention_policy_assignment.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`Retention Policy Assignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy_assignment.RetentionPolicyAssignment) object populated with data from the API. ``` assignment = client.retention_policy_assignment('12345').get() print(f'Assignment id is {assignment.id} and it is assigned by {assignment.assigned_by.name}') ``` ## Get Retention Policy Assignments To retrieve all retention policy assignments for an enterprise, call [`retention_policy.assignments(assignment_type=None, limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.assignments) will return a `BoxObjectCollection` that allows you to iterate over the [`RetentionPolicyAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy_assignment.RetentionPolicyAssignment) objects in the collection. ``` assignments = client.retention_policy(retention_id='12345').assignments(limit=10) for assignment in assignments: print(f'Assignment ID is {assignment.id} and it is assigned by {assignment.assigned_by.name}') ``` Alternatively, you can also specify the `type` of assignment to retrieve with [`retention_policy.assignments(assignment_type='folder')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.retention_policy.assignments). ``` assignments = client.retention_policy(retention_id='12345').assignments(assignment_type='folder', limit=10) for assignment in assignments: print(f'Assignment ID is {assignment.id} and it is assigned by {assignment.assigned_by.name}') ``` ## Get File Version Retentions To retrieve all file version retentions, call [`client.get_file_version_retentions(target_file=None, file_version=None, policy=None, disposition_action=None, disposition_before=None, disposition_after=None, limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client,Client.get_file_version_retentions). This method will return a `BoxObjectCollection` that allows you to iterate over the [`FileVersionRetention`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_version_retention.FileVersionRetention) objects in the collection. ``` retentions = client.get_file_version_retentions() for retention in retentions: print(f'The file version retention ID is {retention.id} and the data time applied at is {retention.applied_at}') ``` ## Get Information about a File Version Retention To get a file version retention object, first call [`client.file_version_retention(retention_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.file_version_retention) to construct the appropriate [`File Version Retention`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file_version_retention.FileVersionRetention) object, and then calling [`file_version_retention.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`FileVersionRetention`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.file_version_retention) object populated with data from the API. ``` retention_info = client.file_version_retention(retention_id='12345').get() print(f'The file version retention ID is {retention.id} and the data time applied at is {retention.applied_at}') ``` ## Get Files under Retention for a Retention Policy Assignment To retrieve all files under retention for a Retention Policy Assignment, call [`retention_policy_assignment.get_files_under_retention(limit=None, marker=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#module-boxsdk.object.retention_policy_assignment). This method will return a `MarkerBasedObjectCollection` that allows you to iterate over the [`File`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#module-boxsdk.object.file) objects in the collection. ``` retention_policy_assignment = client.retention_policy_assignment(assignment_id='12345').get() files_under_retention = retention_policy_assignment.get_files_under_retention() for file in files_under_retention: print(f'The file with ID {file.object_id} and name {file.name} is under retention for a retention policy assignment with ID {retention_policy_assignment.object_id}') ``` ## Get File Versions under Retention for a Retention Policy Assignment To retrieve all file versions under retention for a retention policy assignment, call [`retention_policy_assignment.get_file_versions_under_retention(limit=None, marker=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#module-boxsdk.object.retention_policy_assignment). This method will return a `MarkerBasedObjectCollection` that allows you to iterate over the [`FileVersion`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#module-boxsdk.object.file_version) objects in the collection. ``` retention_policy_assignment = client.retention_policy_assignment(assignment_id='12345').get() file_versions_under_retention = retention_policy_assignment.get_file_versions_under_retention() for file_version in file_versions_under_retention: print(f'The version {file_version.file_version.object_id} of {file_version.name} file is under retention for a retention policy assignment with ID {retention_policy_assignment.object_id}') ``` --- ## Untitled *Type: page* Terms of Service Terms of Service allows Box Admins to configure a custom Terms of Service for end users to accept/re-accept/decline for… # Terms of Service Terms of Service allows Box Admins to configure a custom Terms of Service for end users to accept/re-accept/decline for platform applications [Terms of Service](#terms-of-service) - [Create a Terms of Service](#create-a-terms-of-service) - [Edit a Terms of Service](#edit-a-terms-of-service) - [Get Terms of Service](#get-terms-of-service) - [List Terms of Service](#list-terms-of-service) - [Accept or Decline a Terms of Service](#accept-or-decline-a-terms-of-service) - [Get User Status for a Terms of Service](#get-user-status-for-a-terms-of-service) ## Create a Terms of Service A Terms of Service can be created in an enterprise. Please note that only two can be created. One external and one managed. If a terms of service already exists please use the update call to change the current terms of service. To create a Terms of Service object, calling [`client.create_terms_of_service(status, tos_type, text)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_terms_of_service) will let you create a new [`TermsOfService`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService) object with the specified status, type, and text. This method will return a newly created [`TermsOfService`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService) object populated with data from the API. ``` from boxsdk.object.terms_of_service import TermsOfServiceType, TermsOfServiceStatus terms_of_service = client.create_terms_of_service(TermsOfServiceStatus.ENABLED,TermsOfServiceType.MANAGED, 'Example Text') print(f'Terms of Service status is {terms_of_service.status} and the message is {terms_of_service.text}') ``` ## Edit a Terms of Service To update a terms of service object, first call [`terms_of_service.update_info(data=update_object)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the terms of service. This method returns a newly updated [`TermsOfService`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.terms_of_service) object, leaving the original object unmodified. ``` update_object = {'text': 'New Text'} updated_tos = client.terms_of_service(tos_id='12345').update_info(data=update_object) print(f'The updated message for your custom terms of service is {updated_tos.text} with ID {updated_tos.id}') ``` ## Get Terms of Service To get a terms of service object, call [`client.terms_of_service(service_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.terms_of_service) to construct the appropriate [`TermsOfService`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService), and then calling [`terms_of_service.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`TermsOfService`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService) object populated with data from the API. ``` terms_of_service = client.terms_of_service(tos_id='12345').get() print(f'Terms of Service ID is {terms_of_service.id} and the message is {terms_of_service.text}') ``` ## List Terms of Service To retrieve all terms of service for an enterprise, call [`client.get_terms_of_services(limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.terms_of_service). This method returns a `BoxObjectCollection` that allows you to iterate over the [`TermOfService`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService) objects in the collection. ``` terms_of_services = client.get_terms_of_services() for terms_of_service in terms_of_services: print(f'Terms of Service ID is {terms_of_service.id} and the message is {terms_of_service.text}') ``` ## Accept or Decline a Terms of Service To accept or decline a terms of service, calling [`terms_of_service.set_user_status(is_accepted, user)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService.set_user_status) will allow you to create a newly updated [`TermsOfServiceUserStatus`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service_user_status.TermsOfServiceUserStatus) object populated with data from the API, leaving the original object umodified if a [`TermsOfService`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService) object already exists for a user. If the user does not have a [`TermsOfService`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService) object assigned then [`terms_of_service.set_user_status(is_accepted, user)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service.TermsOfService.set_user_status) will create a new [`TermsOfServiceUserStatus`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service_user_status.TermsOfServiceUserStatus) object populated with data from the API. ``` user = client.user(user_id='22222') user_status = client.terms_of_service(tos_id='12345').set_user_status(is_accepted=True, user=user) print(f'User status ID is {user_status.id} and the accepted status is {user_status.is_accepted}') ``` It is important to note that regardless of whether the user has taken action on this terms of service. This will create and update the user status on the terms of service. Note that this example will make multiple API calls, if you know that your user has already accepted or decline a Terms of Service and you wish to change their status, call [`terms_of_service_user_status.update_info(data=data_to_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the terms of service user status. This method returns a newly updated [`TermsOfServiceUserStatus`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service_user_status.TermsOfServiceUserStatus) object, leaving the original object unmodified. ``` user_status = client.terms_of_service_user_status(tos_user_status_id='12345').update_info(data={'is_accepted': True}) print(f'Terms of Service User Status ID is {user_status.id} and the accepted status is {user_status.is_accepted}') ``` It is important to note that this will accept or decline a custom terms of service for a user. For a user that has taken action in this terms of service, this will update their status. If the user has never taken action on this terms of service then this will return a 404 Not Found Error. ## Get User Status for a Terms of Service To get a terms of service user status object, first call [`client.terms_of_service_user_status(status_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.client.Client.terms_of_service_user_status) to construct the appropriate [`TermsOfServiceUserStatus`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service_user_status.TermsOfServiceUserStatus) object. Then calling [`client.user(user_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.user) to construct the user you wish to retrieve a [`TermsOfServiceUserStatus`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service_user_status.TermsOfServiceUserStatus) object for. Finally, calling [`terms_of_service_user_status.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`TermsOfServiceUserStatus`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.terms_of_service_user_status.TermsOfServiceUserStatus) object populated with data from the API. ``` user = client.user(user_id='11111') user_status = client.terms_of_service(tos_id='12345').get_user_status(user) print(f'User status ID is {user_status.id} and the accepted status is {user_status.is_accepted}') ``` --- ## Untitled *Type: page* Tasks Tasks enable file-centric workflows in Box. User can create tasks on files and assign them to collaborators on Box. Get a Task's… # Tasks Tasks enable file-centric workflows in Box. User can create tasks on files and assign them to collaborators on Box. - [Get a Task's Information](#get-a-tasks-information) - [List Tasks on File](#list-tasks-on-file) - [Add Task to File](#add-task-to-file) - [Update Task Info](#update-task-info) - [Delete a Task](#delete-a-task) - [Assign a Task](#assign-a-task) - [Assign a Task with User Login](#assign-a-task-with-user-login) - [List Task Assignments](#list-task-assignments) - [Get Information about Task Assignment](#get-information-about-task-assignment) - [Update Task Assignment](#update-task-assignment) - [Delete Task Assignment](#delete-task-assignment) ## Get a Task's Information To get a task object, first call [`client.task(task_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.task) to construct the appropriate [`Task`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task.Task) object, and then calling [`task.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`Task`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task.Task) object populated with data from the API, leaving the original object unmodified. ``` task = client.task(task_id='12345').get() print(f'Task ID is {task.id} and the type is {task.type}') ``` ## List Tasks on File To retrieve all tasks on a file, call [`file.get_tasks(fields=None)`]['get_tasks'] will return a `BoxObjectCollection` that allows you to iterate over the [`Task`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task.Task) objects in the collection. ``` tasks = client.file(file_id='11111').get_tasks() for task in tasks: print(f'Task ID is {task.id} and the type is {task.type}') ``` ## Add Task to File To create a single task for a single user on a single file, call [`file.create_task(message=None, due_at=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.create_Task) will return a newly created [`Task`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task.Task) object populated with data from the API. ``` message = 'Please review this' due_at = "2014-04-03T11:09:43-07:00" task = client.file(file_id='11111').create_task(message, due_at) print(f'Task message is {task.message} and it is due at {task.due_at}') ``` ## Update Task Info To update a task object, first call [`task.update_info(data=task_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the task. This method returns a newly updated [`Task`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task.Task) object, leaving the original object unmodified. ``` task_update = {'message': 'New Message', 'due_at': '2014-04-03T11:09:43-10:00'} updated_task = client.task(task_id='12345').update_info(data=task_update) print(f'New task message is {updated_task.message} and the new due time is {updated_task.due_at}') ``` ## Delete a Task To delete a task, first call [`client.task(task_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.task) to construct the appropriate task object, and then call [`task.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deleteion was successful. ``` client.client.task('12345').delete() print('The task was successfully delete!') ``` ## Assign a Task To assign a task object, first call [`client.task(task_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.task) to construct the appropriate task object, then call [`task.assign(user)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task.Task.assign) will return an [`Task Assignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task_assignment.TaskAssignment) object, populated with data from the API. ``` user = client.user(user_id='11111') assignment = client.task(task_id='12345').assign(user) print(f'Assignment ID is {assignment.id} and is assigned to user {assignment.assigned_to.name}') ``` ## Assign a Task with User Login To assign a task object with a user login, first call [`task.assign_with_login(login)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task_assignment.assign_with_login) with a `unicode` value for user login. This method will return a [`TaskAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task_assignment.TaskAssignment) object, populated with data from the API. ``` assignment = client.task(task_id='12345').assign_with_login('test_user@example.com') print(f'Assignment ID is {assignment.id} and the assignee is {assignment.assigned_to.login}') ``` ## List Task Assignments To retrieve all assignments for an enterprise, first call [`client.task(task_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.task) to construct the appropriate task object. Then call ['task.get_assignments(fields=None)'](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task.Task.get_assignments). This method returns a `BoxObjectCollection` that allows you to iterate over the ['TaskAssignment'](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task_assignment.TaskAssignment) objects in the collection. ``` assignments = client.task(task_id='12345').get_assignments() for assignment in assignments: print(f'Assignment ID is {assignment.id} and the assignee is {assignment.assigned_to.login}') ``` ## Get Information about Task Assignment To get a task assignment object, first call [`client.task_assignment(assignment_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.task_assignment) to construct the appropriate [`TaskAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task_assignment.TaskAssignment) object, and then calling ['task_assignment.get(*, fields=None, headers=None, **kwargs)'](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`TaskAssignment`][task_assignment] object populated with data from the API. ``` assignment= client.task_assignment('12345').get() print(f'Assignment ID is {assignment.id} and assignment type is {assignment.type}') ``` ## Update Task Assignment To update a task assignment object, call [`assignment.update_info(data=updated_task)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on a task assignment. This method returns a newly update [`TaskAssignment`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.task_assignment.TaskAssignment) object, leaving the original object unmodified. ``` from boxsdk.object.task_assignment import ResolutionState updated_task = {'resolution_state': ResolutionState.APPROVED} updated_assignment = client.task_assignment(assignment_id='12345').update_info(data=updated_task) print(f'Assignment ID is {updated_assignment.id} and resolution state is {updated_assignment.resolution_state}') ``` ``` updated_task = {'message': 'new message'} updated_assignment = client.task_assignment(assignment_id='12345').update_info(data=updated_task) print(f'Assignment ID is {updated_assignment.id} and message is {updated_task.message}') ``` ## Delete Task Assignment To delete a task assignment, call [`task_assignment.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion was successful. ``` client.task_assignment(assignment_id='12345').delete() print('The task assignment was successfully delete!') ``` --- ## Untitled *Type: page* Trash Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is moved to the Trash… # Trash Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is moved to the Trash. The Trash allows you to recover files and folders that have been deleted. By default, items in the Trash will be purged after 30 days. - [List Trashed Items](#list-trashed-items) - [Get Trashed Items](#get-trashed-items) - [Restore Item from Trash](#restore-item-from-trash) - [Permanently Delete Item](#permanently-delete-item) ## List Trashed Items To retrieve all trashed items for an enterprise, call [`client.trash().get_items(imit=None, offset=None, fields=None)`][get_trashed_items]. This method returns a `BoxObjectCollection` that allows you to iterate over the [`Trash`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.trash.Trash) objects in the collection. ``` trashed_items = client.trash().get_items() for trashed_item in trashed_items: print(f'The item ID is {trashed_item.id} and the item name is {trashed_item.name}') ``` ## Get Trashed Items To get a trashed item, call [`client.trash().get_item(item, fields)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.trash.Trash.get_item) with the item you wish to retrieve passed in. This method will return the ['Item'](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item) object populated with data from the API. ``` file_to_retrieve = client.file(file_id='11111') file_from_trash = client.trash().get_item(file_to_retrieve) print(f'File ID is {file_from_trash.id} and name is {file_from_trash.name}') ``` ``` folder = client.folder(folder_id='22222') folder_from_trash = client.trash().get_item(folder) print(f'Folder ID is {folder_from_trash.id} and name is {folder_from_trash.name}') ``` ``` web_link = client.web_link(web_link_i='33333') web_link_from_trash = client.trash().get_item(web_link) print(f'Web link ID is {web_link_from_trash.id} and name is {web_link_from_trash.name}') ``` ## Restore Item from Trash To retore a trashed item, effectively undeleting it, call [`client.trash().restore(item, name=None, parent_folder, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.trash.Trash.restore_item) with the constructed [`Item`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item) object will let you restore the specific object from your trash. This method will return a [`Item`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item) object populated with data from the API, leaving the original object unmodified. ``` file_to_restore = client.file(file_id='11111') restored_file = client.trash().restore_item(file_to_restore) print(f'File ID is {restored_file.id} and name is {restored_file.name}') ``` ``` folder_to_restore = client.folder(folder_id='22222') restored_folder = client.trash().restore_item(folder_to_restore) print(f'Folder ID is {restored_folder.id} and name is {restored_folder.name}') ``` ``` web_link_to_restore = client.web_link(web_link_id='33333') restored_web_link = client.trash().restore_item(web_link_to_restore) print(f'Web link ID is {restored_web_link.id} and name is {restored_web_link.name}') ``` In order to avoid conflicts, you can set a new name and new parent folder for the item you wish to restore. ``` file_to_restore = client.file(file_id='11111') new_name = 'New File Name' new_parent_folder = client.folder(folder_id='22222') restored_file = client.trash().restore_item(file_to_restore, new_name, new_parent_folder) print(f'New name for file is {restored_file.name} and new parent folder is {restored_file.parent.name}') ``` ## Permanently Delete Item To delete an [`Item`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.item.Item) object from trash, call [`client.trash().permanently_delete_item(item)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.trash.Trash.permanently_delete). This method returns `True` to indicate that the deletion was successful. ``` file_to_delete = client.file(file_id='11111') client.trash().permanently_delete_item(file_to_delete) print('The file was deleted from trash!') ``` ``` folder = client.folder(folder_id='22222') client.trash().permanently_delete_item(folder) print('The folder was deleted from trash!') ``` ``` web_link = client.web_link(web_link_id='33333') client.trash().permanently_delete_item(web_link) print('The web link was deleted from trash!') ``` --- ## Untitled *Type: page* Users Users represent an individual's account on Box. Users Get User Information Get the Current User's Information Create An Enterprise… # Users Users represent an individual's account on Box. [Users](#users) - [Get User Information](#get-user-information) - [Get the Current User's Information](#get-the-current-users-information) - [Create An Enterprise User](#create-an-enterprise-user) - [Get the Avatar for a User](#get-the-avatar-for-a-user) - [Upload user avatar](#upload-user-avatar) - [Delete user avatar](#delete-user-avatar) - [Create An App User](#create-an-app-user) - [Update User](#update-user) - [Delete User](#delete-user) - [Invite User to Enterprise](#invite-user-to-enterprise) - [Get Email Aliases](#get-email-aliases) - [Add Email Alias](#add-email-alias) - [Remove Email Alias](#remove-email-alias) - [Get Enterprise Users](#get-enterprise-users) - [Transfer User Content](#transfer-user-content) ## Get User Information To get information about a user, call the [`user.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) method. This method returns a new [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) object with fields populated by data from the API. ``` user_id = '33333' user = client.user(user_id).get() ``` You can specify which fields on the `User` object you want by passing an `Iterable` of field names: ``` user_id = '33333' user = client.user(user_id).get(['id', 'name', 'login', 'is_sync_enabled']) if user.is_sync_enabled: print(f'User {user.id} has sync enabled') ``` ## Get the Current User's Information To get the current user, call [`client.user(user_id='me')`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.user) to create the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) object and then call [`user.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) to retrieve the user information from the API. ``` current_user = client.user().get() ``` ## Create An Enterprise User To create an enterprise user, call the [`client.create_user(name, login, **user_attributes)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_user) method. This method returns a new [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) object. ``` new_user = client.create_user('Temp User', 'user@example.com') ``` ## Get the Avatar for a User To get the avatar for a user call the [`user.get_avatar()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.user.html#boxsdk.user.User.get_avatar) method with the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) object for the user you wish to retrieve an avatar for. This will return the user avatar to you in bytes. ``` avatar = client.user('33333').get_avatar() ``` ## Upload user avatar To add or update the avatar for a user, call the [`user.upload_avatar(image_path)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.user.User.upload_avatar) method with the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User). Put the path to your image as a method parameter. The supported image extensions are `jpg`, `jpeg` and `png`. The image size cannot exceed 1024 * 1024 pixels or 1MB. ``` avatar_urls = client.user('33333').upload_avatar(image_path='path/to/the/image.png') ``` In return, you will get links to several representations of an avatar within Box account. Alternatively you can upload the avatar by passing the image byte stream and the image extension to the method [`upload_avatar_stream(image_stream, image_extension)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.user.User.upload_avatar_stream): ``` image_stream = open('path/to/the/image.png', 'rb') avatar_urls = client.user('33333').upload_avatar_stream(image_stream=image_stream, image_extension='png') ``` ## Delete user avatar To delete the user avatar image use [`delete_avatar()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.user.User.delete_avatar) method with the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User). ``` client.user('33333').delete_avatar() ``` ## Create An App User Platform applications may create App Users, which represent a "headless" user managed exclusively by the application. These users can only be accessed via the API, and cannot login to the web application or other Box services. To create a new app user, call [`client.create_user(name, login=None, **user_attributes)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_user) without a `login` value. This returns the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) object for the new app user. ``` new_app_user = client.create_user('App User 123', login=None) ``` ## Update User To update a user object, call the [`user.update_info(data=data_to_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) method with a `dict` of fields to update on the user. ``` user_id = '33333' user = client.user(user_id) updated_user = user.update_info(data={'name': 'Smart User'}) ``` ## Delete User To delete a user call the [`user.delete(notify=True, force=False)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User.delete) method. The method returns `True` to indicate that the deletion succeeded. The `notify` parameter determines whether the user should receive an email about the deletion, and the `force` parameter will cause the user to be deleted even if they still have files in their account. If `force` is set to `False` and the user still has files in their account, the deletion will fail. ``` user_id = '33333' client.user(user_id).delete(force=True) ``` ## Invite User to Enterprise To invite an existing user to join an Enterprise call the [`enterprise.invite_user(user_email)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.enterprise.Enterprise.invite_user) method. This method returns an [`Invite`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.invite.Invite) object representing the status of the invitation. ``` enterprise = client.get_current_enterprise() invitation = enterprise.invite_user('user@example.com') ``` ## Get Email Aliases To get a user's email aliases call the [`user.get_email_aliases(limit=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User.get_email_aliases) method. This method returns a [`BoxObjectCollection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.pagination.box_object_collection.BoxObjectCollection) used to iterate over the collection of [`EmailAlias`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.email_alias.EmailAlias) objects. ``` user_id = '33333' user = client.user(user_id) email_aliases = user.get_email_aliases() for alias in email_aliases: print(f'User {user.id} has email alias {alias.email}') ``` ## Add Email Alias To add an email alias for a user, call the [`user.add_email_alias(email)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User.add_email_alias) method with the email address to add as an email alias for the user. This will allow the user to log in and be collaborated by this email in addition to their login email address. Not all emails addresses can be added as email aliases. Email addresses whose domains match the domain of the login email address can always be made aliases. Email addresses whose domains differ from the domain of the login email address can be made aliases depending on the Box account configuration. The method returns an [`EmailAlias`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.email_alias.EmailAlias) object. ``` user_id = '33333' user = client.user(user_id) email_alias = user.add_email_alias('alias@example.com') ``` ## Remove Email Alias To remove an email alias from a user, call the [`user.remove_email_alias(email_alias)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User.remove_email_alias) method with the [`EmailAlias`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.email_alias.EmailAlias) object to remove. The method returns `True` to signify that the removal succeeded. ``` user_id = '33333' email_alias_id = '12345' user = client.user(user_id) email_alias = client.email_alias(email_alias_id) user.remove_email_alias(email_alias) ``` ## Get Enterprise Users To get the users in an enterprise, call [`client.users(limit=None, offset=0, filter_term=None, user_type=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.users). You can specify a `filter_term` to filter on the user's `name` and `login` fields, or select a `user_type` to filter down to only managed or external users. This method returns a [`BoxObjectCollection`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.pagination.box_object_collection.BoxObjectCollection) used to iterate over the collection of [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) objects. ``` users = client.users(user_type='all') for user in users: print(f'{user.name} (User ID: {user.id})') ``` ## Transfer User Content To move all of a user's content to a different user, call the [`user.transfer_content(self, destination_user, notify=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User.transfer_content) method with the [`User`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.user.User) object representing the destination user. This will create a new folder in the destination user's account, containing all files and folders from the original user's account; the method returns a [`Folder`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder) object representing this new folder in the destination user's account. ``` source_user_id = '33333' destination_user_id = '44444' user = client.user(source_user_id) destination_user = client.user(destination_user_id) folder = user.transfer_content(destination_user) print(f'Created new folder "{folder.name}" in the account of user {destination_user.id}') ``` --- ## Untitled *Type: page* Watermarking The ability to watermark files and folders is represented as a sub-resource on the Files and Folders resources, respectively… # Watermarking The ability to watermark files and folders is represented as a sub-resource on the Files and Folders resources, respectively. You can think of the sub-resource as a "label" marking whether the file or folder is watermarked or not. If you apply a watermark label to a folder, then all files inside of it will be protected by the watermark (e.g. previews will be watermarked). However, those files' watermark sub-resource is independent from the folder that got watermarked. This allows you to watermark files and folders independently. [Watermarking](#watermarking) - [Get Watermark on File or Folder](#get-watermark-on-file-or-folder) - [Apply Watermark on File or Folder](#apply-watermark-on-file-or-folder) - [Remove Watermark on File or Folder](#remove-watermark-on-file-or-folder) ## Get Watermark on File or Folder To get a watermark object, call [`file.get_watermark()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.file.File.get_watermark()) or [`folder.get_watermark()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.get_watermark()) will return the [`Watermark`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.watermark.Watermark) object populated with data from the API. ``` watermark = client.file(file_id='12345').get_watermark() print(f'Watermark created at {watermark.created_at} and modified at {watermark.modified_at}') ``` ``` watermark = client.folder(folder_id='11111').get_watermark() print(f'Watermark created at {watermark.created_at} and modified at {watermark.modified_at}') ``` ## Apply Watermark on File or Folder To assign a watermark on a file or folder, call [file.apply_watermark()](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.file.File.apply_watermark()) or [folder.apply_watermark()][apply-folder-watermark] will return the [`Watermark`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.watermark.Watermark) object populated with data from the API. ``` watermark = client.file(file_id='12345').apply_watermark() print(f'Watermark created at {watermark.created_at} and modified at {watermark.modified_at}') ``` ``` watermark = client.folder(folder_id='11111').apply_watermark() print(f'Watermark created at {watermark.created_at} and modified at {watermark.modified_at}') ``` ## Remove Watermark on File or Folder To remove a watermark from a file or folder, call [file.delete_watermark()](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.file.File.delete_watermark()) or [folder.delete_watermark()][delete-folder-watermark] will return `True` to indicate that the deletion was successful. ``` client.file(file_id='12345').delete_watermark() print('The file watermark was deleted!') ``` ``` client.folder(folder_id='11111').delete_watermark() print('The folder watermark was deleted!') ``` --- ## Untitled *Type: page* Webhooks Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your… # Webhooks Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your application when they occur. A webhook notifies your application by sending HTTP requests to a URL of your choosing. - [Get Information about Webhook](#get-information-about-webhook) - [List all Webhooks](#list-all-webhooks) - [Create Webhook](#create-webhook) - [Delete Webhook](#delete-webhook) - [Update Webhook](#update-webhook) - [Validate Webhook Message](#validate-webhook-message) ## Get Information about Webhook To get a webhook object, first call [`client.webhook(webhook_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.webhook) to construct the appropriate [`Webhook`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.webhook.Webhook) object, and then calling [`webhook.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`Webhook`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.webhook.Webhook) object populated with data from the API. ``` webhook = client.webhook(webhook_id='12345').get() print(f'Webhooks ID is {webhook.id} and the address is {webhook.address}') ``` ## List all Webhooks To retrieve all webhooks for an enterprise, call [`client.get_webhooks(limit=None, marker=None, fields=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.get_webhooks). This method returns a `BoxObjectCollection` that allows you to iterate over the [`Webhook`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.webhook.Webhook) objects in the collection. ``` webhooks = client.get_webhooks() for webhook in webhooks: print(f'The webhook ID is {webhook.id} and the address is {webhook.address}') ``` ## Create Webhook To create a webhook object, call [`client.create_webhook(target_url, name=None, description=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.create_webhook) will let you create a new webhook object with the specified target url, name, and description. This method will return an updated [`Webhook`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.webhook.Webhook) object populated with data from the API, leaving the original object unmodified. ``` file = client.file(file_id='12345') webhook = client.create_webhook(file, ['FILE.PREVIEWED'], 'https://example.com') print(f'Webhook ID is {webhook.id} and the address is {webhook.address}') ``` ``` folder = client.folder(folder_id='12345') webhook = client.create_webhook(folder, ['FILE.UPLOADED', 'FILE.PREVIEWED'], 'https://example.com') print(f'Webhook ID is {webhook.id} and the address is {webhook.address}') ``` ## Delete Webhook To delete a webhook, call [`webhook.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion was successful. ``` client.webhook(webhook_id='12345').delete() print('The webhook was successfully deleted!') ``` ## Update Webhook To update a webhook object, first call [`client.webhook(webhook_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.webhook) to construct the appropriate [`Webhook`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.webhook.Webhook) object, and then calling [`webhook.update_info(data=update_object)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the webhook. This method returns a new updated [`Webhook`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.webhook.Webhook) object, leaving the original object unmodified. ``` update_object = { 'triggers': ['FILE.COPIED'], 'address': 'https://newexample.com', } webhook = client.webhook(webhook_id='12345').update_info(data=update_object) print(f'Updated the webhook info for triggers: {webhook.triggers} and address: {webhook.address}') ``` ## Validate Webhook Message When you receive a webhook message from Box, you should validate it by calling [`Webhook.validate_message(body, headers, primary_key, secondary_key)`][validate_webhook]. This will protect your application against attacks. Verification ensures that the notifications were actually sent by Box and not by a malicious party and that the contents of the notification haven't been changed. ``` body = b'{"webhook":{"id":"1234567890"},"trigger":"FILE.UPLOADED","source":{"id":"1234567890","type":"file","name":"Test.txt"}}' headers = { 'box-delivery-id': 'f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f', 'box-delivery-timestamp': '2020-01-01T00:00:00-07:00', 'box-signature-algorithm': 'HmacSHA256', 'box-signature-primary': '4KvFa5/unRL8aaqOlnbInTwkOmieZkn1ZVzsAJuRipE=', 'box-signature-secondary': 'yxxwBNk7tFyQSy95/VNKAf1o+j8WMPJuo/KcFc7OS0Q=', 'box-signature-version': '1', } is_validated = Webhook.validate_message(body, headers, primary_key, secondary_key) print(f'The webhook message is validated to: {is_validated}') ``` --- ## Untitled *Type: page* Zip Allows you to create a temporary zip file on Box, containing Box files and folders, and then download it. Download a Zip File Download a… # Zip Allows you to create a temporary zip file on Box, containing Box files and folders, and then download it. - [Download a Zip File](#download-a-zip-file) ## Download a Zip File Calling [`client.download_zip(name, items, writable_stream)`][create_zip] will let you create a new zip file with the specified name and with the specified items and download it to the stream that is passed in. The response is a status `dict` that contains information about the download, including whether it was successful. The created zip file does not show up in your Box account. ``` name = 'test' file = mock_client.file('466239504569') folder = mock_client.folder('466239504580') items = [file, folder] output_file = open('test.zip', 'wb') status = client.download_zip(name, items, output_file) print(f'The status of the zip download is {status["state"]}') ``` --- ## Untitled *Type: page* Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link… # Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects. **Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)* - [Create Web Link](#create-web-link) - [Get Web Link](#get-web-link) - [Update Web Link](#update-web-link) - [Move a Web Link](#move-a-web-link) - [Copy a Web Link](#copy-a-web-link) - [Rename a Web Link](#rename-a-web-link) - [Delete Web Link](#delete-web-link) - [Create a Shared Link](#create-a-shared-link) - [Update a Shared Link](#update-a-shared-link) - [Get a Shared Link](#get-a-shared-link) - [Remove a Shared Link](#remove-a-shared-link) ## Create Web Link To create a web link object, calling [`folder.create_web_link(target_url, name=None, description=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.folder.Folder.create_web_link) will let you create a new web link with a specified name and description. This method return an newly created [`WebLink`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink) object populated with data from the API, leaving the original object unmodified. ``` web_link = client.folder(folder_id='12345').create_web_link('https://example.com', 'Example Link', 'This is the description') print(f'Web Link url is {web_link.url} and its description is {web_link.description}') ``` ## Get Web Link To get a web link object, first call [`client.web_link(web_link_id)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.client.html#boxsdk.client.client.Client.web_link) to construct the appropriate [`WebLink`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink) object, and then calling [`web_link.get(*, fields=None, headers=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.get) will return the [`WebLink`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink) object populated with data from the API, leaving the original object unmodified. ``` web_link = client.web_link(web_link_id='12345').get() print(f'Web Link ID is {web_link.id} and its type is {web_link.type}') ``` ## Update Web Link To update a web link object, call [`web_link.update_info(data=data_to_update)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.update_info) with a `dict` of properties to update on the web link. This method returns a newly updated ['WebLink'](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink) object, leaving the original object unmodified. ``` updated_web_link = client.web_link(web_link_id='12345').update_info(data={'url': 'https://newurl.com'}) ``` ## Move a Web Link To move a web link from one folder into another, call [`web_link.move(parent_folder, name=None)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.move) with the destination folder to move the web link into. You can optionally provide a `name` parameter to automatically rename the web link in case of a name conflict in the destination folder. This method returns the updated [`WebLink`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink) object in the new folder. ``` web_link_id = '11111' destination_folder_id = '44444' web_link_to_move = client.web_link(web_link_id) destination_folder = client.folder(destination_folder_id) moved_web_link = web_link_to_move.move(parent_folder=destination_folder) print(f'Web link "{moved_web_link.name}" has been moved into folder "{moved_web_link.parent.name}"') ``` ## Copy a Web Link A web link can be copied to a new folder by calling [`web_link.copy(*, parent_folder, name=None, **_kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.copy) with the destination folder and an optional new name for the web link in case there is a name conflict in the destination folder. This method returns a [`WebLink`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink) object representing the copy of the web link in the destination folder. ``` web_link = client.web_link(web_link_id='12345') web_link_copy = web_link_to_copy.copy(parent_folder=destination_folder) print(f'Web link "{web_link_copy.name}" has been copied into folder "{web_link_copy.parent.name}"') ``` ## Rename a Web Link A web link can be renamed by calling [`web_link.rename(name)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_item.BaseItem.rename). This method returns the updated [`WebLink`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink) object with a new name. ``` web_link = client.web_link(web_link_id='12345') renamed_web_link = web_link.rename("new-name") print(f'Web link was renamed to "{renamed_web_link.name}"') ``` ## Delete Web Link To delete a web link, call [`web_link.delete()`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.base_object.BaseObject.delete). This method returns `True` to indicate that the deletion was successful. ``` client.web_link('12345').delete() print('The web link was deleted!') ``` ## Create a Shared Link A shared link for a web link can be generated by calling [`web_link.get_shared_link(*, access=None, unshared_at=SDK_VALUE_NOT_SET, password=None, vanity_name=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink.get_shared_link). This method returns a `unicode` string containing the shared link URL. ``` url = client.web_link('12345').get_shared_link(access='open') print(f'The web link shared link URL is: {url}') ``` ## Update a Shared Link A shared link for a web link can be updated by calling [`web_link.get_shared_link(*, access=None, unshared_at=SDK_VALUE_NOT_SET, password=None, vanity_name=None, **kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink.get_shared_link) with an updated list of properties. This method returns a `unicode` string containing the shared link URL. ``` url = client.web_link('12345').get_shared_link(access='open', password='letmein') print(f'The web link shared link URL is: {url}') ``` ## Get a Shared Link To check for an existing shared link on a web link, simply call `web_link.shared_link` This method returns a `unicode` string containing the shared link URL. ``` shared_link = client.web_link('12345').get().shared_link url = shared_link['url'] ``` ## Remove a Shared Link A shared link for a web link can be removed by calling [`web_link.remove_shared_link(**kwargs)`](https://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html#boxsdk.object.web_link.WebLink.remove_shared_link). ``` client.web_link('12345').remove_shared_link() ``` --- ## Untitled *Type: page* Documentation Under this directory you can find documentation and samples for available SDK functionalities. You can read more about… # Documentation Under this directory you can find documentation and samples for available SDK functionalities. You can read more about supported resources on [API reference](https://developer.box.com/reference/). - [AI](https://developer.box.com/8d9194c240d49364c959eca2716c7608/ai.md) - [Authentication](https://developer.box.com/dc0b3fa5b0ea1869810d2d55e9f55c28/authentication.md) - [Classifications](https://developer.box.com/e38c515b24db20e4210c77b13331dd52/classifications.md) - [Collaboration Whitelist](https://developer.box.com/b1fba4d73980e5874e8dc99d2cf3ddb8/collaboration-whitelist.md) - [Collaborations](https://developer.box.com/58e0e1821ee0a05dcdbafe44e03c3de7/collaborations.md) - [Collections](https://developer.box.com/c11206078efcf1bb9ce312f873251ba1/collections.md) - [Comments](https://developer.box.com/4d285c8d4bb98247c48a7543455045b8/comments.md) - [Custom Requests](https://developer.box.com/eeb4f476732acae1e7c6e6a41f518a17/custom-requests.md) - [Device Pins](https://developer.box.com/c069701b826cdabfda54838e3b933b03/device-pins.md) - [Events](https://developer.box.com/7156e10b9a2bc1ac9fdd62023d2796c9/events.md) - [File Request](https://developer.box.com/df34f284d818af36bd0f76554e30930e/file-request.md) - [Files](https://developer.box.com/5e57c9b7d8c81b1a020e7ea8f72ed9e7/files.md) - [Folders](https://developer.box.com/f7e5ee16179fb52e8c10b592706847ad/folders.md) - [Groups](https://developer.box.com/5fbab21d27cb975e2e3e5c618584a70d/groups.md) - [Legal Holds](https://developer.box.com/95c21f32b98d90bea3114865f9e35ef0/legal-holds.md) - [Metadata Cascade Policies](https://developer.box.com/91bfa832e8bc14d7574df20f558f7728/metadata-cascade-policies.md) - [Metadata](https://developer.box.com/98957703715f3b88682a57c875071faf/metadata.md) - [Recent Items](https://developer.box.com/c4bb23a06ea068823f68b3539db9fe63/recent-items.md) - [Retention Policies](https://developer.box.com/0c5b0cd42026ceeb98cfdaef6059bf29/retention-policies.md) - [Search](https://developer.box.com/123af590125abb1ddf7dfb7333d4f56c/search.md) - [Sign Requests](https://developer.box.com/5e5d6b89b951b0140a2ec01686a96ebf/sign-requests.md) - [Sign Templates](https://developer.box.com/9cdc629d22368a7fb9cc95c61706f1b2/sign-templates.md) - [Storage Policies](https://developer.box.com/fb436b8d8804345e7e518c1e71b4c5d2/storage-policies.md) - [Tasks](https://developer.box.com/2c543d54a5e3bb41a14045e5010e69e4/tasks.md) - [Terms Of Service](https://developer.box.com/932773402c917580e62d4e787fcc857f/terms-of-service.md) - [Trash](https://developer.box.com/159479202d344b8e488cb46b149ca4f9/trash.md) - [Users](https://developer.box.com/749e66ffbf22bbc2c85dc0ff92edce27/users.md) - [Watermarking](https://developer.box.com/d8c02a5cba2726a9e91a9f27f83d58bc/watermarking.md) - [Web Links](https://developer.box.com/84d08d8a630c73d35ec485f1a9c41ced/web-links.md) - [Webhooks](https://developer.box.com/9822d3af25f6eb5dbec34de1488e7b90/webhooks.md) --- ## Untitled *Type: page* AI AI allows to send an intelligence request to supported large language models and returns an answer based on the provided prompt and items… # AI AI allows to send an intelligence request to supported large language models and returns an answer based on the provided prompt and items. - [Send AI question](#send-ai-request) - [Send AI text generation request](#send-ai-text-generation-request) ## Send AI question To send an AI request, use `BoxAIManager.SendAIQuestionAsync(BoxAIAskRequest aiAskRequest)` method In the request you have to provide a prompt, a list of items that your prompt refers to and a mode of the request. There are two modes available: `single_item_qa` and `multiple_item_qa`, which specifies if this request refers to for a single or multiple items. ``` BoxAIResponse response = await client.BoxAIManager.SendAIQuestionAsync( new BoxAIAskRequest { Prompt = "What is the name of the file?", Items = new List<BoxAIAskItem>() { new BoxAIAskItem() { Id = "12345" } }, Mode = AiAskMode.single_item_qa }; ); ``` NOTE: The AI endpoint may return a 412 status code if you use for your request a file which has just been updated to the box. It usually takes a few seconds for the file to be indexed and available for the AI endpoint. ## Send AI text generation request To send an AI request specifically focused on the creation of new text, call `BoxAIManager.SendAITextGenRequestAsync(BoxAiTextGenRequest aiTextGenRequest)` method. In the request you have to provide a prompt, a list of items that your prompt refers to and optionally a dialogue history, which provides additional context to the LLM in generating the response. ``` BoxAIResponse response = await client.BoxAIManager.SendAITextGenRequestAsync( new BoxAITextGenRequest { Prompt = "What is the name of the file?", Items = new List<BoxAITextGenItem>() { new BoxAITextGenItem() { Id = "12345" } }, DialogueHistory = new List<BoxAIDialogueHistory>() { new BoxAIDialogueHistory() { Prompt = "What is the name of the file?", Answer = "MyFile", CreatedAt = DateTimeOffset.Parse("2024-05-16T15:26:57-07:00") } new BoxAIDialogueHistory() { Prompt = "What is the size of the file?", Answer = "10kb", CreatedAt = DateTimeOffset.Parse("2024-05-16T15:26:57-07:00") } } }; ); ``` --- ## Untitled *Type: page* Authentication The Box API uses OAuth2 for authentication, which can be difficult to implement. The SDK makes it easier by providing classes… # Authentication The Box API uses OAuth2 for authentication, which can be difficult to implement. The SDK makes it easier by providing classes that handle obtaining tokens and automatically refreshing them when possible. See the [OAuth 2 overview](https://developer.box.com/en/guides/authentication/) for a detailed overview of how the Box API handles authentication. [Ways to Authenticate](#ways-to-authenticate) - [Developer Token](#developer-token) - [Server Auth with JWT](#server-auth-with-jwt) - [Server Auth with CCG](#server-auth-with-ccg) [Traditional 3-Legged OAuth2](#traditional-3-legged-oauth2) - [AuthRepository Implementation](#authrepository-implementation) [Box View Authentication with App Tokens](#box-view-authentication-with-app-tokens) [As-User](#as-user) [Token Exchange](#token-exchange) ## Ways to Authenticate ### Developer Token The fastest way to get started using the API is with developer tokens. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. The following example creates an API client with a developer token: ``` var config = new BoxConfigBuilder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", new Uri("http://localhost")).Build(); var session = new OAuthSession("YOUR_DEVELOPER_TOKEN", "N/A", 3600, "bearer"); var client = new BoxClient(config, session); ``` ### Server Auth with JWT Server auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. If you generated your public and private keys automatically through the [Box Developer Console](https://app.box.com/developers/console), you can use the JSON file created there to configure the SDK and create a client to make calls as the Service Account: ``` var config = BoxConfigBuilder.CreateFromJsonString(jsonConfig).Build(); var session = new BoxJWTAuth(config); var adminToken = await session.AdminTokenAsync(); //valid for 60 minutes so should be cached and re-used BoxClient adminClient = session.AdminClient(adminToken); ``` Otherwise, you'll need to provide the necessary configuration fields directly to the `BoxConfigBuilder` constructor: ``` var boxConfig = new BoxConfigBuilder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "YOUR_ENTERPRISE_ID", "ENCRYPTED_PRIVATE_KEY", "PRIVATE_KEY_PASSWORD", "PUBLIC_KEY_ID").Build(); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = await boxJWT.AdminTokenAsync(); //valid for 60 minutes so should be cached and re-used BoxClient adminClient = boxJWT.AdminClient(adminToken); adminClient.Auth.SessionAuthenticated += delegate(object o, SessionAuthenticatedEventArgs e) { string newAccessToken = e.Session.AccessToken; // cache the new access token }; ``` App auth applications also often have associated [App Users](https://developer.box.com/guides/getting-started/user-types/app-users/), which are created and managed directly by the application — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user to make calls as that user. See the [API documentation](https://developer.box.com/en/guides/applications/custom-apps/) and [sample app](https://github.com/box/box-windows-sdk-v2/tree/main/Box.V2.Samples.JWTAuth) for detailed instructions on how to use app auth. Clients for making calls as an App User or Managed User can be created with the same `BoxJWTAuth` instance as in the above examples, similarly to creating a Service Account client: ``` var appUserId = "12345"; var userToken = await boxJWT.UserTokenAsync(appUserID); //valid for 60 minutes so should be cached and re-used BoxClient appUserClient = boxJWT.UserClient(userToken, appUserId); appUserClient.Auth.SessionAuthenticated += delegate(object o, SessionAuthenticatedEventArgs e) { string newAccessToken = e.Session.AccessToken; // cache the new access token }; ``` ### Server Auth with CCG Server auth allows your application to authenticate itself with the Box API for a given enterprise. Client Credentials Grant (CCG) allows you to authenticate by providing `clientId` and `clientSecret` and `enterpriseId` of your app. By default, your application has a [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. You'll need to provide the necessary configuration fields directly to the `BoxConfigBuilder` constructor: ``` var boxConfig = new BoxConfigBuilder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET") .SetEnterpriseId("YOUR_ENTERPRISE_ID") .Build(); var boxCCG = new BoxCCGAuth(boxConfig); ``` There are two ways to create an admin client, the first one uses explicit admin token: ``` var adminToken = await boxCCG.AdminTokenAsync(); //valid for 60 minutes so should be cached and re-used IBoxClient adminClient = boxCCG.AdminClient(adminToken); adminClient.Auth.SessionAuthenticated += delegate(object o, SessionAuthenticatedEventArgs e) { string newAccessToken = e.Session.AccessToken; // cache the new access token }; ``` Second way leaves token management (caching) to the `Auth`, a new token is retrieved before the first call. Keep in mind that if you create multiple `adminClient` instances, the token won't be shared, it is expected that the `adminClient` instance is reused. ``` IBoxClient adminClient = boxCCG.AdminClient(); ``` App auth applications also often have associated [App Users](https://developer.box.com/guides/getting-started/user-types/app-users/), which are created and managed directly by the application — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user to make calls as that user. See the [API documentation](https://developer.box.com/en/guides/applications/custom-apps/) for detailed instructions on how to use app auth. Clients for making calls as an App User or Managed User can be created with the same `BoxCCGAuth` instance as in the above examples, similarly to creating a Service Account client. You don't need to provide `enterpriseId` in this case: ``` var boxConfig = new BoxConfigBuilder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET") .Build(); var boxCCG = new BoxCCGAuth(boxConfig); ``` Variant with explicit initial token: ``` var userToken = await boxCCG.UserTokenAsync("USER_ID"); //valid for 60 minutes so should be cached and re-used IBoxClient userClient = boxCCG.UserClient(userToken, "USER_ID"); userClient.Auth.SessionAuthenticated += delegate(object o, SessionAuthenticatedEventArgs e) { string newAccessToken = e.Session.AccessToken; // cache the new access token }; ``` Variant without initial token: ``` IBoxClient userClient = boxCCG.UserClient("USER_ID"); ``` ### Traditional 3-Legged OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/en/guides/applications/custom-apps/oauth2-setup/). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code. After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirect_uri` which will contain an auth code. This auth code can then be used along with your client ID and client secret to establish an API connection. The `BoxClient` will automatically refresh the access token as needed. ``` var config = new BoxConfigBuilder("CLIENT_ID", "CLIENT_SECRET", new System.Uri("YOUR_REDIRECT_URL")).Build(); var client = new BoxClient(config); OAuthSession session = // Create session from custom implementation var client = new BoxClient(config, session); ``` #### AuthRepository Implementation In order to maintain authentication and ensure that your users do not need to log in again every time they use your application, you should persist their token information to some sort of durable store (e.g. a database). The SDK provides an `AuthRepository` base class that you can extend to implement custom logic around token storage and refresh. ### Box View Authentication with App Tokens [Box View](https://developer.box.com/en/guides/embed/box-view/) uses a long-lived access token that is generated from the [Box Developer Console](https://app.box.com/developers/console) to make API calls. These access tokens cannot be automatically refreshed from the SDK, and must be manually changed in your application code. To use the primary or secondary access token generated in the Developer Console, simply create a basic client with that token: ``` var config = new BoxConfigBuilder("YOUR_CLIENT_ID", "N/A", new Uri("http://localhost")).Build(); var session = new OAuthSession("YOUR_APP_TOKEN", "N/A", 3600, "bearer"); var client = new BoxClient(config, session); ``` ## As-User The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an `As-User: USER-ID` header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). Constructing a `BoxClient` with the `asUser` parameter set will create a client that will make calls on behalf of the specified user: ``` var userId = "12345"; var client = new BoxClient(config, session, asUser: userId); ``` ## Token Exchange You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). This is useful if you want to use the [Box UI Kits](https://developer.box.com/en/guides/embed/ui-elements/), since they generally do not need full read/write permissions to run. To exchange the token held by a client for a new token with only `item_preview` scope, restricted to a single file, suitable for the [Content Preview UI Kit](https://developer.box.com/en/guides/embed/ui-elements/preview/): ``` var exchanger = new TokenExchange(client.Auth.Session.AccessToken, "item_preview"); exchanger.SetResource("https://api.box.com/2.0/files/123456789"); string downscopedToken = await exchanger.ExchangeAsync(); ``` To exchange the client's token for one with scopes to upload and delete items, but not to view their contents, which would be suitable for an less-trusted server-side process; ``` var scopes = new List<string>() { "item_upload", "item_download" }; var exchanger = new TokenExchange(client.Auth.Session.AccessToken, scopes); string downscopedToken = await exchanger.ExchangeAsync(); ``` --- ## Untitled *Type: page* Classifications Classifications are a type of metadata that allows users and applications to define and assign a content classification to… # Classifications Classifications are a type of metadata that allows users and applications to define and assign a content classification to files and folders. Classifications use the metadata APIs to add and remove classifications, and assign them to files. For more details on metadata templates please see the [metadata documentation](https://developer.box.com/98957703715f3b88682a57c875071faf/metadata.md). [Classifications](#classifications) - [Add initial classifications](#add-initial-classifications) - [List all classifications](#list-all-classifications) - [Add another classification](#add-another-classification) - [Update a classification](#update-a-classification) - [Delete a classification](#delete-a-classification) - [Delete all classifications](#delete-all-classifications) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Get classification on file](#get-classification-on-file) - [Remove classification from file](#remove-classification-from-file) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Get classification on folder](#get-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Add initial classifications If an enterprise does not already have a classification defined, the first classification(s) can be added with the `MetadataManager.CreateMetadataTemplate(BoxMetadataTemplate metadataTemplate)` method. ``` var field = new BoxMetadataTemplateField { DisplayName = "Classification", Type = "enum", Key = "Box_Security_Classification_Key", Options = new List<BoxMetadataTemplateFieldOption>() { new BoxMetadataTemplateFieldOption { Key = "Classified" } } }; var metadataTemplate = new BoxMetadataTemplate { DisplayName = "Classification", TemplateKey = "securityClassification-6VMVochwUWo", Scope = "enterprise", Fields = new List<BoxMetadataTemplateField>() { field }, }; var template = await client.MetadataManager.CreateMetadataTemplate(metadataTemplate); ``` ## List all classifications To retrieve a list of all the classifications in an enterprise call the `MetadataManager.GetMetadataTemplate(string scope, string template)` method to get the classifications template, which will contain a list of all the classifications. ``` var template = await client.MetadataManager.GetMetadataTemplate("enterprise", "securityClassification-6VMVochwUWo"); ``` ## Add another classification To add another classification, call the `MetadataManager.UpdateMetadataTemplate(IEnumerable<BoxMetadataTemplateUpdate> metadataTemplateUpdate, string scope, string template)` method with proper parameters. ``` var update = new BoxMetadataTemplateUpdate { Op = MetadataTemplateUpdateOp.addEnumOption, FieldKey = "Box_Security_Classification_Key", Data = new { key = "Sensitive" } }; var template = await client.MetadataManager .UpdateMetadataTemplate(new List<BoxMetadataTemplateUpdate>() { update }, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Update a classification To update a classification, call the `MetadataManager.UpdateMetadataTemplate(IEnumerable<BoxMetadataTemplateUpdate> metadataTemplateUpdate, string scope, string template)` method with proper parameters. ``` var update = new BoxMetadataTemplateUpdate { Op = MetadataTemplateUpdateOp.editEnumOption, FieldKey = "Box_Security_Classification_Key", EnumOptionKey = "Sensitive", Data = new { key = "Very Sensitive" } }; var template = await client.MetadataManager .UpdateMetadataTemplate(new List<BoxMetadataTemplateUpdate>() { update }, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Add classification to file To add a classification to a file, call `MetadataManager.SetFileMetadataAsync(string fileId, Dictionary<string, object> metadata, string scope, string template)` with the name of the classification template, as well as the details of the classification to add to the file. ``` var fileId = "0"; var classification = new Dictionary<string, object> { { "Box_Security_Classification_Key", "Sensitive" } }; var classificationData = await client.MetadataManager.SetFileMetadataAsync(fileId, classification, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Update classification on file To update a classification on a file, call `MetadataManager.UpdateFileMetadataAsync(string fileId, List<BoxMetadataUpdate> updates, string scope, string template)` with the name of the classification template, as well as the details of the classification to add to the file. ``` var fileId = "0"; var update = new BoxMetadataUpdate { Op = MetadataUpdateOp.replace, Path = "/Box_Security_Classification_Key", Value = "Very Sensitive" }; var classificationData = await client.MetadataManager .UpdateFileMetadataAsync(fileId, new List<BoxMetadataUpdate>() { update }, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Get classification on file Retrieve the classification on a file by calling `MetadataManager.GetFileMetadataAsync(string fileId, string scope, string template)` on a file. ``` var fileId = "0"; var fileMetadata = await client.MetadataManager.GetFileMetadataAsync(fileId, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Remove classification from file A classification can be removed from a file by calling `MetadataManager.DeleteFileMetadataAsync(string fileId, string scope, string template)`. ``` var fileId = "0"; var fileMetadata = await client.MetadataManager.DeleteFileMetadataAsync(fileId, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Add classification to folder To add a classification to a folder, call `MetadataManager.SetFolderMetadataAsync(string folderId, Dictionary<string, object> metadata, string scope, string template)` with the name of the classification template, as well as the details of the classification to add to the folder. ``` var folderId = "0"; var classification = new Dictionary<string, object> { { "Box_Security_Classification_Key", "Sensitive" } }; var classificationData = await client.MetadataManager.SetFolderMetadataAsync(folderId, classification, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Update classification on folder To update a classification on a folder, call `MetadataManager.UpdateFolderMetadataAsync(string folderId, List<BoxMetadataUpdate> updates, string scope, string template)`. with the name of the classification template, as well as the details of the classification to add to the folder. ``` var folderId = "0"; var update = new BoxMetadataUpdate { Op = MetadataUpdateOp.replace, Path = "/Box_Security_Classification_Key", Value = "Very Sensitive" }; var classificationData = await client.MetadataManager .UpdateFolderMetadataAsync(folderId, new List<BoxMetadataUpdate>(){ update }, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Get classification on folder Retrieve the classification on a folder by calling `MetadataManager.GetFolderMetadataAsync(string folderId, string scope, string template)` on a folder. ``` var folderId = "0"; var folderMetadata = await client.MetadataManager.GetFolderMetadataAsync(folderId, "enterprise", "securityClassification-6VMVochwUWo"); ``` ## Remove classification from folder A classification can be removed from a folder by calling `MetadataManager.DeleteFolderMetadataAsync(string folderId, string scope, string template)`. ``` var folderId = "0"; var folderMetadata = await client.MetadataManager.DeleteFolderMetadataAsync(folderId, "enterprise", "securityClassification-6VMVochwUWo"); ``` --- ## Untitled *Type: page* Collaboration Whitelists Collaboration Whitelists are used to determine specific email domains that can collaborate with a Box Enterprise… # Collaboration Whitelists Collaboration Whitelists are used to determine specific email domains that can collaborate with a Box Enterprise. Certain users can be exempted from these restrictions, for example if they are a trusted person who needs to collaborate outside of the normally-allowed set of domains. - [Add a Domain to Collaboration Whitelist](#add-a-domain-to-collaboration-whitelist) - [Get a Whitelisted Domain's Information](#get-a-whitelisted-domains-information) - [Get Whitelisted Domains for an Enterprise](#get-whitelisted-domains-for-an-enterprise) - [Remove a Domain from Collaboration Whitelist](#remove-a-domain-from-collaboration-whitelist) - [Exempt a User from the Collaboration Whitelist](#exempt-a-user-from-the-collaboration-whitelist) - [Get an Exempt User's Information](#get-an-exempt-users-information) - [Get All Exempt Users for an Enterprise](#get-all-exempt-users-for-an-enterprise) - [Remove a User Exemption from the Collaboration Whitelist](#remove-a-user-exemption-from-the-collaboration-whitelist) ## Add a Domain to Collaboration Whitelist You can whitelist a certain domain to allow collaboration with that domain for your enterprise by calling `CollaborationWhitelistManager.AddCollaborationWhitelistEntryAsync(string domainToWhitelist, string directionForWhitelist)`. ``` BoxCollaborationWhitelistEntry entry = await client.CollaborationWhitelistManager.AddCollaborationWhitelistEntryAsync( "example.com", "both" ); ``` ## Get a Whitelisted Domain's Information Information about a specific collaboration whitelist record, which shows the domain that is whitelisted, can be retrieved by calling `CollaborationWhitelistManager.GetCollaborationWhitelistEntryAsync(string id, IEnumerable<string> fields = null)`. ``` string entryID = "11111"; BoxCollaborationWhitelistEntry entry = await client.CollaborationWhitelistManager.GetCollaborationWhitelistEntryAsync( entryID ); ``` ## Get Whitelisted Domains for an Enterprise You can retrieve the collection of whitelisted domains for an enterprise by calling `CollaborationWhitelistManager.GetAllCollaborationWhitelistEntriesAsync(int limit= 100, string nextMarker = null, bool autoPaginate = false)`. ``` BoxCollectionMarkerBased<BoxCollaborationWhitelistEntry> whitelistedDomains = await client.CollaborationWhitelistManager .GetAllCollaborationWhitelistEntriesAsync(); ``` You can set the `limit` parameter to determine how many results will be fetched, and use the `nextMarker` parameter to manually page through the collection. Alternatively, setting the `autoPaginate` parameter to `true` will make as many API calls as necessary to retrieve the full collection and return it. ## Remove a Domain from Collaboration Whitelist You can remove a domain from the collaboration whitelist by calling `CollaborationWhitelistManager.DeleteCollaborationWhitelistEntryAsync(string id)`. ``` string entryID = "11111"; await client.CollaborationWhitelistManager.DeleteCollaborationWhitelistEntryAsync(entryID); ``` ## Exempt a User from the Collaboration Whitelist You can make a specific user exempt from the collaboration whitelist, which allows them to collaborate with users from any domain, by calling `CollaborationWhitelistManager.AddCollaborationWhitelistExemptUserAsync(string userId)`. ``` string userId = "22222"; BoxCollaborationWhitelistTargetEntry exemptUser = await client.CollaborationWhitelistManager .AddCollaborationWhitelistExemptUserAsync(userId); ``` ## Get an Exempt User's Information To retrieve information about a specific user exemption record, you can use `CollaborationWhitelistManager.GetCollaborationWhitelistExemptUserAsync(string id, IEnumerable<string> fields = null)`. ``` string exemptionID = "33333"; BoxCollaborationWhitelistTargetEntry exemptUser = await client.CollaborationWhitelistManager .GetCollaborationWhitelistExemptUserAsync(exemptionID); ``` ## Get All Exempt Users for an Enterprise To retrieve a collection of users who are exempt from the collaboration whitelist for an enterprise, call `CollaborationWhitelistManager.GetAllCollaborationWhitelistExemptUsersAsync(int limit = 100, string nextMarker = null, bool autoPaginate = false)`. ``` BoxCollectionMarkerBased<BoxCollaborationWhitelistTargetEntry> = await client.CollaborationWhitelistManager .GetAllCollaborationWhitelistExemptUsersAsync(); ``` You can set the `limit` parameter to determine how many results will be fetched, and use the `nextMarker` parameter to manually page through the collection. Alternatively, setting the `autoPaginate` parameter to `true` will make as many API calls as necessary to retrieve the full collection and return it. ## Remove a User Exemption from the Collaboration Whitelist To remove a user exemption from collaboration whitelist and make that user subject to whitelist restrictions again, you can call `CollaborationWhitelistManager.DeleteCollaborationWhitelistExemptUserAsync(string id)`. ``` string exemptionId = "55555"; await client.CollaborationWhitelistManager.DeleteCollaborationWhitelistExemptUserAsync(exemptionId); ``` --- ## Untitled *Type: page* Collaborations Collaborations are used to share folders and files between users or groups. They also define what permissions a user has for… # Collaborations Collaborations are used to share folders and files between users or groups. They also define what permissions a user has for a folder or file. - [Add a Collaboration](#add-a-collaboration) - [Edit a Collaboration](#edit-a-collaboration) - [Remove a Collaboration](#remove-a-collaboration) - [Get a Collaboration's Information](#get-a-collaborations-information) - [Get the Collaborations on a Folder](#get-the-collaborations-on-a-folder) - [Get the Collaborations on a File](#get-the-collaborations-on-a-file) - [Get Pending Collaborations](#get-pending-collaborations) ## Add a Collaboration A collaboration can be added for an existing user by calling `CollaborationsManager.AddCollaborationAsync(BoxCollaborationRequest collaborationRequest, IEnumerable<string> fields = null, bool? notify = null)`. The `Role` field of the `collaborationRequest` parameter determines what permissions the collaborator will have on the folder or file. ``` // collaborate folder 11111 with user 22222 BoxCollaborationRequest requestParams = new BoxCollaborationRequest() { Item = new BoxRequestEntity() { Type = BoxType.folder, Id = "11111" }, Role = "editor", AccessibleBy = new BoxCollaborationUserRequest() { Type = BoxType.user, Id = "22222" } }; BoxCollaboration collab = await client.CollaborationsManager.AddCollaborationAsync(requestParams); ``` Administrators can set the `notify` parameter to `false` to prevent the user who is being collaborated from receiving an email notification about the collaboration. If you want to collaborate a group, provide the type group and the group id. ``` // collaborate folder 11111 with group 333333 BoxCollaborationRequest requestParams = new BoxCollaborationRequest() { Item = new BoxRequestEntity() { Type = BoxType.folder, Id = "11111" }, Role = "editor", AccessibleBy = new BoxCollaborationUserRequest() { Type = BoxType.group, Id = "333333" } }; BoxCollaboration collab = await client.CollaborationsManager.AddCollaborationAsync(requestParams); ``` ## Edit a Collaboration A collaboration can be edited by calling `CollaborationsManager.EditCollaborationAsync(BoxCollaborationRequest collaborationRequest, IEnumerable<string> fields = null)` with the fields to be updated. For example, to change the role of a collaboration: ``` BoxCollaborationRequest requestParams = new BoxCollaborationRequest() { Id = "12345", Role = "viewer" }; BoxCollaboration collab = await client.CollaborationsManager.EditCollaborationAsync(requestParams); ``` ## Remove a Collaboration A collaboration can be removed by calling `CollaborationsManager.RemoveCollaborationAsync(string id)`. This will generally remove the user or group's access to the collaborated item. ``` await client.CollaborationsManager.RemoveCollaborationAsync(id: "12345"); ``` ## Get a Collaboration's Information To get information about a specific collaboration record, call `CollaborationsManager.GetCollaborationAsync(string id, IEnumerable<string> fields = null)` with the ID of the collaboration. ``` BoxCollaboration collab = await client.CollaborationsManager.GetCollaborationAsync(id: "22222"); ``` ## Get the Collaborations on a Folder You can get all of the collaborations on a folder by calling `FoldersManager.GetCollaborationsAsync(string id, IEnumerable<string> fields = null)` with the ID of the folder. ``` string folderId = "11111"; BoxCollection<BoxCollaboration> collaborations = await client.FoldersManager .GetCollaborationsAsync(folderId); ``` ## Get the Collaborations on a File You can get the collection of collaborations on a file by calling `FilesManager.GetCollaborationsCollectionAsync(string id, string marker = null, int? limit = null, IEnumerable<string> fields = null, bool autoPaginate = false)` with the ID of the file. ``` string fileId = "98765"; BoxCollectionMarkerBasedV2<BoxCollaboration> collaborations = await client.FilesManager .GetCollaborationsCollectionAsync(fileId); ``` ## Get Pending Collaborations A collection of all the user's pending collaborations can be retrieved with `CollaborationsManager.GetPendingCollaborationAsync(IEnumerable<string> fields = null)`. ``` BoxCollection<BoxCollaboration> pendingCollabs = await CollaborationsManager .GetPendingCollaborationAsync(); ``` --- ## Untitled *Type: page* Collections Collections are used to store a custom user-defined set of items that may not all be in the same folder. Get a User's… # Collections Collections are used to store a custom user-defined set of items that may not all be in the same folder. - [Get a User's Collections](#get-a-users-collections) - [Get the Items in a Collection](#get-the-items-in-a-collection) - [Set an Item's Collections](#set-an-items-collections) ## Get a User's Collections Get a list of all collections the user has defined by calling `CollectionsManager.GetCollectionsAsync()`. A user always has a default collection called "Favorites" which they can add items to. ``` BoxCollection<BoxCollectionItem> collections = await client.CollectionsManager.GetCollectionsAsync(); ``` ## Get the Items in a Collection Get a list of the items in a collection by passing the ID of the collection to `CollectionsManager.GetCollectionItemsAsync(string collectionId, int limit = 100, int offset = 0, IEnumerable<string> fields = null, bool autoPaginate = false)`. ``` BoxCollection<BoxItem> items = await client.CollectionsManager.GetCollectionItemsAsync(id: "11111"); ``` ## Set an Item's Collections You can set the collections an item belongs to by calling `CollectionsManager.CreateOrDeleteCollectionsForFolderAsync(string folderId, BoxCollectionsRequest collectionsRequest)` or `CollectionsManager.CreateOrDeleteCollectionsForFileAsync(string fileId, BoxCollectionsRequest collectionsRequest)`. ``` // Put file 11111 into collection 22222 BoxCollectionsRequest requestParams = new BoxCollectionsRequest() { Collections = new List<BoxRequestEntity>() { new BoxRequestEntity() { Id = "22222" } }; }; BoxFile file = await client.CollectionsManager.CreateOrDeleteCollectionsForFileAsync(fileId: "11111", requestParams); ``` --- ## Untitled *Type: page* Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. Get a Comment's Information Get… # Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. - [Get a Comment's Information](#get-a-comments-information) - [Get the Comments on a File](#get-the-comments-on-a-file) - [Add a Comment to a File](#add-a-comment-to-a-file) - [Change a Comment's Message](#change-a-comments-message) - [Delete a Comment](#delete-a-comment) ## Get a Comment's Information To get information about a specific comment, call `CommentsManager.GetInformationAsync(string id, IEnumerable<string> fields = null)` with the ID of the comment. ``` BoxComment comment = await client.CommentsManager.GetInformationAsync(id: "11111"); ``` ## Get the Comments on a File You can get all of the comments on a file by calling `FilesManager.GetCommentsAsync(string id, IEnumerable<string> fields = null)` with the ID of the file. ``` string fileId = "11111"; BoxCollection<BoxComment> comments = await client.FilesManager.GetCommentsAsync(fileId); ``` ## Add a Comment to a File A comment can be added to a file by calling `CommentsManager.AddCommentAsync(BoxCommentRequest commentRequest, IEnumerable<string> fields = null)`. ``` var requestParams = new BoxCommentRequest() { Item = new BoxRequestEntity() { Type = BoxType.File, Id = "12345" }, Message = "Great work!" }; BoxComment comment = await client.CommentsManager.AddCommentAsync(requestParams); ``` ## Change a Comment's Message The message of a comment can be changed by calling `CommentsManager.UpdateAsync(string id, BoxCommentRequest commentsRequest, IEnumerable<string> fields = null)` with the ID of the comment and the fields to update. ``` var requestParams = new BoxCommentRequest() { Message = "New message" }; BoxComment updatedComment = await client.CommentsManager.UpdateAsync(id: "11111", requestParams); ``` ## Delete a Comment A comment can be deleted by calling `CommentsManager.DeleteAsync(string id)` with the ID of the comment. ``` await client.CommentsManager.DeleteAsync(id: "11111"); ``` --- ## Untitled *Type: page* Configuration URLs configuration Base URL Account URL Upload URL Timeout Proxy Supress notifications Make API calls As-User Custom private… # Configuration [URLs configuration](#urls-configuration) - [Base URL](#base-url) - [Account URL](#account-url) - [Upload URL](#upload-url) [Timeout](#timeout) [Proxy](#proxy) [Supress notifications](#supress-notifications) [Make API calls As-User](#make-api-calls-as-user) [Custom private key decryptor for JWT](#custom-private-key-decryptor-for-jwt) ## URLs configuration ### Base URL The default base URL used for making API calls to Box can be changed by calling `SetBoxApiHostUri()` method. Default value is [https://api.box.com/](https://api.box.com/). ``` var customUri = new Uri("https://custom-api-url.com"); var boxConfig = new BoxConfigBuilder("clientID", "clientSecret") .SetBoxApiHostUri(customUri) .Build(); ``` ### Account URL The default account URL used to create OAuth authorization URL can be changed by calling `SetBoxAccountApiHostUri()` method. Default value is [https://account.box.com/api/](https://account.box.com/api/). ``` var customUri = new Uri("https://custom-account-url.com"); var boxConfig = new BoxConfigBuilder("clientID", "clientSecret") .SetBoxAccountApiHostUri(customUri) .Build(); ``` ### Upload URL The default URL used for uploads can be changed by calling `SetBoxUploadApiUri()` method. Default value is [https://upload.box.com/api/](https://upload.box.com/api/). ``` var customUri = new Uri("https://custom-upload-url.com"); var boxConfig = new BoxConfigBuilder("clientID", "clientSecret") .SetBoxUploadApiUri(customUri) .Build(); ``` ## Timeout The default request timeout can be changed by calling `SetTimeout()` method. Default timeout is 100 seconds. ``` var timeout = TimeSpan.FromSeconds(200); var boxConfig = new BoxConfigBuilder("clientID", "clientSecret") .SetTimeout(timeout) .Build(); ``` ## Proxy `BoxClient` uses .NET `WebProxy` class to support Proxy. To use proxy you need to call `SetWebProxy()` when building configuration. ``` var proxy = new WebProxy { Address = new Uri("https://my-proxy.com"), Credentials = new NetworkCredential { Domain = "myDomain", UserName = "username", Password = "password" } }; var config = new BoxConfigBuilder("clientID", "clientSecret") .SetWebProxy(proxy) .Build(); ``` ## Supress Notifications If you are making administrative API calls (that is, your application has “Manage an Enterprise” scope, and the user making the API call is a co-admin with the correct "Edit settings for your company" permission) then you can suppress both email and webhook notifications. ``` var config = new BoxConfigBuilder("clientID", "clientSecret", "redirect_uri").Build(); var auth = new OAuthSession("access_token", "refresh_token", 3600, "bearer"); var adminClient = new BoxClient(config, auth, suppressNotifications: true); ``` ## Make API calls As-User If you have an admin token with appropriate permissions, you can make API calls in the context of a managed user. In order to do this you must request Box.com to activate As-User functionality for your API key (see developer site for instructions). ``` var config = new BoxConfigBuilder("clientID", "clientSecret", "redirect_uri").Build(); var auth = new OAuthSession("access_token", "refresh_token", 3600, "bearer"); var userId = "12345678" var userClient = new BoxClient(config, auth, asUser: userId); //returns root folder items for the user with ID '12345678' var items = await userClient.FoldersManager.GetFolderItemsAsync("0", 500); ``` ## Custom private key decryptor for JWT To generate a Json Web Signature used for retrieving tokens in the JWT authentication method, the SDK decrypts an encrypted private key passed in the config. The SDK implementation currently uses `BouncyCastle.Cryptography` library. If you want to use a different implementation (e.g. for FIPS compliance reasons) you need provide implementation for `IPrivateKeyDecryptor` and pass it during creation of `BoxJwtAuth` object. ``` public class MyPrivateKeyDecryptor : IPrivateKeyDecryptor { public RSA DecryptPrivateKey(string encryptedPrivateKey, string passphrase) { // implementation goes here } } var boxJwtAuth = new BoxJWTAuth(boxConfig, new BoxService(new HttpRequestHandler(boxConfig.WebProxy, boxConfig.Timeout)), new MyPrivateKeyDecryptor()); var boxClient = new BoxClient(boxConfig, boxJwtAuth); ``` --- ## Untitled *Type: page* Constructing API Calls Manually The SDK also exposes low-level request methods for constructing your own API calls. These can be useful for… # Constructing API Calls Manually The SDK also exposes low-level request methods for constructing your own API calls. These can be useful for adding your own API calls that aren't yet explicitly supported by the SDK. To make a custom API call you need to provide implementation for `BoxResourceManager`. ``` public class BoxFolderHintsManager : BoxResourceManager { public BoxFolderHintsManager(IBoxConfig config, IBoxService service, IBoxConverter converter, IAuthRepository auth, string asUser = null, bool? suppressNotifications = null) : base(config, service, converter, auth, asUser, suppressNotifications) { } public async Task<MyCustomReturnObject> GetFolderItemsWithHintsAsync(string folderId, string xRepHints) { BoxRequest request = new BoxRequest(_config.FoldersEndpointUri, string.Format(Constants.ItemsPathString, folderId)) .Method(RequestMethod.Get) .Param(ParamFields, "representations") .Header(Constants.RequestParameters.XRepHints, xRepHints); return await ToResponseAsync<MyCustomReturnObject>(request).ConfigureAwait(false); } } ``` You need to first register your custom `BoxResourceManager`, then you can use it as any other SDK manager. ``` var client = boxJWT.UserClient(userToken, userId); client.AddResourcePlugin<BoxFolderHintsManager>(); string folderId = "11111"; string xRepHints = "[jpg?dimensions=32x32][jpg?dimensions=94x94]"; var boxFolderHintsManager = client.ResourcePlugins.Get<BoxFolderHintsManager>(); var response = await boxFolderHintsManager.GetFolderItemsWithHintsAsync(folderId, xRepHints); ``` --- ## Untitled *Type: page* Device Pins Device pins allow enterprises to control what devices can use native Box applications. To learn more about device pinning… # Device Pins Device pins allow enterprises to control what devices can use native Box applications. To learn more about device pinning, please see the [Device Pinning documentation](https://community.box.com/t5/For-Admins/Device-Pinning-Overview-And-FAQs/ta-p/172). - [Get Enterprise Device Pins](#get-enterprise-device-pins) - [Get Device Pin](#get-device-pin) - [Delete Device Pin](#delete-device-pin) ## Get Enterprise Device Pins Get all device pins records for an enterprise by calling `DevicePinManager.GetEnterpriseDevicePinsAsync(string enterpriseId, string marker = null, int limit = 100, BoxSortDirection direction = BoxSortDirection.ASC, bool autoPaginate = false)`. ``` BoxCollectionMarkerBased<BoxDevicePin> pins = await client.DevicePinManager .GetEnterpriseDevicePinsAsync(enterpriseId: "12345"); ``` ## Get Device Pin To get information about a specific device pin, call `DevicePinManager.GetDevicePin(string id)` with the ID of the device pin object. ``` BoxDevicePin pin = await client.DevicePinManager.GetDevicePin(id: "11111"); ``` ## Delete Device Pin To remove a specific device pin, call `DevicePinManager.DeleteDevicePin(string id)` with the ID of the device pin to delete. ``` await client.DevicePinManager.DeleteDevicePin(id: "11111"); ``` --- ## Untitled *Type: page* Events The event feed provides a way for an application to subscribe to any actions performed by any user, users, or service in an… # Events The event feed provides a way for an application to subscribe to any actions performed by any user, users, or service in an enterprise. [User Events](#user-events) - [Get Events Manually](#deduplicating-events) [Enterprise (Admin) Events](#enterprise-admin-events) - [Historical Querying](#historical-querying) - [Live Monitoring](#live-monitoring) ## User Events User events provides a low latency stream of events relevant to the currently authenticated user. ### Get Events Manually The SDK provides an `BoxEventsManager` class and `UserEventsAsync(int limit, UserEventsStreamType streamType, string streamPosition, bool dedupeEvents)`. By default, this will fetch the first available events chronologically. You can pass a specific `stream_position` to get events from a particular time. ``` BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.UserEventsAsync(); ``` If you want to progress within a stream you can use position parameter: ``` BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.UserEventsAsync(20); string nextStreamPosition = events.NextStreamPosition; // process revieved events BoxEventCollection<BoxEnterpriseEvent> events2 = await client.EventsManager .UserEventsAsync(20, UserEventsStreamType.all, nextStreamPosition); // get events from the next position // process revieved events ``` ## Enterprise (Admin) Events Enterprise events provide an event feed for all users and content in an enterprise Box instance. ### Historical Querying The Box API provides an `BoxEventsManager` class and `EnterpriseEventsAsync(int limit, string streamPosition, IEnumerable<string> eventTypes, DateTimeOffset? createdAfter, DateTimeOffset? createdBefore = null)` method that reads from the `admin-logs` stream and returns an `BoxEventCollection<BoxEnterpriseEvent>`. The emphasis for this stream is on completeness over latency, which means that Box will deliver admin events in chronological order and without duplicates, but with higher latency. You can specify start and end time/dates. This method will only work with an API connection for an enterprise admin account or service account with a manage enterprise properties. ``` // get the last two hours of unfiltered enterprise events var createdAfter = DateTimeOffset.UtcNow.AddHours(-2); var createdBefore = DateTimeOffset.UtcNow; BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.EnterpriseEventsAsync(500, null, null, createdAfter, createdBefore); ``` You can also filter events by type. ``` // filter events by type var eventTypestoFilter = new List<string>() { "UPLOAD" }; BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.EnterpriseEventsAsync(500, null, eventTypestoFilter); ``` If you want to progress within a stream you can use position parameter: ``` BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.EnterpriseEventsAsync(20); string nextStreamPosition = events.NextStreamPosition; // process revieved events BoxEventCollection<BoxEnterpriseEvent> events2 = await client.EventsManager .EnterpriseEventsAsync(20, nextStreamPosition); // get events from the next position // process revieved events ``` ### Live Monitoring To monitor recent events that have been generated within Box across the enterprise use `EnterpriseEventsStreamingAsync(int limit, string streamPosition, IEnumerable<string> eventTypes)`, method that reads from the `admin-logs-streaming` stream and returns an `BoxEventCollection<BoxEnterpriseEvent>`. The emphasis for this feed is on low latency rather than chronological accuracy, which means that Box may return events more than once and out of chronological order. Events are returned via the API around 12 seconds after they are processed by Box (the 12 seconds buffer ensures that new events are not written after your cursor position). Only two weeks of events are available via this feed, and you cannot set start and end time/dates. This method will only work with an API connection for an enterprise admin account or service account with a manage enterprise properties. ``` BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.EnterpriseEventsStreamingAsync(); ``` You can limit number of events returned. ``` // get first 20 events int limit = 20 BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.EnterpriseEventsStreamingAsync(limit); ``` You can also filter events by type. ``` // filter events by type var eventTypestoFilter = new List<string>() { "UPLOAD" }; BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.EnterpriseEventsStreamingAsync(500, null, eventTypestoFilter); ``` If you want to progress within a stream you can use position parameter: ``` BoxEventCollection<BoxEnterpriseEvent> events = await client.EventsManager.EnterpriseEventsStreamingAsync(20); string nextStreamPosition = events.NextStreamPosition; // process revieved events BoxEventCollection<BoxEnterpriseEvent> events2 = await client.EventsManager .EnterpriseEventsStreamingAsync(20, nextStreamPosition); // get events from the next position // process revieved events ``` If you have the next stream position, and make a subsequent call, the API will return immediately even when there are no events, the next stream position will be returned. If you have a stream position that is older than two weeks than API will return no events and next stream position. --- ## Untitled *Type: page* File Requests File request objects represent a file request associated with a folder. Get a File Request's Information Copy a File Request's… # File Requests File request objects represent a file request associated with a folder. - [Get a File Request's Information](#get-a-file-requests-information) - [Copy a File Request's Information](#copy-a-file-requests-information) - [Update a File Request's Information](#update-a-file-requests-information) - [Delete a File Request](#delete-a-file-request) ## Get a File Request's Information Calling `FileRequestsManager.GetFileRequestByIdAsync(string fileRequestId)`returns information on a file request. ``` BoxFileRequestObject fileRequest = await client.FileRequestsManager.GetFileRequestByIdAsync("12345"); ``` ## Copy a File Request's Information Calling `FileRequestsManager.CopyFileRequestAsync(string fileRequestId, BoxFileRequestCopyRequest copyRequest)` copies an existing file request that is already present on one folder, and applies it to another folder. ``` var destinationFolder = new BoxRequestEntity { Id = "123456", Type = BoxType.folder }; var copyRequest = new BoxFileRequestCopyRequest { Description = "New file request description", Folder = destinationFolder }; BoxFileRequestObject fileRequest = await client.FileRequestsManager.CopyFileRequestAsync("12345", copyRequest); ``` ## Update a File Request's Information Calling `FileRequestsManager.UpdateFileRequestAsync(string fileRequestId, BoxFileRequestUpdateRequest updateRequest)` updates a file request. This can be used to activate or deactivate a file request. ``` var updateRequest = new BoxFileRequestUpdateRequest { Description = "New file request description", Status = BoxFileRequestStatus.inactive }; BoxFileRequestObject fileRequest = await client.FileRequestsManager.UpdateFileRequestAsync("12345", updateRequest); ``` ## Delete a File Request Calling `FileRequestsManager.DeleteFileRequestAsync(string fileRequestId)` deletes a file request permanently. ``` bool isSuccess = await client.FileRequestsManager.DeleteFileRequestAsync("12345"); ``` --- ## Untitled *Type: page* Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other… # Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other common file operations (move, copy, delete, etc.). - [Get a File's Information](#get-a-files-information) - [Update a File's Information](#update-a-files-information) - [Download a File](#download-a-file) - [Get a File's Download URL](#get-a-files-download-url) - [Upload a File](#upload-a-file) - [Copy a File](#copy-a-file) - [Delete a File](#delete-a-file) - [Get Previous File Versions](#get-previous-file-versions) - [Upload a New Version of a File](#upload-a-new-version-of-a-file) - [Upload a Large File Version in Chunks](#upload-a-large-file-version-in-chunks) - [Download a Previous Version of a File](#download-a-previous-version-of-a-file) - [Promote Version](#promote-version) - [Delete a Previous File Version](#delete-a-previous-file-version) - [Lock a File](#lock-a-file) - [Unlock a File](#unlock-a-file) - [Create or update a Shared Link](#create-or-update-a-shared-link) - [Get Embed Link](#get-embed-link) - [Get Representation Info](#get-representation-info) - [Get Thumbnail](#get-thumbnail) - [Download a Zip File](#download-a-zip-file) ## Get a File's Information To get information about a specific file, call `FilesManager.GetInformationAsync(string id, IEnumerable<string> fields = null)` with the ID of the file. ``` BoxFile file = await client.FilesManager.GetInformationAsync(id: "11111"); ``` ## Update a File's Information Updating a file's information is done by calling `FilesManager.UpdateInformationAsync(BoxFileRequest fileRequest, string etag = null, IEnumerable<string> fields = null)` with the fields of the file object to update. ``` // Rename file 11111 var requestParams = new BoxFileRequest() { Id = "11111", Name = "New name.pdf" }; BoxFile updatedFile = await client.FilesManager.UpdateInformationAsync(requestParams); ``` ## Download a File A file can be downloaded by calling `FilesManager.DownloadStreamAsync(string id, string versionId = null, TimeSpan? timeout = null, int? startOffsetInBytes = null, int? endOffsetInBytes = null)`, which provides a `Stream` that will yield the file's contents. ``` Stream fileContents = await client.FilesManager.DownloadStreamAsync(id: "11111"); ``` ## Get a File's Download URL The download URL of a file an be retrieved by calling `FilesManager.GetDownloadUriAsync(string id, string versionId = null)` with the ID of the file. ``` Uri downloadUri = await client.FilesManager.GetDownloadUriAsync(id: "11111"); ``` ## Upload a File The simplest way to upload a file to a folder is by calling `FilesManager.UploadAsync(BoxFileRequest fileRequest, Stream stream, IEnumerable<string> fields = null, TimeSpan? timeout = null, byte[] contentMD5 = null, bool setStreamPositionToZero = true, Uri uploadUri = null)` with the upload parameters and a stream of the file contents to upload. ``` using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { BoxFileRequest requestParams = new BoxFileRequest() { Name = uploadFileName, Parent = new BoxRequestEntity() { Id = "0" } }; BoxFile file = await client.FilesManager.UploadAsync(requestParams, fileStream); } ``` ## Copy a File A file can be copied to a new folder with the `FilesManager.CopyAsync(BoxFileRequest fileRequest, IEnumerable<string> fields = null)` method. ``` string fileId = "11111"; string destinationFolderId = "22222"; var requestParams = new BoxFileRequest() { Id = fileId, Parent = new BoxRequestEntity() { Id = destinationFolderId } }; BoxFile fileCopy = await client.FilesManager.CopyAsync(requestParams); ``` ## Delete a File Calling the `FilesManager.DeleteAsync(string id, string etag = null)` method will move the file to the user's trash. ``` await client.FilesManager.DeleteAsync(id: "11111"); ``` ## Get Previous File Versions Retrieve a list of previous versions of a file by calling `FilesManager.ViewVersionsAsync(string id, IEnumerable<string> fields = null)` with the ID of the file. ``` BoxCollection<BoxFileVersion> previousVersions = await client.FilesManager .ViewVersionsAsync(id: "11111"); ``` ## Upload a New Version of a File A new version of a file can be uploaded by calling `FilesManager.UploadNewVersionAsync(string fileName, string fileId, Stream stream, string etag = null, IEnumerable<string> fields = null, TimeSpan? timeout = null, byte[] contentMD5 = null, bool setStreamPositionToZero = true, Uri uploadUri = null)` with the name and ID of the file, and a `Stream` of the new contents of the file. ``` using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { BoxFile file = await client.FilesManager .UploadNewVersionAsync("File v2.pdf", "11111", fileStream); } ``` ## Upload a Large File Version in Chunks A new version of a large file (over 50MB) can be uploaded by calling `FilesManager.UploadUsingSessionAsync(Stream stream, string fileName, string folderId, TimeSpan? timeout = null, IProgress<BoxProgress> progress = null)` with the `Stream` of the new contents of the file, name, parent folder ID of the file, timeout (default none) and progress listener (default null). ``` var progress = new Progress<BoxProgress>(val => { Console.WriteLine("Uploaded {0}%", val.progress); }); using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { string parentFolderId = "0"; var bFile = await client.FilesManager.UploadUsingSessionAsync(fileStream, "File v2.pdf", parentFolderId, null, progress); Console.WriteLine("{0} uploaded to folder: {1} as file: {2}", filePath, parentFolderId, bFile.Id); } ``` ## Download a Previous Version of a File For users with premium accounts, previous versions of a file can be downloaded by calling `FilesManager.DownloadStreamAsync(string id, string versionId = null, TimeSpan? timeout = null, int? startOffsetInBytes = null, int? endOffsetInBytes = null)` with the ID of the file and the optional version ID. ``` string fileId = "11111"; Stream versionContents = await client.FilesManager.DownloadStreamAsync(fileId, versionId: "22222"); ``` ## Promote Version Promote file version to the top of the stack by calling `FilesManager.PromoteVersionAsync(string id, string versionId)` with the ID of the file and the ID of the version to make the current version. This will create a new file version with the same contents as the previous version, as the current version. ``` string fileId = "11111"; BoxFileVersion current = await client.FilesManager.PromoteVersionAsync(fileId, versionId: "22222"); ``` ## Delete a Previous File Version An old version of a file can be moved to the trash by calling `FilesManager.DeleteOldVersionAsync(string id, string versionId, string etag = null)` with the ID of the file and the ID of the file version to delete. ``` string fileId = "11111"; await client.FilesManager.DeleteOldVersionAsync(fileId, versionId: "22222"); ``` ## Lock a File A file can be locked, which prevents other users from editing the file, by calling the `FilesManager.LockAsync(BoxFileLockRequest lockFileRequest, string id)` method. You may optionally prevent other users from downloading the file, as well as set an expiration time for the lock. ``` var lockParams = new BoxFileLockRequest() { Lock = new BoxFileLock() { IsDownloadPrevented = true }; }; string fileId = "11111"; BoxFileLock lock = await client.FilesManager.LockAsync(lockParams, fileId); ``` ## Unlock a File A file can be unlocked by calling `FilesManager.UnLock(string id)` with the ID of the file to unlock. ``` await client.FilesManager.UnLock(id: "11111"); ``` ## Create or update a Shared Link A shared link for a file can be created or updated by calling `FilesManager.CreateSharedLinkAsync(string id, BoxSharedLinkRequest sharedLinkRequest, IEnumerable<string> fields = null)`. ``` string fileId = "11111"; var sharedLinkParams = new BoxSharedLinkRequest() { Access = BoxSharedLinkAccessType.open, Permissions = new BoxPermissionsRequest { Download = true, Edit = true } }; BoxFile file = client.FilesManager.CreateSharedLinkAsync(fileId, sharedLinkParams); string sharedLinkUrl = file.SharedLink.Url; ``` ## Get Embed Link An embed link for a file can be generated by calling the `FilesManager.GetPreviewLinkAsync(string id)` method with the ID of the file. The embed link is an expiring URL for embedding a Box file preview into a webpage, usually via an `<iframe>` element. For more information, see the [API documentation](https://developer.box.com/en/guides/embed/box-embed/). ``` Uri embedUri = await client.FilesManager.GetPreviewLinkAsync(id: "11111"); ``` ## Get Representation Info A file's representation info can be retrieved by calling `FilesManager.GetRepresentationsAsync(BoxRepresentationRequest representationRequest)`. You will be able to fetch information regarding PDF representation, thumbnail representation, multi-page images representation, and extracted text representation. You can specify your own set of representations to get info for by manually constructing the [X-Rep-Hints value](https://developer.box.com/en/reference/get-files-id/#param-X-Rep-Hints) and passing it as `representationTypes`. ``` var requestParams = new BoxRepresentationRequest() { FileId = "11111", XRepHints = "[pdf]" }; BoxRepresentationCollection<BoxRepresentation> representations = client.FilesManager .GetRepresentationsAsync(requestParams); ``` ## Get Thumbnail A thumbnail for a file can be retrieved by calling `FilesManager.GetThumbnailAsync(string id, int? minHeight = null, int? minWidth = null, int? maxHeight = null, int? maxWidth = null, bool throttle = true, bool handleRetry = true)`. ``` Stream thumbnailContents = await client.FilesManager.GetThumbnailAsync("11111", maxWidth: 160, maxHeight: 160); ``` ## Download a Zip File Calling `FilesManager.DownloadZip(BoxZipRequest zipRequest, OutputStream output)` will let you create a new zip file with the specified name and with the specified items and download it to the stream that is passed in. The return object is a `BoxZipDownloadStatus` object that contains information about the download, including whether it was successful. The created zip file does not show up in your Box account. ``` BoxZipRequest request = new BoxZipRequest(); request.Name = "test"; request.Items = new List<BoxZipItemRequest>(); var file = new BoxZipRequestItem() { Id = "466239504569", Type = BoxZipItemType.file }; var folder = new BoxZipRequestItem() { Id = "466239504580", Type = BoxZipItemType.folder }; request.Items.Add(file); request.Items.Add(folder); Stream fs = new FileStream(@"c:\temp\MyTest.zip"); BoxZipDownloadStatus status = await _filesManager.DownloadZip(request, fs); ``` --- ## Untitled *Type: page* Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a… # Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a folder with another user or group, and perform other common folder operations (move, copy, delete, etc.). - [Get a Folder's Items](#get-a-folders-items) - [Get a Folder's Information](#get-a-folders-information) - [Update a Folder's Information](#update-a-folders-information) - [Create a Folder](#create-a-folder) - [Copy a Folder](#copy-a-folder) - [Delete a Folder](#delete-a-folder) - [Create or update a Shared Link](#create-or-update-a-shared-link) - [Create a Folder Lock](#create-a-folder-lock) - [Get Folder Locks](#get-folder-locks) - [Delete a Folder Lock](#delete-a-folder-lock) ## Get a Folder's Items Folder items can be retrieved by calling the `FoldersManager.GetFolderItemsMarkerBasedAsync(string id, int limit string marker = null, IEnumerable<string> fields = null, bool autoPaginate = false, string sort = null, BoxSortDirection? direction = null, string sharedLink = null, string sharedLinkPassword = null)` method. Use the `fields` option to specify the desired fields. Requesting information for only the fields you need can improve performance by reducing the size of the network response. Following method supports marker-based pagination. ``` BoxCollection<BoxItem> folderItems = await client.FoldersManager.GetFolderItemsMarkerBasedAsync("11111", 100); ``` Alternatively you can use method with offset-based pagination. ``` BoxCollection<BoxItem> folderItems = await client.FoldersManager.GetFolderItemsAsync("11111", 100, offset: 10); ``` ## Get a Folder's Information Folder information can be retrieved by calling `FoldersManager.GetInformationAsync(string id, IEnumerable<string> fields = null)` with the ID of the folder. ``` BoxFolder folder = await client.FoldersManager.GetInformationAsync("11111"); ``` ## Update a Folder's Information Updating a folder's information is done by calling the `FoldersManager.UpdateInformationAsync(BoxFolderRequest folderRequest, IEnumerable<string> fields = null, string etag = null)` method. ``` var requestParams = new BoxFolderRequest() { Id = "11111", Name = "My Documents (2017)" }; BoxFolder updatedFolder = await client.FoldersManager.UpdateInformationAsync(requestParams); ``` ## Create a Folder Create a subfolder inside of another folder by calling `FoldersManager.CreateAsync(BoxFolderRequest folderRequest, IEnumerable<string> fields = null)`. ``` // Create a new folder in the user's root folder var folderParams = new BoxFolderRequest() { Name = "New folder", Parent = new BoxRequestEntity() { Id = "0" } }; BoxFolder folder = await client.FoldersManager.CreateAsync(folderParams); ``` ## Copy a Folder To copy a folder from its current location into a different folder, call `FoldersManager.CopyAsync(BoxFolderRequest folderRequest, IEnumerable<string> fields = null)`. ``` // Copy folder 11111 into folder 22222 var requestParams = new BoxFolderRequest() { Id = "11111", Parent = new BoxRequestEntity() { Id = "22222" } }; BoxFolder folderCopy = await client.FoldersManager.CopyAsync(requestParams); ``` ## Delete a Folder A folder can be deleted by calling `FoldersManager.DeleteAsync(string id, bool recursive = false, string etag = null)` with the ID of the folder to delete. By default, the folder will only be deleted if it is empty; to delete the folder and all of its contents, set the optional `recursive` parameter to `true`. ``` await client.FoldersManager.DeleteAsync("11111", recursive: true); ``` ## Create or update a Shared Link You can create or update a shared link for a folder by calling `FoldersManager.CreateSharedLinkAsync(string id, BoxSharedLinkRequest sharedLinkRequest, IEnumerable<string> fields = null)` with the ID of the folder and the shared link parameters. ``` var sharedLinkParams = new BoxSharedLinkRequest() { Access = BoxSharedLinkAccessType.open }; BoxFolder folder = await client.FoldersManager.CreateSharedLinkAsync("11111", sharedLinkParams); string sharedLinkUrl = folder.SharedLink.Url; ``` ## Create a Folder Lock To lock a folder, call `FoldersManager.CreateLockAsync(string id)` with the ID of the folder. This prevents the folder from being moved and/or deleted. ``` BoxFolderLock folderLock = await _foldersManager.CreateLockAsync("11111"); ``` ## Get Folder Locks To retrieve a list of the locks on a folder, call `FoldersManager.GetLocksAsync(string id, bool autoPaginate` with the ID of the folder. Currently only one lock can exist per folder. Folder locks define access restrictions placed by folder owners to prevent specific folders from being moved or deleted. ``` BoxCollection<BoxFolderLock> folderLock = await _foldersManager.GetLocksAsync("11111"); string id = folderLock.Entries[0].Id; ``` ## Delete a Folder Lock To remove a folder lock, call `FoldersManger.DeleteLockAsync(string id)` with the ID of the folder lock. ``` await _foldersManager.DeleteLockAsync("11111"); ``` --- ## Untitled *Type: page* Groups Groups contain a set of users, and can be used in place of individual users in some operations, such as collaborations. Create Group… # Groups Groups contain a set of users, and can be used in place of individual users in some operations, such as collaborations. - [Create Group](#create-group) - [Get Group](#get-group) - [Get All Groups](#get-all-groups) - [Update Group](#update-group) - [Delete Group](#delete-group) - [Get Group Collaborations](#get-group-collaborations) - [Add a User to a Group](#add-a-user-to-a-group) - [Update Membership](#update-membership) - [Remove Membership](#remove-membership) - [Get Group Memberships](#get-group-memberships) - [Get Group Memberships for a User](#get-group-memberships-for-a-user) ## Create Group To create a new group, call `GroupsManager.CreateAsync(BoxGroupRequest groupRequest, IEnumerable<string> fields = null)` with the parameters for the group being created. ``` var groupParams = new BoxGroupRequest() { Name = "Engineers" }; BoxGroup group = await client.GroupsManager.CreateAsync(groupParams); ``` ## Get Group To retrieve the information for a group, call `GroupsManager.GetGroupAsync(string id, IEnumerable<string> fields = null)` with the ID of the group. ``` BoxGroup group = await client.GroupsManager.GetGroupAsync("11111"); ``` ## Get All Groups To get a list of all groups in the calling user's enterprise, call `GroupsManager.GetAllGroupsAsync(int? limit = null, int? offset = null, IEnumerable<string> fields = null, bool autoPaginate = false, string filterTerm = null)`. Note that this requires permission to view an enterprise's groups, which is reserved for enterprise administrators. ``` BoxCollection<BoxGroup> groups = await client.GroupsManager.GetAllGroupsAsync(); ``` ## Update Group To change the properties of a group object, call the `GroupsManager.UpdateAsync(string id, BoxGroupRequest groupRequest, IEnumerable<string> fields = null)` method with the set of properties to update. ``` var updates = new BoxGroupRequest() { Name = "New group name" }; BoxGroup updatedGroup = await client.GroupsManager.UpdateAsync("11111", updates); ``` ## Delete Group To delete a group, call `(string id)` with the ID of the group to delete. ``` await client.GroupsManager.DeleteAsync("11111"); ``` ## Get Group Collaborations To get a list of collaborations for a group, which show which items the group has access to, call `GroupsManager.GetCollaborationsForGroupAsync(string groupId, int? limit = null, int? offset = null, IEnumerable<string> fields = null, bool autoPaginate = false)` with the ID of the group. ``` BoxCollection<BoxCollaboration> groupCollaborations = await client.GroupsManager .GetCollaborationsForGroupAsync(groupId: "11111"); ``` ## Add a User to a Group To add a user to a group, call `GroupsManager.AddMemberToGroupAsync(BoxGroupMembershipRequest membershipRequest, IEnumerable<string> fields = null)`. ``` var requestParams = new BoxGroupMembershipRequest() { User = new BoxRequestEntity() { Id = "22222" }, Group = new BoxGroupRequest() { Id = "11111" } }; BoxGroupMembership membership = await client.GroupsManager.AddMemberToGroupAsync(requestParams); ``` To retrieve information about a specific membership record, which shows that a given user is in the group, call `GroupsManager.GetGroupMembershipAsync(string id, IEnumerable<string> fields = null)` with the ID of the membership object. ``` BoxGroupMembership membership = await client.GroupsManager.GetGroupMembershipAsync("33333"); ``` ## Update Membership To update a membership record, call `GroupsManager.UpdateGroupMembershipAsync(string membershipId, BoxGroupMembershipRequest memRequest, IEnumerable<string> fields = null)` with the ID of the membership object and the fields to update. ``` var updates = new BoxGroupMembershipRequest() { Role = "admin" }; BoxGroupMembership updatedMembership = await client.GroupsManager .UpdateGroupMembershipAsync("33333", updates); ``` ## Remove Membership To remove a specific membership record, which removes a user from the group, call the `GroupsManager.DeleteGroupMembershipAsync(string id)` method with the ID of the membership record to remove. ``` await client.GroupsManager.DeleteGroupMembershipAsync("33333"); ``` ## Get Group Memberships To get a list of all memberships to a group, call the `GroupsManager.GetAllGroupMembershipsForGroupAsync(string groupId, int? limit = null, int? offset = null, IEnumerable<string> fields = null, bool autoPaginate = false)` method with the ID of the group to get the list of memberships for. ``` BoxCollection<BoxGroupMembership> memberships = await client.GroupsManager .GetAllGroupMembershipsForGroupAsync("11111"); ``` ## Get Group Memberships for a User To get a list of groups to which a user belongs, call the `GroupsManager.GetAllGroupMembershipsForUserAsync(string userId, int? limit = null, int? offset = null, IEnumerable<string> fields = null, bool autoPaginate = false)` method. Note that this method requires the calling user to have permission to view groups, which is restricted to enterprise administrators. ``` BoxCollection<BoxGroupMembership> memberships = await client.GroupsManager .GetAllGroupMembershipsForUserAsync(userId: "11111"); ``` --- ## Untitled *Type: page* Legal Hold Policies A legal hold policy blocks permanent deletion of content during ongoing litigation. Admins can create legal hold… # Legal Hold Policies A legal hold policy blocks permanent deletion of content during ongoing litigation. Admins can create legal hold policies and then later assign them to specific folders, files, or users. - [Get Legal Hold Policy](#get-legal-hold-policy) - [Get Enterprise Legal Hold Policies](#get-enterprise-legal-hold-policies) - [Create Legal Hold Policy](#create-legal-hold-policy) - [Update Legal Hold Policy](#update-legal-hold-policy) - [Delete Legal Hold Policy](#delete-legal-hold-policy) - [Get Legal Hold Policy Assignment](#get-legal-hold-policy-assignment) - [Get Legal Hold Policy Assignments](#get-legal-hold-policy-assignments) - [Assign Legal Hold Policy](#assign-legal-hold-policy) - [Delete Legal Hold Policy Assignment](#delete-legal-hold-policy-assignment) - [Get File Version Legal Hold](#get-file-version-legal-hold) - [Get File Version Legal Holds](#get-file-version-legal-holds) ## Get Legal Hold Policy To retrieve information about a specific legal hold policy, call `LegalHoldPoliciesManager.GetLegalHoldPolicyAsync(string legalHoldId)` with the ID of the legal hold policy. ``` BoxLegalHoldPolicy policy = await client.LegalHoldPoliciesManager.GetLegalHoldPolicyAsync("11111"); ``` ## Get Enterprise Legal Hold Policies To retrieve all of the legal hold policies for the given enterprise, call `LegalHoldPoliciesManager.GetListLegalHoldPoliciesAsync(string policyName = null, string fields = null, int limit = 100, string marker = null, bool autoPaginate = false)`. ``` BoxCollectionMarkerBased<BoxLegalHoldPolicy> policies = await client.LegalHoldPoliciesManager .GetListLegalHoldPoliciesAsync(); ``` ## Create Legal Hold Policy To create a new legal hold policy, call `LegalHoldPoliciesManager.CreateLegalHoldPolicyAsync(BoxLegalHoldPolicyRequest createRequest)`. ``` var policyParams = new BoxLegalHoldPolicyRequest() { PolicyName = "IRS Audit" }; BoxLegalHoldPolicy policy = await client.LegalHoldPoliciesManager .CreateLegalHoldPolicyAsync(policyParams); ``` ## Update Legal Hold Policy To update or modify an existing legal hold policy, call `LegalHoldPoliciesManager.UpdateLegalHoldPolicyAsync(string legalHoldPolicyId, BoxLegalHoldPolicyRequest updateRequest)` with the ID of the policy to update and the fields to update. ``` var updates = new BoxLegalHoldPolicyRequest() { Description = "Hold for documents related to the IRS audit" }; BoxLegalHoldPolicy updatedPolicy = await client.LegalHoldPoliciesManager .UpdateLegalHoldPolicyAsync("11111", updates); ``` ## Delete Legal Hold Policy To delete a legal hold policy, call `LegalHoldPoliciesManager.DeleteLegalHoldPolicyAsync(string legalHoldPolicyId)`. Note that this is an asynchronous process - the policy will not be fully deleted yet when the response comes back. ``` await client.LegalHoldPoliciesManager.DeleteLegalHoldPolicyAsync("11111"); ``` ## Get Legal Hold Policy Assignment To retrieve information about a legal hold policy assignment, call `LegalHoldPoliciesManager.GetAssignmentAsync(string assignmentId)` with the ID of the assignment object. ``` BoxLegalHoldPolicyAssignment assignment = await client.LegalHoldPoliciesManager .GetAssignmentAsync(assignmentId: "22222"); ``` ## Get Legal Hold Policy Assignments To get a list of all legal hold policy assignments associated with a specified legal hold policy, call `LegalHoldPoliciesManager.GetAssignmentsAsync(string legalHoldPolicyId, string fields = null, string assignToType = null, string assignToId = null, int limit = 100, string marker = null, bool autoPaginate = false)` with the ID of the policy. ``` BoxCollectionMarkerBased<BoxLegalHoldPolicyAssignment> assignments = await client.LegalHoldPoliciesManager .GetAssignmentsAsync(legalHoldPolicyId: "11111"); ``` ## Assign Legal Hold Policy To assign a legal hold policy, call `LegalHoldPoliciesManager.CreateAssignmentAsync(BoxLegalHoldPolicyAssignmentRequest createRequest)`. ``` var requestParams = new BoxLegalHoldPolicyAssignmentRequest() { PolicyId = "11111", AssignTo = new BoxRequestEntity() { Type = "folder", Id = "12345" } }; BoxLegalHoldPolicyAssignment assignment = await client.LegalHoldPoliciesManager .CreateAssignmentAsync(requestParams); ``` ## Delete Legal Hold Policy Assignment To delete a legal hold assignment and remove a legal hold policy from an item, call the `LegalHoldPoliciesManager.DeleteAssignmentAsync(string assignmentId)` method. Note that this is an asynchronous process - the assignment will not be fully deleted yet when the response comes back. ``` await client.LegalHoldPoliciesManager.DeleteAssignmentAsync("22222"); ``` ## Get File Version Legal Hold A file version legal hold is a record for a held file version. To get information for a specific file version legal hold record, call `LegalHoldPoliciesManager.GetFileVersionLegalHoldAsync(string fileVersionLegalHoldId)` with the ID of the file version legal hold record. ``` BoxFileVersionLegalHold hold = await client.LegalHoldPoliciesManager .GetFileVersionLegalHoldAsync("55555"); ``` ## Get File Version Legal Holds To retrieve a list of all file version legal holds for a given policy, call `LegalHoldPoliciesManager.GetFileVersionLegalHoldsAsync(string policyId, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)` with the ID of the legal hold policy. ``` BoxCollectionMarkerBased<BoxFileVersionLegalHold> holds = await client.LegalHoldPoliciesManager .GetFileVersionLegalHoldsAsync(policyId: "11111"); ``` --- ## Untitled *Type: page* Metadata Cascade Policies A metadata cascade policy indicates if a metadata instance value should be cascaded to files and subfolders in a… # Metadata Cascade Policies A metadata cascade policy indicates if a metadata instance value should be cascaded to files and subfolders in a specific folder. Any user with edit permisions on a folder can create metadata cascade policies for that given folder. Policies are assigned to exactly one folder and exactly one metadata instance on that folder. It should be noted that there is some delay from file upload to metadata application. - [Create Metadata Cascade Policy](#create-metadata-cascade-policy) - [Get a Metadata Cascade Policy](#get-a-metadata-cascade-policy) - [Get Metadata Cascade Policies for Folder](#get-metadata-cascade-policies-for-folder) - [Force Apply Metadata Cascade Policy](#force-apply-metadata-cascade-policy) ## Create Metadata Cascade Policy To create a new metadata cascade policy, call `MetadataCascadePolicyManager.CreateCascadePolicyAsync(string folderId, string scope, string templateKey)`. ``` BoxMetadataCascadePolicy metadataCascadePolicy = await client.MetadataCascadePolicyManager .CreateCascadePolicyAsync("22222", "enterprise_11111", "templateKey"); ``` ## Get a Metadata Cascade Policy To get information about a specific metadata cascade policy, call `MetadataCascadePolicyManager.GetCascadePolicyAsync(string policyId)` ``` BoxMetadataCascadePolicy retrievedCascadePolicy = await client.MetadataCascadePolicyManager .GetCascadePolicyAsync("12345", IEnumerable<string> fields = null); ``` ## Get Metadata Cascade Policies for Folder To retrieve a collection of metadata cascade policies within a given folder for the current enterprise, use `MetadataCascadePolicyManager.GetAllMetadataCascadePoliciesAsync(string folderId, string ownerEnterpriseId = null, int limit = 100, string nextMarker = null, IEnumerable<string> fields = null, bool autopaginate = false)` ``` BoxCollectionMarkerBased<BoxMetadataCascadePolicy> metadataCascadePolicies = await client.MetadataCascadePolicyManager.GetAllMetadataCascadePoliciesAsync("12345"); ``` You can also retrieve metadata cascade policies for another enterprise with specific fields to retrieve by using `MetadataCascadePolicyManager.GetAllMetadataCascadePoliciesAsync(string folderId, string ownerEnterpriseId, int limit, IEnumberable<string> fields)` ``` string folderId = "1111"; string ownerEnterpriseId = "2222"; BoxCollectionMarkerBased<BoxMetadataCascadePolicy> metadataCascadePolicies = await client.MetadataCascadePolicyManager.GetAllMetadataCascadePoliciesAsync(folderId, ownerEnterpriseId); ``` ## Force Apply Metadata Cascade Policy To apply a policy on a folder that already has one, use `MetadataCascadePolicyManager.ForceApplyCascadePolicyAsync(string policyId, string conflictResolution)` ``` string policyId = "11111"; string conflictResolution = Constants.ConflictResolution.Overwrite BoxMetadataCascadePolicy newCascadePolicy = client.MetadataCascadePolicyManager .ForceApplyCascadePolicyAsync(policyId, conflictResolution); ``` The conflict_resolution field can be set to either `none` which will preserve the existing value on the file, or `overwrite`, which will force-apply the cascade policy's value over any existing value. --- ## Untitled *Type: page* Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of… # Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of key:value pairs that belong to files/folders. For example, an important contract may have key:value pairs of `"clientNumber":"820183"` and `"clientName":"bioMedicalCorp"`. Metadata that belongs to a file/folder is grouped by templates. Templates allow the metadata service to provide a multitude of services, such as pre-defining sets of key:value pairs or schema enforcement on specific fields. Each file/folder can have multiple distinct template instances associated with it, and templates are also grouped by scopes. Currently, the only scopes support are `enterprise` and `global`. Enterprise scopes are defined on a per enterprises basis, whereas global scopes are Box application-wide. In addition to `enterprise` scoped templates, every file on Box has access to the `global` `properties` template. The Properties template is a bucket of free form key:value string pairs, with no additional schema associated with it. Properties are ideal for scenarios where applications want to write metadata to file objects in a flexible way, without pre-defined template structure. - [Create Metadata Template](#create-metadata-template) - [Update Metadata Template](#update-metadata-template) [Get Metadata Template](#get-metadata-template) - [Get by template scope and key](#get-by-template-scope-and-key) - [Get by ID](#get-by-id) [Get Enterprise Metadata Templates](#get-enterprise-metadata-templates) [Set Metadata on a File](#set-metadata-on-a-file) [Get Metadata on a File](#get-metadata-on-a-file) [Remove Metadata from a File](#remove-metadata-from-a-file) [Set Metadata on a Folder](#set-metadata-on-a-folder) [Get Metadata on a Folder](#get-metadata-on-a-folder) [Remove Metadata from a Folder](#remove-metadata-from-a-folder) [Execute Metadata Query](#execute-metadata-query) ## Create Metadata Template To create a new metadata template, call `MetadataManager.CreateMetadataTemplate(BoxMetadataTemplate template)`. ``` var templateParams = new BoxMetadataTemplate() { TemplateKey = "marketingCollateral", DisplayName = "Marketing Collateral", Scope = "enterprise", Fields = new List<BoxMetadataTemplateField>() { new BoxMetadataTemplateField() { Type = "enum", Key = "audience", DisplayName = "Audience", Options = new List<BoxMetadataTemplateFieldOption>() { new BoxMetadataTemplateFieldOption() { Key = "internal" }, new BoxMetadataTemplateFieldOption() { Key = "external" } } }, new BoxMetadataTemplateField() { Type = "string", Key = "author", DisplayName = "Author" } } }; BoxMetadataTemplate template = await client.MetadataManager.CreateMetadataTemplate(templateParams); ``` ## Update Metadata Template To update a metadata template, call the `MetadataManager.UpdateMetadataTemplate(IEnumerable<BoxMetadataTemplateUpdate> metadataTemplateUpdate, string scope, string template)` method with the operations to perform on the template. See the [API Documentation](https://developer.box.com/en/reference/put-metadata-templates-id-id-schema/) for more information on the operations available. ``` var updates = new List<BoxMetadataTemplateUpdate>() { new BoxMetadataTemplateUpdate() { Op = MetadataTemplateUpdateOp.addEnumOption, FieldKey = "fy", Data = new { key = "FY20" } }, new BoxMetadataTemplateUpdate() { Op = MetadataTemplateUpdateOp.editTemplate, Data = new { hidden = false } } }; BoxMetadataTemplate updatedTemplate = await client.MetadataManager .UpdateMetadataTemplate(updates, "enterprise", "marketingCollateral"); ``` ## Get Metadata Template ### Get by template scope and key To retrieve a specific metadata template by its scope and template key, call the `MetadataManager.GetMetadataTemplate(string scope, string template)` method with the scope and template key. ``` BoxMetadataTemplate template = await client.MetadataManager .GetMetadataTemplate("enterprise", "marketingCollateral"); ``` ### Get by ID To get a specific metadata template by its ID, call the `MetadataManager.GetMetadataTemplateById(string templateId)` method with the ID of the template. ``` BoxMetadataTemplate template = await client.MetadataManager .GetMetadataTemplateById("17f2d715-6acb-45f2-b96a-28b15efc9faa"); ``` ## Get Enterprise Metadata Templates Get all metadata templates for the current enterprise and scope by calling `MetadataManager.GetEnterpriseMetadataAsync(string scope = "enterprise")`. ``` BoxEnterpriseMetadataTemplateCollection<BoxMetadataTemplate> templates = await client.MetadataManager .GetEnterpriseMetadataAsync(); ``` ## Get Global Metadata Templates Get all metadata templates available to all enterprises by calling `MetadataManager.GetEnterpriseMetadataAsync(string scope = "global")`. ``` BoxEnterpriseMetadataTemplateCollection<BoxMetadataTemplate> templates = await client.MetadataManager .GetEnterpriseMetadataAsync("global"); ``` ## Set Metadata on a File To set metadata on a file, call `MetadataManager.SetFileMetadataAsync(string fileId, Dictionary<string, object> metadata, string scope, string template)` with the scope and template key of the metadata template, as well as a `Dictionary` containing the metadata keys and values to set. **Note:** This method will unconditionally apply the provided metadata, overwriting existing metadata for the keys provided. To specifically create or update metadata, see the `CreateFileMetadataAsync()` and `UpdateFileMetadataAsync()` methods below. ``` var metadataValues = new Dictionary<string, object>() { { "audience", "internal" }, { "documentType", "Q1 plans" }, { "competitiveDocument", "no" }, { "status", "active" }, { "author": "M. Jones" }, { "currentState": "proposal" } }; Dictionary<string, object> metadata = await client.MetadataManager .SetFileMetadataAsync(fileId: "11111", metadataValues, "enterprise", "marketingCollateral"); ``` To add new metadata to a file, call `MetadataManager.CreateFileMetadataAsync(string fileId, Dictionary<string, object> metadata, string scope, string template)` with a metadata template and a `Dictionary` of key/value pairs to add as metadata. **Note:**: This method will only succeed if the provided metadata template is not current applied to the file, otherwise it will fail with a Conflict error. ``` var metadataValues = new Dictionary<string, object>() { { "audience", "internal" }, { "documentType", "Q1 plans" }, { "competitiveDocument", "no" }, { "status", "active" }, { "author": "M. Jones" }, { "currentState": "proposal" } }; Dictionary<string, object> metadata = await client.MetadataManager .CreateFileMetadataAsync(fileId: "11111", metadataValues, "enterprise", "marketingCollateral"); ``` Update a file's existing metadata by calling `MetadataManager.UpdateFileMetadataAsync(string fileId, List<BoxMetadataUpdate> updates, string scope, string template)` with a list of update operations to apply. **Note:** This method will only succeed if the provided metadata template has already been applied to the file; if the file does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know the file will already have metadata applied, since it will save an API call compared to `SetFileMetadataAsync()`. ``` var updates = new List<BoxMetadataUpdate>() { new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/competitiveDocument", Value = "no" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.remove, Path = "/competitiveDocument" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/status", Value = "active" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.replace, Path = "/competitiveDocument", Value = "inactive" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/author", Value = "Jones" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.copy, From="/author", Path = "/editor" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/currentState", Value = "proposal" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.move, From = "/currentState", Path = "/previousState" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.add, Path = "/currentState", Value = "reviewed" } }; Dictionary<string, object> updatedMetadata = await client.MetadataManager .UpdateFileMetadataAsync("11111", updates, "enterprise", "marketingCollateral"); ``` ## Get Metadata on a File Retrieve a specific metadata template on a file by calling `MetadataManager.GetFileMetadataAsync(string fileId, string scope, string template)` with the ID of the file and which template to fetch. ``` Dictionary<string, object> metadata = await client.MetadataManager. .GetFileMetadataAsync(fileId: "11111", "enterprise", "marketingCollateral"); ``` You can also get all metadata on a file by calling `MetadataManager.GetAllFileMetadataTemplatesAsync(string fileId)`. ``` BoxMetadataTemplateCollection<Dictionary<string, object>> metadataInstances = await client.MetadataManager .GetAllFileMetadataTemplatesAsync(fileId: "11111"); ``` ## Remove Metadata from a File A metadata template can be removed from a file by calling `MetadataManager.DeleteFileMetadataAsync(string fileId, string scope, string template)` with the ID of the file and the metadata template to remove. ``` await client.MetadataManager.DeleteFileMetadataAsync("11111", "enterprise", "marketingCollateral"); ``` ## Set Metadata on a Folder To set metadata on a folder, call `MetadataManager.SetFolderMetadataAsync(string folderId, Dictionary<string, object> metadata, string scope, string template)` with the scope and template key of the metadata template, as well as a `Dictionary` containing the metadata keys and values to set. **Note:** This method will unconditionally apply the provided metadata, overwriting existing metadata for the keys provided. To specifically create or update metadata, see the `CreateFileMetadataAsync()` and `UpdateFileMetadataAsync()` methods below. ``` var metadataValues = new Dictionary<string, object>() { { "audience", "internal" }, { "documentType", "Q1 plans" }, { "competitiveDocument", "no" }, { "status", "active" }, { "author": "M. Jones" }, { "currentState": "proposal" } }; Dictionary<string, object> metadata = await client.MetadataManager .SetFolderMetadataAsync(folderId: "11111", metadataValues, "enterprise", "marketingCollateral"); ``` To add new metadata to a folder, call `MetadataManager.CreateFolderMetadataAsync(string folderId, Dictionary<string, object> metadata, string scope, string template)` with a metadata template and a `Dictionary` of key/value pairs to add as metadata. **Note:**: This method will only succeed if the provided metadata template is not current applied to the folder, otherwise it will fail with a Conflict error. ``` var metadataValues = new Dictionary<string, object>() { { "audience", "internal" }, { "documentType", "Q1 plans" }, { "competitiveDocument", "no" }, { "status", "active" }, { "author": "M. Jones" }, { "currentState": "proposal" } }; Dictionary<string, object> metadata = await client.MetadataManager .CreateFolderMetadataAsync(folderId: "11111", metadataValues, "enterprise", "marketingCollateral"); ``` Update a folder's existing metadata by calling `MetadataManager.UpdateFolderMetadataAsync(string folderId, List<BoxMetadataUpdate> updates, string scope, string template)` with a list of update operations to apply. **Note:** This method will only succeed if the provided metadata template has already been applied to the folder; if the folder does not have existing metadata, this method will fail with a Not Found error. This is useful in cases where you know the folder will already have metadata applied, since it will save an API call compared to `SetFolderMetadataAsync()`. ``` var updates = new List<BoxMetadataUpdate>() { new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/competitiveDocument", Value = "no" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.remove, Path = "/competitiveDocument" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/status", Value = "active" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.replace, Path = "/competitiveDocument", Value = "inactive" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/author", Value = "Jones" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.copy, From="/author", Path = "/editor" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.test, Path = "/currentState", Value = "proposal" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.move, From = "/currentState", Path = "/previousState" }, new BoxMetadataUpdate() { Op = MetadataUpdateOp.add, Path = "/currentState", Value = "reviewed" } }; Dictionary<string, object> updatedMetadata = await client.MetadataManager .UpdateFolderMetadataAsync("11111", updates, "enterprise", "marketingCollateral"); ``` ## Get Metadata on a Folder Retrieve a specific metadata template on a folder by calling `MetadataManager.GetFolderMetadataAsync(string folderId, string scope, string template)` with the ID of the folder and which template to fetch. ``` Dictionary<string, object> metadata = await client.MetadataManager. .GetFolderMetadataAsync(folderId: "11111", "enterprise", "marketingCollateral"); ``` You can also get all metadata on a folder by calling `MetadataManager.GetAllFolderMetadataTemplatesAsync(string folderId)`. ``` BoxMetadataTemplateCollection<Dictionary<string, object>> metadataInstances = await client.MetadataManager .GetAllFolderMetadataTemplatesAsync(folderId: "11111"); ``` ## Remove Metadata from a Folder A metadata template can be removed from a folder by calling `MetadataManager.DeleteFolderMetadataAsync(string folderId, string scope, string template)` with the ID of the folder and the metadata template to remove. ``` await client.MetadataManager.DeleteFolderMetadataAsync("11111", "enterprise", "marketingCollateral"); ``` ## Execute Metadata Query There are two types of methods for executing a metadata query, methods without the fields parameter and with it. The method with the fields parameters returns a `BoxItem` object. The method without the fields parameters returns data that is a `BoxMetadataQueryItem` and is **deprecated**. The API will eventually not support this method and the other method should be used instead. Examples of these two types are shown below. The `MetadataManager.ExecuteMetadataQueryAsync(string from, string ancestorFolderId, IEnumerable<string> fields, string query, Dictionary<string, object> queryParameters, string indexName, List<BoxMetadataQueryOrderBy> orderBy, int limit, string marker, bool autoPaginate)` method queries files and folders based on their metadata and allows for fields to be passed in. A returned `BoxItem` must be cast to a `BoxFile` or `BoxFolder` to get its metadata. ``` var queryParams = new Dictionary<string, object>(); queryParams.Add("arg", "Bob Dylan"); List<string> fields = new List<string>(); fields.Add("id"); fields.Add("name"); fields.Add("sha1"); fields.Add("metadata.enterprise_240748.catalogImages.photographer"); BoxCollectionMarkerBased<BoxItem> items = await _metadataManager.ExecuteMetadataQueryAsync(from: "enterprise_67890.catalogImages", query: "photographer = :arg", fields: fields, queryParameters: queryParams, ancestorFolderId: "0", autoPaginate: true); BoxFile file = (BoxFile) items.Entries[0]; BoxFolder folder = (BoxFolder) items.Entries[1]; string metadataFile = file.Metadata["enterprise_240748"]["catalogImages"]["photographer"].Value; string metadataFolder = folder.Metadata["enterprise_240748"]["catalogImages"]["photographer"].Value; ``` **Deprecated** The `MetadataManager.ExecuteMetadataQueryAsync(string from, string ancestorFolderId, string query = null, Dictionary<string, object> queryParameters, string indexName, List<BoxMetadataQueryOrderBy> orderBy, int limit, string marker, bool autoPaginate)` method queries files and folders based on their metadata. ``` var queryParams = new Dictionary<string, object>(); queryParams.Add("arg", 100); List<BoxMetadataQueryOrderBy> orderByList = new List<BoxMetadataQueryOrderBy>(); var orderBy = new BoxMetadataQueryOrderBy() { FieldKey = "amount", Direction = BoxSortDirection.ASC }; orderByList.Add(orderBy); BoxCollectionMarkerBased<BoxMetadataQueryItem> items = await _metadataManager.ExecuteMetadataQueryAsync(from: "enterprise_123456.someTemplate", query: "amount >= :arg", queryParameters: queryParams, ancestorFolderId: "5555", indexName: "amountAsc", orderBy: orderByList, autoPaginate: true); ``` --- ## Untitled *Type: page* Recent Items Recent Items returns information about files that have been accessed by a user not long ago. It keeps track of items that were… # Recent Items Recent Items returns information about files that have been accessed by a user not long ago. It keeps track of items that were accessed either in the last 90 days or the last 1000 items accessed (both conditions must be met). - [Get a User's Recent Items](#get-a-users-recent-items) ## Get a User's Recent Items Get a list of all recent items the user has by calling `GetRecentItemsAsync(int limit = 100, string marker = null, IEnumerable<string> fields = null, bool autoPaginate = false)`. ``` BoxCollectionMarkerBasedV2<BoxRecentItem> recentItems = await client.RecentItemsManager .GetRecentItemsAsync(limit: 500); ``` --- ## Untitled *Type: page* Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention… # Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console. - [Create Retention Policy](#create-retention-policy) - [Get Retention Policy](#get-retention-policy) - [Update Retention Policy](#update-retention-policy) - [Get Enterprise Retention Policies](#get-enterprise-retention-policies) - [Get Retention Policy Assignments](#get-retention-policy-assignments) - [Assign Retention Policy](#assign-retention-policy) - [Get Retention Policy Assignment](#get-retention-policy-assignment) - [Get File Version Retention](#get-file-version-retention) - [Get File Version Retentions](#get-file-version-retentions) (will be deprecated in the future, use [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) and [Get File Version Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) instead) - [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) - [Get File Version Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) ## Create Retention Policy To create a new retention policy, call `RetentionPoliciesManager.CreateRetentionPolicyAsync(BoxRetentionPolicyRequest retentionPolicyRequest)` with the parameters for the new retention policy. ``` var policyParams = new BoxRetentionPolicyRequest() { PolicyName = "Important Documents!", PolicyType = "finite", RetentionLength = 365, DispositionAction = "remove_retention" }; BoxRetentionPolicy policy = await client.RetentionPoliciesManager .CreateRetentionPolicyAsync(policyParams); ``` ## Get Retention Policy To retrieve information about a specific retention policy, call `RetentionPoliciesManager.GetRetentionPolicyAsync(string id, IEnumerable<string> fields = null)` with the ID of the policy. ``` BoxRetentionPolicy policy = await client.RetentionPoliciesManager.GetRetentionPolicyAsync("11111"); ``` ## Update Retention Policy To update or modify an existing retention policy, call `RetentionPoliciesManager.UpdateRetentionPolicyAsync(string id, BoxRetentionPolicyRequest retentionPolicyRequest, IEnumerable<string> fields = null)` with the ID of the policy to update and the set of fields to update. ``` var updates = new BoxRetentionPolicyRequest() { PolicyName = "New Policy Name" }; BoxRetentionPolicy updatedPolicy = await client.RetentionPoliciesManager .UpdateRetentionPolicyAsync("11111", updates); ``` ## Get Enterprise Retention Policies To retrieve all of the retention policies for the given enterprise, call `RetentionPoliciesManager.GetRetentionPoliciesAsync(string policyName = null, string policyType = null, string createdByUserId = null, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)`. ``` BoxCollectionMarkerBased<BoxRetentionPolicy> policies = await client.RetentionPoliciesManager .GetRetentionPoliciesAsync(); ``` ## Get Retention Policy Assignments To get a list of all retention policy assignments associated with a specified retention policy, call `RetentionPoliciesManager.GetRetentionPolicyAssignmentsAsync(string retentionPolicyId, string type = null, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)` with the ID of the policy to get asisgnments for. ``` BoxCollectionMarkerBased<BoxRetentionPolicyAssignment> assignments = await client.RetentionPoliciesManager .GetRetentionPolicyAssignmentsAsync(retentionPolicyId: "11111"); ``` ## Assign Retention Policy To assign a retention policy, call `RetentionPoliciesManager.CreateRetentionPolicyAssignmentAsync(BoxRetentionPolicyAssignmentRequest policyAssignmentRequest, IEnumerable<string> fields = null)` with the parameters of the assignment. ``` var assignmentParams = new BoxRetentionPolicyAssignmentRequest() { PolicyId = "11111", AssignTo = new BoxRequestEntity() { Type = BoxType.folder, Id = "22222" } }; BoxRetentionPolicyAssignment assignment = await client.RetentionPoliciesManager .CreateRetentionPolicyAssignmentAsync(assignmentParams); ``` ## Get Retention Policy Assignment To retrieve information about a retention policy assignment, call `RetentionPoliciesManager.GetRetentionPolicyAssignmentAsync(string retentionPolicyAssignmentId, IEnumerable<string> fields = null)` with the ID of the assignment. ``` BoxRetentionPolicyAssignment assignment = await client.RetentionPoliciesManager .GetRetentionPolicyAssignmentAsync("33333"); ``` ## Get File Version Retention A file version retention is a record for a retained file version. To get information for a specific file version retention record, call the `RetentionPoliciesManager.GetFileVersionRetentionAsync(string fileVersionRetentionId, IEnumerable<string> fields = null)` method with the ID of the retention object. ``` BoxFileVersionRetention retention = await client.RetentionPoliciesManager .GetFileVersionRetentionAsync("55555"); ``` ## Get File Version Retentions To retrieve a list of all file version retentions for the given enterprise or to filter for some category of file version retention records, call `RetentionPoliciesManager.GetFileVersionRetentionsAsync(IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false, string fileId = null, string fileVersionId = null, string policyId = null, DateTime? dispositionBefore = null, DateTime? dispositionAfter = null, DispositionAction? dispositionAction = null)`. ``` BoxCollectionMarkerBased<BoxFileVersionRetention> retentions = await client.RetentionPoliciesManager .GetFileVersionRetentionsAsync(); ``` ## Get Files Under Retention For Assignment To retrieve a list of all files under retention for assignment, call `RetentionPoliciesManager.GetFilesUnderRetentionForAssignmentAsync(string retentionPolicyAssignmentId, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)`. ``` BoxCollectionMarkerBased<BoxFile> filesUnderRetentionForAssignment = await client.RetentionPoliciesManager .GetFilesUnderRetentionForAssignmentAsync("55555"); ``` ## Get File Versions Under Retention For Assignment To retrieve a list of all file versions under retention for assignment, call `RetentionPoliciesManager.GetFileVersionsUnderRetentionForAssignmentAsync(string retentionPolicyAssignmentId, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)`. ``` BoxCollectionMarkerBased<BoxFileVersion> fileVersionsUnderRetentionForAssignment = await client.RetentionPoliciesManager .GetFileVersionsUnderRetentionForAssignmentAsync("55555"); ``` --- ## Untitled *Type: page* Search Search for Content Search for Content with Shared Link Items Metadata Search Search for Content To get a list of items matching a… # Search [Search for Content](#search-for-content) - [Search for Content with Shared Link Items](#search-for-content-with-shared-link-items) - [Metadata Search](#metadata-search) ## Search for Content To get a list of items matching a search query, call the ``` SearchManager.QueryAsync(string query, string scope = null, IEnumerable<string> fileExtensions = null, DateTime? createdAfter = null, DateTime? createdBefore = null, DateTime? updatedAfter = null, DateTime? updatedBefore = null, long? sizeLowerBound = null, long? sizeUpperBound = null, IEnumerable<string> ownerUserIds = null, IEnumerable<string> ancestorFolderIds = null, IEnumerable<string> contentTypes = null, string type = null, string trashContent = null, List<BoxMetadataFilterRequest> mdFilters = null, int limit = 30, int offset = 0, IEnumerable<string> fields = null, string sort = null, BoxSortDirection? direction = null) ``` method. There are many possible options for advanced search filtering, which are documented in the [Search API Reference](https://developer.box.com/en/guides/search/). For most types of searches, a query string is required; for example, it is not possible to search for all files created after a certain date through the Search API. ``` // Search for PDF or Word documents matching "Meeting Notes" BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync("Meeting Notes", fileExtensions: new { "pdf", "docx" }); ``` ## Search for Content with Shared Link Items To get a list of items matching a search query, including items that a user might have accessed recently through a shared link, call the ``` SearchManager.QueryAsyncWithSharedLinks(string query, string scope = null, IEnumerable<string> fileExtensions = null, DateTime? createdAfter = null, DateTime? createdBefore = null, DateTime? updatedAfter = null, DateTime? updatedBefore = null, long? sizeLowerBound = null, long? sizeUpperBound = null, IEnumerable<string> ownerUserIds = null, IEnumerable<string> ancestorFolderIds = null, IEnumerable<string> contentTypes = null, string type = null, string trashContent = null, List<BoxMetadataFilterRequest> mdFilters = null, int limit = 30, int offset = 0, IEnumerable<string> fields = null, string sort = null, BoxSortDirection? direction = null) ``` method. There are many possible options for advanced search filtering, which are documented in the [Search API Reference](https://developer.box.com/en/guides/search/). For most types of searches, a query string is required. ``` // Search for PDF or Word documents matching "Meeting Notes" BoxCollection<BoxSearchResult> results = await client.SearchManager .QueryAsyncWithSharedLinks("Meeting Notes", fileExtensions: new { "pdf", "docx" }); ``` ### Metadata Search When searching on metadata values, a search query string is not required and can be set to `null`. ``` // Search for all Powerpoint presentations with the TopSecret metadata applied var metadataFilters = new List<BoxMetadataFilterRequest>() { new BoxMetadataFilterRequest() { TemplateKey = "TopSecret", Scope = "enterprise" } }; BoxCollection<BoxItem> results = await client.SearchManager .QueryAsync(null, fileExtensions: new { "pptx" }, mdFilters: metadataFilters); ``` --- ## Untitled *Type: page* Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files… # Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files and can be sent to one or more Box Sign Request Signers. - [Create Sign Request](#create-sign-request) - [Get all Sign Requests](#get-all-sign-requests) - [Get Sign Request by ID](#get-sign-request-by-id) - [Cancel Sign Request](#cancel-sign-request) - [Resend Sign Request](#resend-sign-request) ## Create Sign Request The `SignRequestsManager.CreateSignRequestAsync(BoxSignRequestCreateRequest signRequestCreateRequest)` method will create a Sign Request. You need to provide at least one file and up to ten files (from which the signing document will be created) with at least one signer to receive the Sign Request. ``` var sourceFiles = new List<BoxSignRequestCreateSourceFile> { new BoxSignRequestCreateSourceFile() { Id = "12345" } }; var signers = new List<BoxSignRequestSignerCreate> { new BoxSignRequestSignerCreate() { Email = "example@gmail.com" } }; var parentFolder = new BoxRequestEntity() { Id = "12345", Type = BoxType.folder }; var request = new BoxSignRequestCreateRequest { SourceFiles = sourceFiles, Signers = signers, ParentFolder = parentFolder }; BoxSignRequest signRequest = await client.SignRequestsManager.CreateSignRequestAsync(request); ``` If you set `isDocumentPreparationNeeded` flag to true, you need to visit `prepareUrl` before the Sign Request will be sent. For more information on `isDocumentPreparationNeeded` and the other parameters available, please refer to the [developer documentation](https://developer.box.com/guides/sign-request/). ## Get All Sign Requests Calling the `SignRequestsManager.GetSignRequestsAsync(int limit = 100, string nextMarker = null, bool autoPaginate = false)` will return an iterable that will page through all the Sign Requests. ``` BoxCollectionMarkerBased<BoxSignRequest> signRequests = await client.SignRequestsManager.GetSignRequestsAsync(); ``` ## Get Sign Request by ID Calling `SignRequestsManager.GetSignRequestByIdAsync(string signRequestId)` will return an object containing information about the Sign Request. ``` BoxSignRequest signRequest = await client.SignRequestsManager.GetSignRequestByIdAsync("12345"); ``` ## Cancel Sign Request Calling `SignRequestsManager.CancelSignRequestAsync(string signRequestId)` will cancel a created Sign Request. ``` BoxSignRequest cancelledSignRequest = await client.SignRequestsManager.CancelSignRequestAsync("12345"); ``` ## Resend Sign Request Calling `SignRequestsManager.ResendSignRequestAsync(string signRequestId)` will resend a Sign Request to all signers that have not signed it yet. There is an 10-minute cooling-off period between re-sending reminder emails. ``` await client.SignRequestsManager.ResendSignRequestAsync("12345"); ``` --- ## Untitled *Type: page* Sign Templates Box Sign enables you to create templates so you can automatically add the same fields and formatting to requests for… # Sign Templates Box Sign enables you to create templates so you can automatically add the same fields and formatting to requests for signature. With templates, you don't need to repetitively add the same fields to each request every time you send a new document for signature. - [Get All Sign Templates](#get-all-sign-templates) - [Get Sign Template by ID](#get-sign-template-by-id) ## Get All Sign Templates Calling the `SignTemplatesManager.GetSignTemplatesAsync(int limit = 100, string nextMarker = null, bool autoPaginate = false)` method will return an iterable that will page through all the Sign Templates. ``` BoxCollectionMarkerBased<BoxSignTemplate> signTemplates = await client.SignTemplatesManager.GetSignTemplatesAsync(); ``` ## Get Sign Template by ID Calling the `SignTemplatesManager.GetSignTemplateByIdAsync(string signTemplateId)` method will return the Sign Template with the given ID. ``` BoxSignTemplate signTemplate = await client.SignTemplatesManager.GetSignTemplateByIdAsync("12345"); ``` --- ## Untitled *Type: page* Storage Policies Storage policies allow enterprise administrators to choose where their content is physically stored; different policies can… # Storage Policies Storage policies allow enterprise administrators to choose where their content is physically stored; different policies can be purchased and assigned either as the default policy for the entire enterprise or on a per-user basis. ## Get Available Storage Policies for an Enterprise To get a list of the storage policies that are available for the current user's enterprise, call the `StoragePoliciesManager.GetListStoragePoliciesAsync(string fields = null, string marker = null, int limit = 100, bool autoPaginate = false)` method. ``` BoxCollectionMarkerBased<BoxStoragePolicy> policies = await client.StoragePoliciesManager .GetListStoragePoliciesAsync(); ``` ## Get Information About a Specific Storage Policy Information about a specific storage policy (by its ID) can be retrieved by calling the `StoragePoliciesManager.GetStoragePolicyAsync(String policyId)` method with the ID of the storage policy to retrieve. ``` BoxStoragePolicy policy = await client.StoragePoliciesManager.GetStoragePolicyAsync(policyId: "6"); ``` ## Assign a Storage Policy to a User To assign a storage policy to a user, call the `StoragePoliciesManager.AssignAsync(string userId, string storagePolicyId)` method with the ID of the storage policy to assign and the ID of the user to which it should be assigned. **Note:** This method will check if an assignment already exists for the user and take appropriate action. It should work regardless of the current status of the user. ``` BoxStoragePolicyAssignment assignment = await client.StoragePoliciesManager .AssignAsync(userId: "22222", storagePolicyId: "6"); ``` ## Get Information About a Specific Storage Policy Assignment To get information about a specific storage policy assignment by ID, call the `StoragePoliciesManager.GetAssignmentAsync(string assignmentId)` method with the ID of the storage policy assignment. ``` BoxStoragePolicyAssignment assignment = await client.StoragePoliciesManager .GetAssignmentAsync(assignmentId: "dXNlcl8yMjIyMg=="); ``` ## Get the Storage Policy Assigned to a User To determine which storage policy is assigned to a user, call `StoragePoliciesManager.GetAssignmentForTargetAsync(string entityId, string entityType = "user")` with the ID of the user. ``` BoxStoragePolicyAssignment assignment = client.StoragePoliciesManager .GetAssignmentForTargetAsync("22222"); ``` ## Create a Storage Policy Assignment To create a new storage policy assignment, call the `StoragePoliciesManager.CreateAssignmentAsync(string userId, string policyId)` method with the ID of the storage policy to assign and the ID of the user to assign it to. **Note:** This method only works if the user does not already have an assignment. If the current state of the user is not known, use the [`AssignAsync()`](#assign-a-storage-policy-to-a-user) method instead. ``` BoxStoragePolicyAssignment assignment = client.StoragePoliciesManager .CreateAssignmentAsync(userId: "22222", policyId: "6"); ``` ## Update a Storage Policy Assignment To update a storage policy assignment, for example to update which storage policy is asisgned to a user, call the `StoragePoliciesManager.UpdateStoragePolicyAssignment(string assignmentId, String policyId)` method with the ID of the assignment to update and the new policy ID to assign. ``` // Reassign user 1234 to storage policy 7 BoxStoragePolicyAssignment assignment = await client.StoragePoliciesManager .UpdateStoragePolicyAssignment(assignmentId: "dXNlcl8yMjIyMg==", policyId: "7"); ``` ## Remove a Storage Policy Assignment To remove a storage policy assignment and return the user it was assigned to to the default storage policy for the enterprise, call `StoragePoliciesManager.DeleteAssignmentAsync(string assignmentId)` with the ID of the assignment to remove. ``` await client.StoragePoliciesManager.DeleteAssignmentAsync(assignmentId: "dXNlcl8yMjIyMg=="); ``` --- ## Untitled *Type: page* Tasks Tasks enable file-centric workflows in Box. User can create tasks on files and assign them to collaborators on Box. Get a Task's… # Tasks Tasks enable file-centric workflows in Box. User can create tasks on files and assign them to collaborators on Box. - [Get a Task's Information](#get-a-tasks-information) - [Get Tasks on a File](#get-tasks-on-a-file) - [Create a Task](#create-a-task) - [Update a Task](#update-a-task) - [Delete a Task](#delete-a-task) - [Get Assignments for a Task](#get-assignments-for-a-task) - [Assign Task](#assign-task) - [Get Task Assignment](#get-task-assignment) - [Update Task Assignment](#update-task-assignment) - [Remove Task Assignment](#remove-task-assignment) ## Get a Task's Information To get a task information call `TasksManager.GetTaskAsync(string taskId)` with the ID of the task. ``` BoxTask task = await client.TasksManager.GetTaskAsync("11111"); ``` ## Get Tasks on a File Calling the `FilesManager.GetFileTasks(string id, IEnumerable<string> fields = null)` method will retrieve all of the tasks for the given file. ``` BoxCollection<BoxTask> tasks = await client.FilesManager.FilesManager.GetFileTasks("11111"); ``` ## Create a Task To create a task, call `TasksManager.CreateTaskAsync(BoxTaskCreateRequest taskCreateRequest)` with the parameters of the task. ``` var taskParams = new BoxTaskCreateRequest() { Item = new BoxRequestEntity() { Type = BoxType.file, Id = "11111" }, Message = "Please review!" }; BoxTask task = await client.TasksManager.CreateTaskAsync(taskParams); ``` ## Update a Task To update a task, call `TasksManager.UpdateTaskAsync(BoxTaskUpdateRequest taskUpdateRequest)`. ``` var updates = new BoxTaskUpdateRequest() { Id = "22222", Message = "Could you please review this?" }; BoxTask updatedTask = await client.TasksManager.UpdateTaskAsync(updates); ``` ## Delete a Task To delete a task, call the `TasksManager.DeleteTaskAsync(string taskId)` method with the ID of the task to be deleted. ``` await client.TasksManager.DeleteTaskAsync("11111"); ``` ## Get Assignments for a Task To get a list of assignments for a task, which associate the task to users who must complete it, call `TasksManager.GetAssignmentsAsync(string taskId)` with the ID of the task. ``` BoxCollection<BoxTaskAssignment> assignments = await client.TasksManager .GetAssignmentsAsync(taskId: "11111"); ``` ## Assign Task To assign a task to a user, call `TasksManager.CreateTaskAssignmentAsync(BoxTaskAssignmentRequest taskAssignmentRequest)` with the ID of the task to assign and either the ID or login email address of the user to whom the task should be assigned. ``` // Assign task 11111 to user 22222 var assignmentParams = new BoxTaskAssignmentRequest() { Task = new BoxTaskRequest() { Id = "11111" }, AssignTo = new BoxAssignmentRequest() { Id = "22222" } }; BoxTaskAssignment assignment = await client.TasksManager.CreateTaskAssignmentAsync(assignmentParams); ``` ``` // Assign task 11111 to user with login user@example.com var assignmentParams = new BoxTaskAssignmentRequest() { Task = new BoxTaskRequest() { Id = "11111" }, AssignTo = new BoxAssignmentRequest() { Login = "user@example.com" } }; BoxTaskAssignment assignment = await client.TasksManager.CreateTaskAssignmentAsync(assignmentParams); ``` ## Get Task Assignment To retrieve information about a specific task assignment, call the `TasksManager.GetTaskAssignmentAsync(string taskAssignmentId)` method with the ID of the assignment to get. ``` BoxTaskAssignment assignment = await client.TasksManager.GetTaskAssignmentAsync("12345"); ``` ## Update Task Assignment To update a task assignment, call the `TasksManager.UpdateTaskAssignmentAsync(BoxTaskAssignmentUpdateRequest taskAssignmentUpdateRequest)` method. This can be used to resolve or complete a task. Updating the resolution state: ``` var requestParams = new BoxTaskAssignmentUpdateRequest() { Id = "12345", ResolutionState = ResolutionStateType.approved }; BoxTaskAssignment updatedAssignment = await client.TasksManager.UpdateTaskAssignmentAsync(requestParams); ``` Updating the message: ``` var requestParams = new BoxTaskAssignmentUpdateRequest() { Id = "12345", Message = "Updated message" }; BoxTaskAssignment updatedAssignment = await client.TasksManager.UpdateTaskAssignmentAsync(requestParams); ``` ## Remove Task Assignment To delete a task assignment, effectively unassigning a user from the task, call the `TasksManager.DeleteTaskAssignmentAsync(string taskAssignmentId)` method with the ID of the assignment to remove. ``` await client.TasksManager.DeleteTaskAssignmentAsync("12345"); ``` --- ## Untitled *Type: page* Terms of Service Terms of Service are custom objects that the admin of an enterprise can configure. This will prompt the end user to accept… # Terms of Service Terms of Service are custom objects that the admin of an enterprise can configure. This will prompt the end user to accept/re-accept or decline the custom Terms of Service for platform applications built on Box Platform. [Terms of Service](#terms-of-service) - [Create a Terms of Service for an Enterprise](#create-a-terms-of-service-for-an-enterprise) - [Update a Terms of Service for an Enterprise](#update-a-terms-of-service-for-an-enterprise) - [Get a Terms of Service By ID](#get-a-terms-of-service-by-id) - [Get Terms of Service for an Enterprise](#get-terms-of-service-for-an-enterprise) - [Create User Status on Terms of Service](#create-user-status-on-terms-of-service) - [Update User Status on Terms of Service](#update-user-status-on-terms-of-service) - [Get Terms of Service Status for User](#get-terms-of-service-status-for-user) ## Create a Terms of Service for an Enterprise To create a terms of service call the `TermsOfServiceManager.CreateTermsOfServicesAsync(BoxTermsOfServicesRequest termsOfServicesRequest)` method with the parameters for the new terms of service. ``` var tosParams = new CreateTermsOfServicesAsync() { Status = "enabled" TosType = "external", Text = "By using this service, you agree to ..." }; BoxTermsOfService tos = await client.TermsOfServiceManager.CreateTermsOfServicesAsync(tosParams); ``` ## Update a Terms of Service for an Enterprise To update a terms of service call `TermsOfServiceManager.UpdateTermsOfServicesAsync(string tosId, BoxTermsOfServicesRequest termsOfServicesRequest)` method with the fields to update and their new values. ``` var updates = new BoxTermsOfServicesRequest() { Status = "disabled", Text = "Updated Text" }; BoxTermsOfService updatedToS = client.TermsOfServiceManager .UpdateTermsOfServicesAsync("11111", updates); ``` ## Get a Terms of Service By ID To get the terms of service with an ID call `TermsOfServiceManager.GetTermsOfServicesByIdAsync(string tosId)` with the ID of the terms of service object. ``` BoxTermsOfService tos = await client.TermsOfServiceManager.GetTermsOfServicesByIdAsync("11111"); ``` ## Get Terms of Service for an Enterprise To get the terms of service for an enterprise, call `TermsOfServiceManager.GetTermsOfServicesAsync(string tosType = null)`. ``` BoxTermsOfServiceCollection<BoxTermsOfService> termsOfService = await client.TermsOfServiceManager .GetTermsOfServicesAsync(); ``` ## Create User Status on Terms of Service For create user status on a terms of service call the `TermsOfServiceManager.CreateBoxTermsOfServiceUserStatusesAsync(BoxTermsOfServiceUserStatusCreateRequest termsOfServiceUserStatusCreateRequest)` You can only create a user status on a terms of service if the user has never accepted/declined a terms of service. If they have then you will need to make the update call.. ``` var createStatusRequest = new BoxTermsOfServiceUserStatusCreateRequest() { TermsOfService = new BoxRequestEntity() { Id = "11111", Type = BoxType.terms_of_service }, User = new BoxRequestEntity() { Id = "22222", Type = BoxType.user }, IsAccepted = true }; BoxTermsOfServiceUserStatuses termsOfServiceUserStatuses = await client.TermsOfServiceManager.CreateBoxTermsOfServiceUserStatusesAsync(createStatusRequest); ``` ## Update User Status on Terms of Service To update user status on a terms of service call the `TermsOfServiceManager.UpdateTermsofServiceUserStatusesAsync(string tosId, bool isAccepted)` method with the ID of the status object, and the new acceptance value for the user. It is important to note that this will accept or decline a custom terms of service for a user. For a user that has taken action in this terms of service, this will update their status. If the user has never taken action on this terms of service then this will return a 404 Not Found error. ``` BoxTermsOfServiceUserStatuses updatedStatus = await client.TermsOfServiceManager .UpdateTermsofServiceUserStatusesAsync("12345", false); ``` ## Get Terms of Service Status for User To get user status on a terms of service call the `TermsOfServiceManager.GetTermsOfServiceUserStatusesAsync(string tosId, String userId = null)` method with the ID of the terms of service. If no user ID is provided, the method defaults to the current user. ``` BoxTermsOfServiceUserStatusesCollection<BoxTermsOfServiceUserStatuses> tosStatuses = await client.TermsOfServiceManager .GetTermsOfServiceUserStatusesAsync(tosId: "11111", userId: "22222"); ``` --- ## Untitled *Type: page* Trash Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is moved to the Trash… # Trash Under normal circumstances, when an item in Box is deleted, it is not actually erased immediately. Instead, it is moved to the Trash. The Trash allows you to recover files and folders that have been deleted. By default, items in the Trash will be purged after 30 days. - [Get Trashed Items](#get-trashed-items) - [Get a Trashed File](#get-a-trashed-file) - [Get a Trashed Folder](#get-a-trashed-folder) - [Purge a File from the Trash](#purge-a-file-from-the-trash) - [Purge a Folder from the Trash](#purge-a-folder-from-the-trash) - [Restore a File From Trash](#restore-a-file-from-trash) - [Restore a Folder from Trash](#restore-a-folder-from-trash) ## Get Trashed Items To retrieve files and folders that have been moved to the Trash, call `FoldersManager.GetTrashItemsAsync(int limit, int offset = 0, IEnumerable<string> fields = null, bool autoPaginate=false)`. ``` BoxCollection<BoxItem> trashedItems = await client.FoldersManager.GetTrashItemsAsync(limit: 100); ``` ## Get a Trashed File Information about a file in the trash can be retrieved by calling the `FilesManager.GetTrashedAsync(string id, IEnumerable<string> fields = null)` method with the ID of the file in the trash. ``` BoxFile trashedFile = await client.FilesManager.GetTrashedAsync("11111"); ``` ## Get a Trashed Folder Information about a folder in the trash can be retrieved by calling the `FoldersManager.GetTrashedFolderAsync(string id, IEnumerable<string> fields = null)` method with the ID of the folder in the trash. ``` BoxFolder trashedFolder = await client.FoldersManager.GetTrashedFolderAsync("22222"); ``` ## Purge a File from the Trash Calling the `FilesManager.PurgeTrashedAsync(string id)` method will remove the file permanently from the user's trash. ``` await client.FilesManager.PurgeTrashedAsync("11111"); ``` ## Purge a Folder from the Trash Calling the `FoldersManager.PurgeTrashedFolderAsync(string id)` method will remove the folder permanently from the user's trash. ``` await client.FoldersManager.PurgeTrashedFolderAsync("22222"); ``` ## Restore a File From Trash Calling `FilesManager.RestoreTrashedAsync(BoxFileRequest fileRequest, IEnumerable<string> fields = null)` will restore an item from the user's trash. Default behavior is to restore the item to the folder it was in before it was moved to the trash. Options are available to handle possible failure cases: if an item with the same name already exists in folder's old location, the restored folder can be given an alternate name with the `Name` option. If the folder's old location no longer exists, it can be placed inside a new parent folder with the `Parent.Id` option. ``` var requestParams = new BoxFileRequest() { Name = "Name in case of conflict", Parent = new BoxRequestEntity() { // File will be placed in this folder if original location no longer exists Id = "12345" } }; BoxFile restoredFile = await client.FilesManager.RestoreTrashedAsync(requestParams); ``` ## Restore a Folder from Trash A folder can be restored from the trash with the `FoldersManager.RestoreTrashedFolderAsync(BoxFolderRequest folderRequest, IEnumerable<string> fields = null)` method. Default behavior is to restore the item to the folder it was in before it was moved to the trash. Options are available to handle possible failure cases: if an item with the same name already exists in folder's old location, the restored folder can be given an alternate name with the `Name` option. If the folder's old location no longer exists, it can be placed inside a new parent folder with the `Parent.Id` option. ``` var requestParams = new BoxFolderRequest() { Name = "Name in case of conflict", Parent = new BoxRequestEntity() { // Folder will be placed in this parent folder if original location no longer exists Id = "12345" } }; BoxFolder restoredFolder = await client.FoldersManager.RestoreTrashedFolderAsync(requestParams); ``` --- ## Untitled *Type: page* Users Users represent an individual's account on Box. Get the Current User's Information Get User's Information Get User Avatar Add or… # Users Users represent an individual's account on Box. - [Get the Current User's Information](#get-the-current-users-information) - [Get User's Information](#get-users-information) - [Get User Avatar](#get-user-avatar) - [Add or update User Avatar](#add-or-update-user-avatar) - [Delete User Avatar](#delete-user-avatar) - [Add New User](#add-new-user) - [Add New App User](#add-new-app-user) - [Update User](#update-user) - [Delete User](#delete-user) - [Get Email Aliases](#get-email-aliases) - [Add Email Alias](#add-email-alias) - [Delete Email Alias](#delete-email-alias) - [Get Enterprise Users](#get-enterprise-users) - [Transfer User Content](#transfer-user-content) ## Get the Current User's Information To get the current user call the `UsersManager.GetCurrentUserInformationAsync(IEnumerable<string> fields = null)` method. ``` BoxUser currentUser = await client.UsersManager.GetCurrentUserInformationAsync(); ``` ## Get User's Information To get a user call `UsersManager.GetUserInformationAsync(string userId)` with the ID of the user. ``` BoxUser user = await client.UsersManager.GetUserInformationAsync(userId: "33333"); ``` ## Get User Avatar To retrieve the avatar image for a user, call `UsersManager.GetUserAvatar(string userId)` with the ID of the user. ``` Stream imageStream = await client.UsersManager.GetUserAvatar(string userId); ``` ## Add or Update User Avatar To add or update user avatar call the `UsersManager.AddOrUpdateUserAvatarAsync(string userId, FileStream stream)` method with the ID of the user and and a fileStream of the avatar contents to upload. ``` using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { BoxUploadAvatarResponse response = await client.UsersManager.AddOrUpdateUserAvatarAsync(userId, fileStream); } ``` Alternatively, you can use a generic stream (e.g. MemoryStream) and provide filename explicitly. The filename should also contain file extension (.jpg or .png). ``` Stream genericStream; BoxUploadAvatarResponse response = await client.UsersManager.AddOrUpdateUserAvatarAsync(userId, genericStream, "avatar.png"); ``` ## Delete User Avatar To remove existing user avatar call the `UsersManager.DeleteUserAvatarAsync(string userId)` method with the ID of the user. ``` bool isDeleted = await client.UsersManager.DeleteUserAvatarAsync(userId); ``` ## Add New User To provision a new managed user within the current enterprise, call the `UsersManager.CreateEnterpriseUserAsync(BoxUserRequest userRequest, IEnumerable<string> fields = null)` method with the email address the user will use to log in and the user's name. ``` var userParams = new BoxUserRequest() { Name = "Example User", Login = "user@example.com" }; BoxUser newUser = await client.UsersManager.CreateEnterpriseUserAsync(userParams); ``` ## Add New App User To provision a new app user within the current enterprise, call the `UsersManager.CreateEnterpriseUserAsync(BoxUserRequest userRequest, IEnumerable<string> fields = null)` method with the `BoxUserRequest.IsPlatformAccessOnly` property set to `true`. ``` var userParams = new BoxUserRequest() { Name = "App User 12", ExternalAppUserId = "external-id", IsPlatformAccessOnly = true }; BoxUser newUser = await client.UsersManager.CreateEnterpriseUserAsync(userParams); ``` ## Update User To update a user's information, call `UsersManager.UpdateUserInformationAsync(BoxUserRequest userRequest, IEnumerable<string> fields = null)` with the fields to update. ``` var updates = new BoxUserRequest() { Id = "44444", Role = "coadmin", CanSeeManagedUsers = true }; BoxUser updatedUser = await client.UsersManager.UpdateUserInformationAsync(updates); ``` ## Delete User To delete a user call the `UsersManager.DeleteEnterpriseUserAsync(string userId, bool notify, bool force)` method. If the user still has files in their account and the `force` parameter is not sent, an error is returned. ``` await client.UsersManager.DeleteEnterpriseUserAsync("44444", notify: false, force: true); ``` ## Get Email Aliases To get a users email aliases, call `UsersManager.GetEmailAliasesAsync(string userId)` with the ID of the user. ``` BoxCollection<BoxEmailAlias> aliases = await client.UsersManager .GetEmailAliasesAsync(userId: "33333"); ``` ## Add Email Alias To add an email alias for a user, call `UsersManager.AddEmailAliasAsync(string userId, string email)` with the ID of the user and the email address to add as an alias. ``` BoxEmailAlias alias = await client.UsersManager .AddEmailAliasAsync(userId: "33333", email: "user+foo@example.com"); ``` ## Delete Email Alias To delete a users email alias, call `UsersManager.DeleteEmailAliasAsync(string userId, string emailAliasId)` with the ID of the user to whom the alias belongs and the ID of the email alias. ``` await client.UsersManager.DeleteEmailAliasAsync(userId: "33333", emailAliasId: "12345"); ``` ## Get Enterprise Users Get a list of users in the current enterprise by calling the `UsersManager.GetEnterpriseUsersAsync(string filterTerm = null, uint offset = 0, uint limit = 100, IEnumerable<string> fields = null, string userType = null, string externalAppUserId = null, bool autoPaginate = false)` method. ``` BoxCollection<BoxUser> users = await client.UsersManager.GetEnterpriseUsersAsync(); ``` ## Transfer User Content To transfer one managed user's content to another user's account, call the `MoveUserFolderAsync(string userId, string ownedByUserId, string folderId = "0", bool notify = false)` method with the IDs of the source and destination users. **Note:** Currently, only moving the user's root folder (with ID "0") is supported. ``` var sourceUserId = "33333"; var destinationUserId = "44444"; BoxFolder movedFolder = await client.MoveUserFolderAsync(sourceUserId, destinationUserId); ``` --- ## Untitled *Type: page* Watermarking Watermarking allows you to place a semi-transparent overlay on an embedded file preview that displays a viewer's email address… # Watermarking Watermarking allows you to place a semi-transparent overlay on an embedded file preview that displays a viewer's email address or user ID and the time of access over a file's content. Once a watermark is applied to a file or folder via the API, the watermark will be displayed on any file preview. - [Get Watermark on a File](#get-watermark-on-a-file) - [Apply Watermark to a File](#apply-watermark-to-a-file) - [Remove Watermark from a File](#remove-watermark-from-a-file) - [Get Watermark on a Folder](#get-watermark-on-a-folder) - [Apply Watermark to a Folder](#apply-watermark-to-a-folder) - [Remove Watermark from a Folder](#remove-watermark-from-a-folder) ## Get Watermark on a File To get watermark information for a file call the `FilesManager.GetWatermarkAsync(string id)` method with the ID of the file. ``` BoxWatermark watermark = await client.FilesManager.GetWatermarkAsync("11111"); ``` ## Apply Watermark to a File To apply or update the watermark to a file call the `FilesManager.ApplyWatermarkAsync(string id, BoxApplyWatermarkRequest applyWatermarkRequest = null)` method with the ID of the file. ``` BoxWatermark watermark = await client.FilesManager.ApplyWatermarkAsync("11111"); ``` ## Remove Watermark from a File A file's watermark can be removed by calling `FilesManager.RemoveWatermarkAsync(string id)` with the ID of the watermarked file. ``` await client.FilesManager.RemoveWatermarkAsync("11111"); ``` ## Get Watermark on a Folder To get watermark information for a folder call the `FoldersManager.GetWatermarkAsync(string id)` method with the ID of the folder. ``` BoxWatermark watermark = await client.FoldersManager.GetWatermarkAsync("22222"); ``` ## Apply Watermark to a Folder To apply or update the watermark for a folder call the `FoldersManager.ApplyWatermarkAsync(string id, BoxApplyWatermarkRequest applyWatermarkRequest = null)` method with the ID of the folder. ``` BoxWatermark watermark = await client.FoldersManager.ApplyWatermarkAsync("22222"); ``` ## Remove Watermark from a Folder A folder's watermark can be removed by calling `FoldersManager.RemoveWatermarkAsync(string id)` with the ID of the watermarked folder. ``` await client.FoldersManager.RemoveWatermarkAsync("22222"); ``` --- ## Untitled *Type: page* Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link… # Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects, so they will also support shared links, copy, permanent delete, and restore. - [Create a Web Link](#create-a-web-link) - [Get a Web Link's information](#get-a-web-links-information) - [Update a Web Link](#update-a-web-link) - [Delete a Web Link](#delete-a-web-link) - [Copy a Web Link](#copy-a-web-link) - [Create or update a Shared Link](#create-or-update-a-shared-link) - [Remove a Shared Link](#remove-a-shared-link) ## Create a Web Link To create a web link call `WebLinksManager.CreateWebLinkAsync(BoxWebLinkRequest createWebLinkRequest)`. ``` var weblinkParams = new BoxWebLinkRequest() { Url = new Uri("http://www.example.com"), Parent = new BoxRequestEntity() { Id = "22222" } }; BoxWebLink link = await client.WebLinksManager.CreateWebLinkAsync(weblinkParams); ``` ## Get a Web Link's information You can request a web link object by ID by calling `WebLinksManager.GetWebLinkAsync(string webLinkId)` with the ID of the web link object. ``` BoxWebLink link = await client.WebLinksManager.GetWebLinkAsync("11111"); ``` ## Update a Web Link To update a web link call the `WebLinksManager.UpdateWebLinkAsync(string webLinkId, BoxWebLinkRequest updateWebLinkRequest)` method with the fields to update and their new values. ``` var updates = new BoxWebLinkRequest() { Name = "New Name for Weblink" }; BoxWebLink updatedLink = await client.WebLinksManager.UpdateWebLinkAsync("11111", updates); ``` ## Delete a Web Link To move a web link to the trash call `WebLinksManager.DeleteWebLinkAsync(string webLinkId)` with the ID of the web link object to delete. ``` await client.WebLinksManager.DeleteWebLinkAsync("11111"); ``` ## Copy a Web Link To make a copy of a web link, call `WebLinksManager.CopyAsync(string webLinkId, string destinationFolderId, IEnumerable<string> fields = null)` with the ID of the web link and the ID of the folder into which it should be copied. ``` BoxWebLink copiedLink = await client.WebLinksManager.CopyAsync("11111", "22222"); ``` ## Create or update a Shared Link A shared link for a web link can be created or updated by calling `WebLinksManager.CreateSharedLinkAsync(string id, BoxSharedLinkRequest sharedLinkRequest, IEnumerable<string> fields = null)`. ``` string webLinkId = "11111"; var sharedLinkParams = new BoxSharedLinkRequest() { Access = BoxSharedLinkAccessType.open }; BoxWebLink link = client.WebLinksManager .CreateSharedLinkAsync(webLinkId, sharedLinkParams); string sharedLinkUrl = link.SharedLink.Url; ``` ## Remove a Shared Link To remove a shared link from a web link, call `WebLinksManager.DeleteSharedLinkAsync(string id, IEnumerable<string> fields = null)` with the ID of the web link. ``` BoxWebLink updatedLink = client.WebLinksManager.DeleteSharedLinkAsync("11111"); ``` --- ## Untitled *Type: page* Webhooks A webhook object enables you to attach events triggers to Box files and folders. These event triggers monitor events on Box objects… # Webhooks A webhook object enables you to attach events triggers to Box files and folders. These event triggers monitor events on Box objects and notify your application, via HTTP requests to a URL of your choosing, when they occur. - [Create a Webhook](#create-a-webhook) - [Get All Webhooks](#get-all-webhooks) - [Get a Webhook"s Information](#get-a-webhooks-information) - [Validate a Webhook Message](#validate-a-webhook-message) - [Delete a Webhook](#delete-a-webhook) - [Update a Webhook](#update-a-webhook) ## Create a Webhook To attach a webhook to an item, call the `WebhooksManager.CreateWebhookAsync(BoxWebhookRequest webhookRequest)` method with the type and ID of the item, a URL to send notifications to, and a list of triggers. ``` var webhookParams = new BoxWebhookRequest() { Target = new BoxRequestEntity() { Type = BoxType.file, Id = "22222" }, Triggers = new List<string>() { "FILE.PREVIEWED" }, Address = "https://example.com/webhook" }; BoxWebhook webhook = await client.WebhooksManager.CreateWebhookAsync(webhookParams); ``` Similarly, webhooks can be created for folders. ``` var webhookParams = new BoxWebhookRequest() { Target = new BoxRequestEntity() { Type = BoxType.folder, Id = "22222" }, Triggers = new List<string>() { "FILE.UPLOADED", "FILE.DOWNLOADED" }, Address = "https://example.com/webhook }; BoxWebhook webhook = await client.WebhooksManager.CreateWebhookAsync(webhookParams); ``` ## Get All Webhooks Get a list of all webhooks for the requesting application and user by calling the `WebhooksManager.GetWebhooksAsync (int limit = 100, string nextMarker = null, bool autoPaginate=false)` method. The maximum limit per page of results is 200, Box uses the default limit of 100. ``` BoxCollectionMarkerBased<BoxWebhook> webhooks = await client.WebhooksManager.GetWebhooksAsync(); ``` ## Get a Webhook"s Information Retrieve information about a specific webhook by calling `WebhooksManager.GetWebhookAsync(string id)` to retrieve a webhook by ID. ``` BoxWebhook webhook = await client.WebhooksManager.GetWebhookAsync("12345"); ``` ## Validate a Webhook Message When you receive a webhook message from Box, you should validate it by calling the static `WebhooksManager.VerifyWebhook(string deliveryTimestamp, string signaturePrimary, string signatureSecondary, string payload, string primaryWebhookKey, string secondaryWebhookKey)` method with the components of the webhook message. ``` using Box.V2.Managers; var body = "{\"type\":\"webhook_event\",\"webhook\":{\"id\":\"1234567890\"},\"trigger\":\"FILE.UPLOADED\",\"source\":{\"id\":\"1234567890\",\"type\":\"file\",\"name\":\"Test.txt\"}}"; var headers = new Dictionary<string, string>() { { "box-delivery-id", "f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f" }, { "box-delivery-timestamp", "2020-01-01T00:00:00-07:00" }, { "box-signature-algorithm", "HmacSHA256" } , { "box-signature-primary", "6TfeAW3A1PASkgboxxA5yqHNKOwFyMWuEXny/FPD5hI=" }, { "box-signature-secondary", "v+1CD1Jdo3muIcbpv5lxxgPglOqMfsNHPV899xWYydo=" }, { "box-signature-version", "1" } }; var primaryKey = "Fd28OJrZ8oNxkgmS7TbjXNgrG8v"; var secondaryKey = "KWkROAOiof4zhYUHbAmiVn63cMj" bool isValid = BoxWebhooksManager.VerifyWebhook( deliveryTimestamp: headers["box-delivery-timestamp"], signaturePrimary: headers["box-signature-primary"], signatureSecondary: headers["box-signature-secondary"], payload: body, primaryWebhookKey: primaryKey, secondaryWebhookKey: secondaryKey ); ``` ## Delete a Webhook A file or folder's webhook can be removed by calling `WebhooksManager.DeleteWebhookAsync(string id)` with the ID of the webhook object. ``` await client.WebhooksManager.DeleteWebhookAsync("11111"); ``` ## Update a Webhook Update a file or folder's webhook by calling `WebhooksManager.UpdateWebhookAsync(BoxWebhookRequest webhookRequest)` with the fields of the webhook object to update. ``` var updates = new BoxWebhookRequest() { Id = "12345", Address = "https://example.com/webhooks/fileActions }; BoxWebhook updatedWebhook = await client.WebhooksManager.UpdateWebhookAsync(updates); ``` --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 5.8.0 (2024-07-2… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## 5.8.0 (2024-07-22) ### New Features and Enhancements: - add support for AI ([#965](https://github.com/box/box-windows-sdk-v2/issues/965)) ([a9e130a](https://github.com/box/box-windows-sdk-v2/commit/a9e130a99cf9862f9b50178a6188b2820f9f2c32)) ### Bug Fixes: - Bump `System.IdentityModel.Tokens.Jwt` dependency version to `v6.35.0` ([#962](https://github.com/box/box-windows-sdk-v2/issues/962)) ([6e47237](https://github.com/box/box-windows-sdk-v2/commit/6e472378e2fccea2db67bf5ef0eb017a31491703)), closes [#960](https://github.com/box/box-windows-sdk-v2/issues/960) [#961](https://github.com/box/box-windows-sdk-v2/issues/961) - remove `Microsoft.AspNetCore.StaticFiles` and `System.Web` dependencies ([#964](https://github.com/box/box-windows-sdk-v2/issues/964)) ([2c8eedc](https://github.com/box/box-windows-sdk-v2/commit/2c8eedc91c473aca52249aad443345471ca7eafc)) ### 5.7.1 (2024-06-28) ### Bug Fixes: - Add missing enum values to `BoxSortBy` ([#953](https://github.com/box/box-windows-sdk-v2/issues/953)) ([1f89bb0](https://github.com/box/box-windows-sdk-v2/commit/1f89bb047442dcdc9045aeff1c3d6aadf61e2856)), closes [#952](https://github.com/box/box-windows-sdk-v2/issues/952) - Add missing fields of `EventSource` ([#956](https://github.com/box/box-windows-sdk-v2/issues/956)) ([138eda5](https://github.com/box/box-windows-sdk-v2/commit/138eda516ad59f08968d88b04e9bb06df3c397f2)) - do not recreate Random each time ([#945](https://github.com/box/box-windows-sdk-v2/issues/945)) ([d03b1ce](https://github.com/box/box-windows-sdk-v2/commit/d03b1ce65d4077e2895acfce3bc286ea501669aa)), closes [#944](https://github.com/box/box-windows-sdk-v2/issues/944) [#944](https://github.com/box/box-windows-sdk-v2/issues/944) [#944](https://github.com/box/box-windows-sdk-v2/issues/944) [#944](https://github.com/box/box-windows-sdk-v2/issues/944) ## 5.7.0 (2024-02-27) ### New Features and Enhancements: - add marker-based pagination version of `GetFolderItems` ([#936](https://github.com/box/box-windows-sdk-v2/issues/936)) ([f877a8f](https://github.com/box/box-windows-sdk-v2/commit/f877a8f9105d65a3e3ca459fcbf4a1bb653ff0f3)) - Support sign request signer group ID ([#938](https://github.com/box/box-windows-sdk-v2/issues/938)) ([096a098](https://github.com/box/box-windows-sdk-v2/commit/096a09805b189c591289e77ae5f8a8e6f1b466f1)) ### Bug Fixes: - Remove delete classification ([#932](https://github.com/box/box-windows-sdk-v2/issues/932)) ([fb59489](https://github.com/box/box-windows-sdk-v2/commit/fb594897850ad9daacf75cab702f3765cc7168c0)) ### 5.6.1 (2023-11-29) ### Bug Fixes: - support object value in `BoxConflictErrorContextInfo` ([#930](https://github.com/box/box-windows-sdk-v2/issues/930)) ([496f758](https://github.com/box/box-windows-sdk-v2/commit/496f758c3436b1834188078027b7305ca6a98fce)) ## 5.6.0 (2023-09-25) ### New Features and Enhancements: - Support `iframeable_embed_url` for sign request ([#925](https://github.com/box/box-windows-sdk-v2/issues/925)) ([e9de994](https://github.com/box/box-windows-sdk-v2/commit/e9de994cea97afcc1c3bc52ddf1cc023b9ee731c)) ## 5.5.0 (2023-09-20) ### New Features and Enhancements: - Add shared link header support in file and folder managers ([#923](https://github.com/box/box-windows-sdk-v2/issues/923)) ([ffbfc72](https://github.com/box/box-windows-sdk-v2/commit/ffbfc72289c70cdd91ea500326944a40b89993e3)) ## 5.4.0 (2023-09-07) ### New Features and Enhancements: - Support Sign Templates and new Sign Request statuses ([#920](https://github.com/box/box-windows-sdk-v2/issues/920)) ([78580fb](https://github.com/box/box-windows-sdk-v2/commit/78580fbd3de553273970376b96bc28c7c5614a97)) ## 5.3.0 (2023-09-04) ### New Features and Enhancements: - add `attachment` content type to `SignRequestSigner` ([#913](https://github.com/box/box-windows-sdk-v2/issues/913)) ([ad612ff](https://github.com/box/box-windows-sdk-v2/commit/ad612ffc7821a9ecbc180e3dbeefe16d3e397820)) ### Bug Fixes: - replace deprecated `BouncyCastle` library ([#909](https://github.com/box/box-windows-sdk-v2/issues/909)) ([f00f2af](https://github.com/box/box-windows-sdk-v2/commit/f00f2af9c5277b42e6a62060c1b0229ecff0203e)) ### 5.2.2 (2023-05-23) ### Bug Fixes: - catch exception when .net core version cannot be determined ([#906](https://github.com/box/box-windows-sdk-v2/issues/906)) ([e3be209](https://github.com/box/box-windows-sdk-v2/commit/e3be209b20a5c323f547d7634663883613959180)) ### 5.2.1 (2023-04-18) ### Bug Fixes: - Catch all exceptions when getting User Agent header ([#901](https://github.com/box/box-windows-sdk-v2/issues/901)) ([75d8874](https://github.com/box/box-windows-sdk-v2/commit/75d887470698a5f312610cebd58be58aee7eaa9b)) ## 5.2.0 (2023-03-14) ### New Features and Enhancements: - add `Id` to `MetadataTemplateField` ([#890](https://github.com/box/box-windows-sdk-v2/issues/890)) ([b7fe214](https://github.com/box/box-windows-sdk-v2/commit/b7fe2149e1a0ade8573b497b7bb36e9f3c4f4a82)) - add `start_date_field` and `description` to retention policies ([#888](https://github.com/box/box-windows-sdk-v2/issues/888)) ([100b722](https://github.com/box/box-windows-sdk-v2/commit/100b722ce4909395c00b527677564f37a61ec2cb)) - add configurable `JWTAudience` claim ([#897](https://github.com/box/box-windows-sdk-v2/issues/897)) ([50219fd](https://github.com/box/box-windows-sdk-v2/commit/50219fdfd553d6335b6f0b4341719b09680c4ba0)) - add shared link support to `GetFolderItemsAsync` ([#892](https://github.com/box/box-windows-sdk-v2/issues/892)) ([0eba85c](https://github.com/box/box-windows-sdk-v2/commit/0eba85c693763472c51fe81cbc43222305e9eefb)) ### Bug Fixes: - Use fixed value of `aud` field in `JWT` claim ([#896](https://github.com/box/box-windows-sdk-v2/issues/896)) ([8c9982d](https://github.com/box/box-windows-sdk-v2/commit/8c9982d160ec4806c796ee2621b1811232ea59c1)) ## 5.1.0 (2023-01-17) ### New Features and Enhancements: - `BoxCCGAuth` add User and Admin clients factory methods without initial token ([#883](https://github.com/box/box-windows-sdk-v2/issues/883)) ([c1337fc](https://github.com/box/box-windows-sdk-v2/commit/c1337fc9d765bf7d4bc1757ea832bec92a602f76)) ## 5.0.0 (2023-01-12) ### ⚠ BREAKING CHANGES - upgrade .net framework to 4.6.2 (#881) - remove deprecated methods (#881) - remove `use_index` references (#881) - return proper object from `GetFileVersionsUnderRetentionForAssignmentAsync`(#881) ### New Features and Enhancements: - upgrade .net framework to 4.6.2 ([#881](https://github.com/box/box-windows-sdk-v2/issues/881)) ([f1989aa](https://github.com/box/box-windows-sdk-v2/commit/f1989aa94cd085ad4bec04b4ebedb04f40455569)), closes [#863](https://github.com/box/box-windows-sdk-v2/issues/863) - remove deprecated methods ([#881](https://github.com/box/box-windows-sdk-v2/issues/881)) ([f1989aa](https://github.com/box/box-windows-sdk-v2/commit/f1989aa94cd085ad4bec04b4ebedb04f40455569)), closes [#874](https://github.com/box/box-windows-sdk-v2/issues/874) - remove `use_index` references ([#881](https://github.com/box/box-windows-sdk-v2/issues/881)) ([f1989aa](https://github.com/box/box-windows-sdk-v2/commit/f1989aa94cd085ad4bec04b4ebedb04f40455569)), closes [#870](https://github.com/box/box-windows-sdk-v2/issues/870) ### Bug Fixes: - Added pagination option to `IBoxFilesManager#ViewVersionsAsync` ([#869](https://github.com/box/box-windows-sdk-v2/issues/869)) ([2324495](https://github.com/box/box-windows-sdk-v2/commit/232449531440227a0c8b3489ceda813fe4f4a73f)), closes [#866](https://github.com/box/box-windows-sdk-v2/issues/866) - return proper object from `GetFileVersionsUnderRetentionForAssignmentAsync` ([#881](https://github.com/box/box-windows-sdk-v2/issues/881)) ([f1989aa](https://github.com/box/box-windows-sdk-v2/commit/f1989aa94cd085ad4bec04b4ebedb04f40455569)), closes [#875](https://github.com/box/box-windows-sdk-v2/issues/875) ## 4.6.0 (2022-10-18) ### New Features and Enhancements: - Add `redirect_url` and `declined_redirect_url` to Sign Request ([#853](https://github.com/box/box-windows-sdk-v2/issues/853)) ([5ef2f18](https://github.com/box/box-windows-sdk-v2/commit/5ef2f18985d8c3b8e7c0cdba5709785bfb1d5f34)) - Add support for modifiable retention policies & enable deleting retention policy assignment ([#856](https://github.com/box/box-windows-sdk-v2/issues/856)) ([564904f](https://github.com/box/box-windows-sdk-v2/commit/564904fa2ce0b1881a2f07b80cc3bb3e648310d0)) ## 4.5.0 (2022-08-24) ### New Features and Enhancements: - Add `content-type` field to sign request ([#850](https://github.com/box/box-windows-sdk-v2/issues/850)) ([054d3e1](https://github.com/box/box-windows-sdk-v2/commit/054d3e1a5f44b6a4a0292e8f9444266b2de0fff0)) - expose `effective_access` in `BoxSharedLink` [#843](https://github.com/box/box-windows-sdk-v2/issues/843) ([d84ddd4](https://github.com/box/box-windows-sdk-v2/commit/d84ddd48aac489ecdd1d9dc740a7672cb064b0ca)) ### Bug Fixes: - fix null reference exception when it's not possible to get `runtime` version from the assembly ([#851](https://github.com/box/box-windows-sdk-v2/issues/851)) ([77046fb](https://github.com/box/box-windows-sdk-v2/commit/77046fb0c1ce80b6e7e2dc30058ed275e46e990c)) - replace infinite retries with exponential backoff strategy in file representations ([#835](https://github.com/box/box-windows-sdk-v2/issues/835)) ([f2a5713](https://github.com/box/box-windows-sdk-v2/commit/f2a57136078de8b1fc59ec2c4a9e98c062d9d19b)) ## 4.4.0 (2022-06-14) ### New Features and Enhancements: - add `can_edit` field to `SharedLink` ([#831](https://github.com/box/box-windows-sdk-v2/issues/831)) ([e0d4197](https://github.com/box/box-windows-sdk-v2/commit/e0d4197070db0dbd947f4a51a6bbb1e01c0b0cdf)) - add `version_number` to `BoxFileVersion` ([#820](https://github.com/box/box-windows-sdk-v2/issues/820)) ([f174358](https://github.com/box/box-windows-sdk-v2/commit/f174358973caefc9262df480208341fd8233dc7f)) - add upload and delete support for Avatar API ([#829](https://github.com/box/box-windows-sdk-v2/issues/829)) ([4dcb84a](https://github.com/box/box-windows-sdk-v2/commit/4dcb84ade78d6bd0bc621ff2ed7f5f886486858a)) ### Bug Fixes: - Fix initialization of `BoxAPIException` object ([#828](https://github.com/box/box-windows-sdk-v2/issues/828)) ([a298f01](https://github.com/box/box-windows-sdk-v2/commit/a298f01187f84200825ec6ed4748fe8bbd717d11)) - properly dispose response on exception ([#819](https://github.com/box/box-windows-sdk-v2/issues/819)) ([8415bd3](https://github.com/box/box-windows-sdk-v2/commit/8415bd3dbe42910b99f99535247a26f8d8e645c1)) ### 4.3.1 (2022-04-19) ### Bug Fixes: - simplify base `urls` usage ([#815](https://github.com/box/box-windows-sdk-v2/issues/815)) ([f8e7344](https://github.com/box/box-windows-sdk-v2/commit/f8e73447afa5c0a893c3c4ace922fc360a376f66)) ## 4.3.0 (2022-04-01) ### New Features and Enhancements: - add `SourceLink` support for Core project ([#795](https://github.com/box/box-windows-sdk-v2/issues/795)) ([a9cbede](https://github.com/box/box-windows-sdk-v2/commit/a9cbedece2ffb4f832be880bebf35b715c9cb28b)) ### Bug Fixes: - add missing enum to string parsing in several places ([#813](https://github.com/box/box-windows-sdk-v2/issues/813)) ([e370282](https://github.com/box/box-windows-sdk-v2/commit/e3702826216132dfe1fb061af95a8d9700f114d4)) - properly cast response when uploading a new file version using session ([#810](https://github.com/box/box-windows-sdk-v2/issues/810)) ([73d877f](https://github.com/box/box-windows-sdk-v2/commit/73d877ff679b5999ea50cdfa68f14b0e2169ea65)) ## 4.2.0 (2022-02-10) ### Bug Fixes: - correctly pass null when rolling out user from the enterprise ([#792](https://github.com/box/box-windows-sdk-v2/issues/792)) ([c85c573](https://github.com/box/box-windows-sdk-v2/commit/c85c5735865b7dd97ffa1428a8f57d2edff6811b)) - Creating BoxAuthenticationFailedException no longer throws an exception ([#790](https://github.com/box/box-windows-sdk-v2/issues/790)) ([55a706e](https://github.com/box/box-windows-sdk-v2/commit/55a706e4091271aa55208a260b2f4f96e1527698)) - Null Argument Exception in AutoPaginate ([#666](https://github.com/box/box-windows-sdk-v2/issues/666)) ([c61f08c](https://github.com/box/box-windows-sdk-v2/commit/c61f08cc02d5c95ff71ef700e97393a0dc3dc890)) ### New Features and Enhancements: - add admin_logs_streaming support ([#797](https://github.com/box/box-windows-sdk-v2/issues/797)) ([a775e1e](https://github.com/box/box-windows-sdk-v2/commit/a775e1e5c7696a1e5f82b5dc7edbed8eb09f640d)) - add Client Credentials Grant auth support ([#799](https://github.com/box/box-windows-sdk-v2/issues/799)) ([b8a64ca](https://github.com/box/box-windows-sdk-v2/commit/b8a64ca3887298feccef5185f6bfec4c3771b5a9)) - add disposition_at field to the File object ([#793](https://github.com/box/box-windows-sdk-v2/issues/793)) ([2766a91](https://github.com/box/box-windows-sdk-v2/commit/2766a914fad1eb40371cd4430b3450360088b331)) - add possibility to set auth token uri in BoxConfig ([#794](https://github.com/box/box-windows-sdk-v2/issues/794)) ([ae8cd8b](https://github.com/box/box-windows-sdk-v2/commit/ae8cd8b91dd91b8a786e53ff5b3501d2700686a4)) - deprecate index_name in ExecuteMetadataQuery ([#800](https://github.com/box/box-windows-sdk-v2/issues/800)) ([6a6a0e4](https://github.com/box/box-windows-sdk-v2/commit/6a6a0e4a0e41ec70ec33acacba00bee6c7ee881f)) ## 4.1.0 (2021-12-14) ### Bug Fixes: - add missing configureAwait(false) when awaiting to prevent deadlocks ([#775](https://github.com/box/box-windows-sdk-v2/issues/775)) ([b16267e](https://github.com/box/box-windows-sdk-v2/commit/b16267e8f3dca5396e87be660e30a1e9405d8139)) ### New Features and Enhancements: - add configurable Timeout for BoxClient ([#779](https://github.com/box/box-windows-sdk-v2/issues/779)) ([ac842ed](https://github.com/box/box-windows-sdk-v2/commit/ac842ed4ba1a2dfe499706524441bc6ae3b3c192)) - add file request api ([#777](https://github.com/box/box-windows-sdk-v2/issues/777)) ([1098f75](https://github.com/box/box-windows-sdk-v2/commit/1098f75983e2d784521f13b8d53df0e55d03203b)) - add vanity_name to SharedLink ([#782](https://github.com/box/box-windows-sdk-v2/issues/782)) ([00a1e26](https://github.com/box/box-windows-sdk-v2/commit/00a1e265569d76c2c9593aa259202d7febef629c)) ## 4.0.0 (2021-11-02) ### Breaking changes: - Extract interfaces for BoxClient and Managers to improve testability ([#603](https://github.com/box/box-windows-sdk-v2/pull/603)) - Add BoxConfigBuilder and make BoxConfig immutable ([#737](https://github.com/box/box-windows-sdk-v2/pull/737)) - Expose tasks from async methods ([#742](https://github.com/box/box-windows-sdk-v2/pull/742)) - Use DateTimeOffset instead of DateTime ([#749](https://github.com/box/box-windows-sdk-v2/pull/749)) - Rework returned exceptions ([#753](https://github.com/box/box-windows-sdk-v2/pull/753)) - Upgrade .NET Standard to 2.0 ([#755](https://github.com/box/box-windows-sdk-v2/pull/755)) ### New Features and Enhancements: - Add ability to get files under retention for assignment and file versions under retention for assignment ([#734](https://github.com/box/box-windows-sdk-v2/pull/734)) - Add `is_collaboration_restricted_to_enterprise` flag support for `Folder` update ([#732](https://github.com/box/box-windows-sdk-v2/pull/732)) - Replace insensitive language ([#738](https://github.com/box/box-windows-sdk-v2/pull/738)) - Add new, easier to use method for create terms of service user status ([#740](https://github.com/box/box-windows-sdk-v2/pull/740)) - Allow sort and direction parameter to be passed in when getting trashed items ([#754](https://github.com/box/box-windows-sdk-v2/pull/754)) - Add support for Task completion_rule field ([#758](https://github.com/box/box-windows-sdk-v2/pull/758)) - Add BoxSign API support ([#765](https://github.com/box/box-windows-sdk-v2/pull/765)) ### Bug Fixes: - Fix `Cannot access a closed Stream.Request` exception during upload ([#739](https://github.com/box/box-windows-sdk-v2/pull/739)) ([#757](https://github.com/box/box-windows-sdk-v2/pull/757)) ## 3.26.0 [2021-04-01] **New Features and Enhancements:** - Add filter fields to get file version retentions ([#717](https://github.com/box/box-windows-sdk-v2/pull/717)) - Add support for search param to get shared link items ([#721](https://github.com/box/box-windows-sdk-v2/pull/721)) - Add folder lock functionality ([#725](https://github.com/box/box-windows-sdk-v2/pull/725)) ## 3.25.0 [2020-10-19] **New Features and Enhancements:** - Add support for filtering when getting Groups (#703) - Add zip functionality (#700) - Deprecate one of the overloaded `ExecuteMetadataQueryAsync()` methods (#699) - Add support for `copyInstanceOnItemCopy` field for metadata templates (#698) **Bug Fixes:** - Fix bug with JWT Authentication automatic retry (#697) ## 3.24.0 [2020-07-21] - Add path parameter sanitization - Add support for the classification field for Files and Folders - Fix bug with notification email field deserializing for `BoxUser` - Add `fields` parameter for metadata query - Add ability to set a request timeout for `FoldersManager.UpdateInformationAsync()` and `UsersManager.MoverUserFolderAsync()` ## 3.23.0 [2020-05-12] - Add ability to get and set a notification email address for a user - Fix deadlock issue for JWT authentication in UI elements - Add support for the uploader display name field for Files and File Versions ## 3.22.0 [2020-02-25] - Fixed Authentication Request Retries - Added the ability to query Box items based on their metadata. The method to do so is `MetadataManager.ExecuteMetadataQueryAsync()`. - Added `TrashedAt` field to `BoxItem` objects (file, folder, weblink). - Added marker based pagination for get users methods - Updated retry logic to retry on 503 status codes returned by the API - Provide better details for debugging, if the HttpClient used to make API requests times out ## 3.21.0 [2019-12-05] - Added `fields` parameter to `UsersManager.GetUserInformationAsync()` - Added `ExternalAppUserId` property to `BoxUser` model - Added the ability to set the `TrackingCodes` property when updating or creating a user (thanks @Cpcrook!) ## 3.20.0 [2019-09-19] - Added missing fields for File Version object. ## 3.19.0 [2019-08-29] - Added `FILE_VERSION_RESTORE` constant to Admin Event. - Added action_by field to Enterprise Event. - Audited missing fields on BoxFile and BoxFolder objects. - Better error handling and messaging for errors pertaining to OAuth2 error responses. ## 3.18.0 [2019-06-20] Added `sort` and `direction` parameters to `FoldersManager.GetFolderItemsAsync()` to enable sorting the folder items returned - Added a new `SearchManager.QueryAsync()` method with correct types for file size filter parameters - Deprecated the `SearchManager.SearchAsync()` method, which is superseded by `SearchManager.QueryAsync()` - Added support for setting the `IsExternalCollabRestricted` parameter when creating and updating Users Added a `WebProxy` property to `BoxConfig` instances, which can be used to manually set the network proxy used by the SDK ## 3.17.0 [2019-05-09] - Fixed the encoding of dates in the query parameters for Events and Search endpoints - Deprecated `FilesManager.DownloadStreamAsync()` and introduced a replacement method with correct parameter types for byte offsets: `FilesManager.DownloadAsync()` ## 3.16.0 [2019-04-29] - Added `sort` and `direction` parameters to `client.SearchManager.SearchAsync()` to control sort order - Added `extension` parameter to `client.FilesManager.GetThumbnailAsync()` to control which thumbnail format is returned (thanks @guilmori!) - Fixed a bug where query string parameters were not correctly encoded Added `SetFileMetadataAsync()` and `SetFolderMetadataAsync()` methods to `client.MetadataManager` to set metadata keys and values, overwriting existing values for the provided keys. - Automatically retry most API calls when the API responds with a transient error status code ## 3.15.0 [2019-03-28] - Added support for passing custom IBoxService to BoxJWTAuth constructor. ## 3.14.1 [2019-03-07] - Removed unnecessary package.config from sample files. ## 3.14.0 [2019-02-28] - Added trace ID to API response exception message. - Fix deserialization of translated task assignment status. ## 3.13.1 [2019-02-21] - Fixed an issue where some objects related to Events did not have their `.Id` property correctly deserialized from JSON ## 3.13.0 [2019-02-14] Added the `.InviteEmail` property to `BoxCollaboration` objects, which displays the email address for the invited user in a pending collaboration - Added `.Timezone`, `.IsExternalCollabRestricted`, `.Tags`, and `.Hostname` properties to `BoxUser` objects ## 3.12.0 [2019-02-07] Added `client.FilesManager.GetCollaborationsCollectionAsync()` and deprecated `client.FilesManager.GetCollaborationsAsync()` to enable paging through the entire collection of collaborations on a file Added `client.WebLinksManager.CopyAsync()`, `client.WebLinksManager.CreateSharedLinkAsync()`, and `client.WebLinksManager.DeleteSharedLinkAsync()` - Added `client.UsersManager.GetUserAvatarAsync()` for retrieving a user's avatar image ## 3.11.0 [2019-01-17] - Added support for reading and writing more Group fields - Fixed an issue where the `UnsharedAt` field of a shared link could not be set to `null` - Fixed renaming a file on new version upload - Added the ability to set the content modification timestamp on file version upload - Fixed issues around reading the source of an event when the source item is a web link ## 3.10.0 [2018-12-14] - Added support for Metadata Cascade Policies ## 3.9.3 [2018-09-04] - Strong named the assembly. ## 3.9.2 [2018-06-14] - Added support for [setting flag](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Models/Request/BoxFolderRequest.cs#L39) allowing non owners of a folder to invite collaborators. ## 3.9.1 [2018-06-07] - Fixed bug where Xamarin applications would run out of connections ## 3.9.0 [2018-05-10] - Added support for Storage Policies ## 3.8.0 [2018-04-30] - Fixed an issue where users could not create `BoxClient` on Xamarin - Added `File` property to `BoxLock` objects in events - Added `MetadataManager.DeleteMetadataTemplate(string scope, string template)` for deleting a Metadata template - Made API URLs modifiable in `BoxConfig` - Improved API response error objects/messages ## 3.7.0 [2018-04-10] - Added support for assigning a Retention Policy to a metadata template - Added `CONTENT_ACCESS` event type to enum ## 3.6.0 [2018-03-27] - Fixed an issue where a "Security protocol not supported" exception could be thrown on MacOS - Added `client.FilesManager.GetRepresentationContentAsync()` for fetching a stream over representation contents - Fixed parsing of some `Source` objects on `BoxEvent` objects ## 3.5.2 [2018-03-21] - Switched to exponential backoff when the SDK receives a rate limit or server error response. - Force support for TLSv1.1 or higher when available to improve the security of connections to the Box API. - Perform modified retry on JWT auth for when the local clock and the Box Server clock are not aligned as well as if the JWT ID has already been consumed. - Made `name` parameter optional on `RestoreTrashedAsync()`. ## 3.4.2 [2018-01-31] - Deprecated `uploadFileVersionUsingSessionAsync()`(which returned just a Box File Version) in favor of `uploadNewVersionUsingSessionAsync()`(which returns the entire Box File object containing the Box File Version). - Added support for OAuth2 access token creation type to the AdminEventTypesEnum - Added `ExpiresAt` param to `BoxCollaborationRequest`. ## 3.4.1 [2018-01-09] - Added support for [Collaboration Whitelist](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Managers/BoxCollaborationWhitelistManager.cs) endpoint - Added [Event Types Enum](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Config/Constants.cs#L287) - Fixed deserialization issue with BoxRepresentationStatus (#429) ## 3.3.0 [2017-11-22] - Added support for [Terms of Service](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Managers/BoxTermsOfServiceManager.cs) endpoint - Added support for [Metadata Template ID](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Managers/BoxMetadataManager.cs#L175) endpoint - Added missing fields for Folder Model (#414) ## 3.2.0 [2017-10-04] - Added support for [Representations](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Managers/BoxFilesManager.cs#L1216) endpoint - Added support for [Chunked Upload New File Version](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Managers/BoxFilesManager.cs#L423) - Fixed BoxEventsManager DateTime formatter (#400) ## 3.1.0 [2017-08-18] - Added Unified Metadata Support (#379) ## 3.0.0 [2017-07-28] - Major version bump to 3, targeting net45 - Upgrading the whole sln to vs2017 - Added support for [Recents](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Managers/BoxRecentItemsManager.cs#L1) endpoint - New operation on [Metadata](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Managers/BoxMetadataManager.cs#L1) endpoint - Progress on [Chunked Upload New File](https://github.com/box/box-windows-sdk-v2/blob/main/Box.V2/Managers/BoxFilesManager.cs#L463) - Minor bug fixes --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - if you want to contribute code. Please be sure to file an issue first. ## Pull request best practices We want to accept your pull requests. Please follow these steps: ### Step 1: File an issue Before writing any code, please file an issue stating the problem you want to solve or the feature you want to implement. This allows us to give you feedback before you spend any time writing code. There may be a known limitation that can't be addressed, or a bug that has already been fixed in a different way. The issue allows us to communicate and figure out if it's worth your time to write a bunch of code for the project. ### Step 2: Fork this repository in GitHub This will create your own copy of our repository. ### Step 3: Add the upstream source The upstream source is the project under the Box organization on GitHub. To add an upstream source for this project, type: ``` git remote add upstream git@github.com:box/box-windows-sdk-v2.git ``` This will come in useful later. ### Step 4: Create a feature branch Create a branch with a descriptive name, such as `add-search`. ### Step 5: Push your feature branch to your fork We use [semantic-versioning](https://semver.org/) and the [conventional commit message format](https://www.conventionalcommits.org/en/v1.0.0/). Keep a separate feature branch for each issue you want to address. As you develop code, continue to push code to your remote feature branch. Example: ``` tag: short description longer description here if necessary. ``` The message summary should be a one-sentence description of the change, and it must be 72 characters in length or shorter. For a list of tags, please [click here](https://github.com/commitizen/conventional-commit-types/blob/master/index.json). Note that you must include the `!` for breaking changes (e.g. `feat!: removed old apis`). Shown below are examples of the release type that will be done based on a commit message. #### Commit Types "Semantic versioning" means that changes to the version number of the package (e.g. `3.42.11` to `3.43.0`) are done according to rules that indicate how the change will affect consumers. Read more on the [semver page](https://semver.org/). The version number is broken into 3 positions — `Major.Minor.Patch`. In semantic release terms, changes to the numbers follow `Breaking.Feature.Fix`. The `release` script parses commit messages and decides what type of release to make based on the types of commits detected since the last release. The rules for commit types are: - Anything that changes or removes an API, option, or output format is a breaking change denoted by `!`. - Anything that adds new functionality in a backwards-compatible way is a feature (`feat`). Consumers have to upgrade to the new version to use the feature, but nothing will break if they do so. - Bugfixes (`fix`) for existing behavior are a patch. Consumers don't have to do anything but upgrade. - Other prefixes, such as `docs` or `chore`, don't trigger releases and don't appear in the changelog. These tags signal that there are **no external changes to *any* APIs** (including non-breaking ones). In most cases, commits will be a `feat` or `fix`. Make sure to include the `!` in the title if there are non-backwards-compatible changes in the commit. | Commit message | Release type | New version | | --- | --- | --- | | feat!: remove old files endpoints | Major ("breaking") | X+1.0.0 | | feat: add new file upload endpoint | Minor ("feature") | X.Y+1.0 | | fix: file streaming during download | Patch ("fix") | X.Y.Z+1 | | docs: document files api | No release | X.Y.Z | | chore: remove commented code from file upload | No release | X.Y.Z | | refactor: rename a variable (invisible change) | No release | X.Y.Z | ### Step 6: Rebase Before sending a pull request, rebase against upstream, such as: ``` git fetch upstream git rebase upstream/main ``` This will add your changes on top of what's already in upstream, minimizing merge issues. ### Step 7: Run the tests Make sure that all tests are passing before submitting a pull request by running: `dotnet test` ### Step 8: Send the pull request Send the pull request from your feature branch to us. Be sure to include a description that lets us know what work you did. Keep in mind that we like to see one issue addressed per pull request, as this helps keep our git history clean and we can more easily track down issues. --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Deprecation notice This version of the Box .NET SDK is under maintenance mode, and will be deprecated soon, only critical security updates… # Deprecation notice This version of the Box .NET SDK is under maintenance mode, and will be deprecated soon, only critical security updates and bug fixes will be provided. We recommend using the new version Box .NET SDK, which can be found at [box/box-dotnet-sdk-gen](https://github.com/box/box-dotnet-sdk-gen) You can find the migration guide [here](https://github.com/box/box-dotnet-sdk-gen/blob/main/migration-guide.md) for transitioning from Box .NET SDK v5.x to the new `box-sdk-gen` package. If you have any questions, please create an issue in the new repository or reach out to [Box Developer Support](https://developer.box.com/support/). # Box Windows V2 SDK [](http://opensource.box.com/badges) [](https://raw.githubusercontent.com/box/box-windows-sdk-v2/main/LICENSE) [](https://github.com/box/box-windows-sdk-v2/actions/workflows/build_and_test.yml) The Box .NET SDK can be used to make API calls to the Box APIs in a .NET project. The SDK is available for both .NET Framework 4.6.2 and .NET Core 2.0 or above. The installation of the SDK depends on the platform used. ## Table of contents [Getting Started](#getting-started) - [Installation](#installation) - [Authentication](#authentication) - [Sample Apps](#sample-apps) [Usage](#usage) [Other Resources](#additional-resources) [Versions](#versions) - [Supported Version](#supported-version) - [Version schedule](#version-schedule) [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) [Contributing](#contributing) [Copyright and License](#copyright-and-license) ## Getting Started ### Installation You can install SDK library using Nuget If you want to use .NET Core ``` PM> Install-Package Box.V2.Core ``` If you want to use .NET Framework ``` PM> Install-Package Box.V2 ``` Or you can add it to your project directly in Visual Studio. You can also download latest version from our [Github's release page](https://github.com/box/box-windows-sdk-v2/releases) ### Authentication Our .NET SDK supports the following authentication methods: - [Server Auth with JWT](https://developer.box.com/docs/authentication.md#server-auth-with-jwt) - [Server Auth with CCG](https://developer.box.com/docs/authentication.md#server-auth-with-ccg) - [Traditional 3-Legged OAuth2](https://developer.box.com/docs/authentication.md#traditional-3-legged-oauth2) - [Developer token](https://developer.box.com/docs/authentication.md#developer-token) ### Sample apps You can check one of our sample apps included in this repository to see how to use the SDK - [Create App User](https://github.com/box/box-windows-sdk-v2/tree/main/Box.V2.Samples.Core.AppUser.Create/) - [Upload File](https://github.com/box/box-windows-sdk-v2/tree/main/Box.V2.Samples.Core.File.Upload/) - [Proxy example](https://github.com/box/box-windows-sdk-v2/tree/main/Box.V2.Samples.Core.HttpProxy/) - [JWT Auth](https://github.com/box/box-windows-sdk-v2/tree/main/Box.V2.Samples.JWTAuth/) - [Token exchange](https://github.com/box/box-windows-sdk-v2/tree/main/Box.V2.Samples.TransactionalAuth/) ## Usage You can find detailed usage documentation and code samples under [docs](https://developer.box.com/073643284ab50a43e5967b215e71c6f5/README.md) directory. ## Other resources - [API Reference](https://developer.box.com/reference/) - [API Guides](https://developer.box.com/guides/) - [SDK Nuget Package](https://www.nuget.org/packages/Box.V2/) - [.NET Core SDK Nuget Package](https://www.nuget.org/packages/Box.V2.Core/) - [Box Windows SDK Video Tutorial](https://youtu.be/hqko0hxbaXU) - [Getting Started Docs](https://developer.box.com/guides/tooling/sdks/dotnet/) ## Versions We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. See [version strategy](https://developer.box.com/c7a878a5913191d95b5d99cc09ba99b4/VERSIONS.md) for details which is effective from 30 July 2022. ### Supported Version Only the current MAJOR version of SDK is supported. New features, functionality, bug fixes, and security updates will only be added to the current MAJOR version. A current release is on the leading edge of our SDK development, and is intended for customers who are in active development and want the latest and greatest features. Instead of stating a release date for a new feature, we set a fixed minor or patch release cadence of maximum 2-3 months (while we may release more often). At the same time, there is no schedule for major or breaking release. Instead, we will communicate one quarter in advance the upcoming breaking change to allow customers to plan for the upgrade. We always recommend that all users run the latest available minor release for whatever major version is in use. We highly recommend upgrading to the latest SDK major release at the earliest convenient time and before the EOL date. ### Version schedule | Version | Supported Environments | State | First Release | EOL/Terminated | | --- | --- | --- | --- | --- | | 5 | .NET Framework 4.6.2+ and .NET Core 2.0+ | Supported | 02 Nov 2021 | TBD | | 4 | .NET Framework 4.5+ and .NET Core 2.0+ | EOL | 02 Nov 2021 | TBD | | 3 | | EOL | 28 Jul 2017 | 02 Nov 2021 | | 2 | | EOL | 05 Nov 2015 | 28 Jul 2017 | ### Migrating from the old version? If you are migrating from the old major version visit our [upgrade documentation](https://developer.box.com/docs/upgrades/). ## Questions, Bugs, and Feature Requests? [Browse the issues tickets](https://github.com/box/box-windows-sdk-v2/issues)! Or, if that doesn't work, [file a new one](https://github.com/box/box-windows-sdk-v2/issues/new) and someone will get back to you. If you have general questions about the Box API, you can post to the [Box Developer Forum](https://community.box.com/t5/Developer-Forum/bd-p/DeveloperForum). ## Contributing All contributions to this project are welcome! For more information, please see our [Contribution guidelines](https://developer.box.com/716d2fedae801ced680fadf955be1b2b/CONTRIBUTING.md). ## Copyright and License Copyright 2018 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- ## Untitled *Type: page* Integration tests Setup To run the integration tests locally, you need an existing Box app. Create a platform app in https://cloud.app.box… # Integration tests ## Setup To run the integration tests locally, you need an existing Box app. Create a platform app in [https://cloud.app.box.com/developers/console](https://cloud.app.box.com/developers/console). Select the JWT authentication method. You must enable all possible scopes and authorize your app to access the Enterprise if you want to run all the tests. Some tests requires enterprise access and different scopes. When your application is ready download App Settings as and replace the existing `config.json` file in this directory with your own. There is an optional `userId` field that you can fill in with your existing `userId`, so this user will be used in the tests and no new user will be created. You can run the test using Visual Studio test explorer or from the command line by calling the following command ``` dotnet test .\Box.V2.Test.Integration ``` By default, integration tests will run for .net framework and .net core. You can run tests against either of these by passing the -f flag as follows. ``` dotnet test .\Box.V2.Test.Integration -f netcoreapp2.0 ``` ## Command approach for test setup Typically, integration tests require pre-existing resources (such as files) to operate on them. Such resources should also be removed from the account when the test ends or when an exception is thrown. To eliminate the need to duplicate such logic, the command approach was introduced. An example `IDisposableCommand` implementation looks like this ``` using System.Threading.Tasks; using Box.V2.Models; namespace Box.V2.Test.Integration.Configuration.Commands.DisposableCommands { public class CreateFolderCommand : CommandBase, IDisposableCommand { private readonly string _folderName; private readonly string _parentId; public string FolderId; public BoxFolder Folder; public CreateFolderCommand(string folderName, string parentId = "0", CommandScope scope = CommandScope.Test, CommandAccessLevel accessLevel = CommandAccessLevel.User) : base(scope, accessLevel) { _folderName = folderName; _parentId = parentId; } public async Task<string> Execute(IBoxClient client) { var createFolderRequest = new BoxFolderRequest { Name = _folderName, Parent = new BoxRequestEntity { Id = _parentId } }; Folder = await client.FoldersManager.CreateAsync(createFolderRequest); FolderId = Folder.Id; return FolderId; } public async Task Dispose(IBoxClient client) { await client.FoldersManager.DeleteAsync(FolderId); await client.FoldersManager.PurgeTrashedFolderAsync(FolderId); } } } ``` The Execute command will be called when the command is executed, and Dispose when the test is terminated or an exception is thrown. As you can see, dispose or execute command could consist of multiple API calls. `CommandAccessLevel` indicates which BoxClient should be used for the test (managed or service account). Depends on what you may need and the enterprise access (e.g., to create a MetadataTemplate). `CommandScope` indicates when dispose will be called (test, class, assembly). You can usually keep this as `CommandScope.Test` for single test setup commands. Commands are usually wrapped in helper methods that look like this ``` public static async Task<BoxFolder> CreateFolder(string parentId = "0", CommandScope commandScope = CommandScope.Test, CommandAccessLevel accessLevel = CommandAccessLevel.User) { var createFolderCommand = new CreateFolderCommand(GetUniqueName("folder"), parentId, commandScope, accessLevel); await ExecuteCommand(createFolderCommand); return createFolderCommand.Folder; } ``` You can then simply call this command in your test as follows ``` [TestMethod] public async Task GetWatermarkAsync_ForExistingFolder_ShouldCorrectlyApplyWatermarkOnFolder() { var folder = await CreateFolder(FolderId); await UserClient.FoldersManager.ApplyWatermarkAsync(folder.Id); var watermark = await UserClient.FoldersManager.GetWatermarkAsync(folder.Id); Assert.IsNotNull(watermark); } ``` As you can see, since this test does not test folder creation, so command logic is used. Try using or adding commands like this to simplify and reuse the test setup. This makes the tests more readable, easier to maintain, and ensures that the test account is in the same state after and before running all the tests. --- ## Untitled *Type: page* Upgrading from 4.x.x to 5.x.x Follow the General changes to see the changes that are package indenpendent. Also refer to the Box.V2 or Box.V… # Upgrading from 4.x.x to 5.x.x Follow the [General changes](#general-changes) to see the changes that are package indenpendent. Also refer to the [Box.V2](#box-v2) or [Box.V2.Core](#box-v2-core) section depending on the package you are using. ## General changes ### Removed deprecated methods Some old, deprecated methods have been removed from version 5.x.x. Read this section further to see a new, alternative methods. #### BoxMetadataManager/IBoxMetadataManager ``` //Old ExecuteMetadataQueryAsync(string from, string ancestorFolderId, IEnumerable<string> fields, string query, Dictionary<string, object> queryParameters, string indexName, List<BoxMetadataQueryOrderBy> orderBy, int limit, string marker, bool autoPaginate) ExecuteMetadataQueryAsync(string from, string ancestorFolderId, string query = null, Dictionary<string, object> queryParameters = null, string indexName = null, List<BoxMetadataQueryOrderBy> orderBy = null, int limit = 100, string marker = null, bool autoPaginate = false) //New ExecuteMetadataQueryAsync(BoxMetadataQueryRequest queryRequest) ``` #### BoxConfigBuilder/IBoxConfigBuilder ``` //Old SetBoxApiUri(...) SetBoxTokenApiUri(...) //New SetBoxApiHostUri(...) ``` #### BoxFilesManager/IBoxFilesManager ``` //Old DownloadStreamAsync(...) //New DownloadAsync(...) ``` ``` //Old UploadFileVersionUsingSessionAsync(...) //New UploadNewVersionUsingSessionAsync(...) ``` ``` //Old GetCollaborationsAsync(...) //New GetCollaborationsCollectionAsync(...) ``` ``` //Old GetFilePreviewAsync(...) GetPreviewAsync(...) //New GetPreviewLinkAsync(...) ``` #### BoxSearchManager/IBoxSearchManager ``` //Old SearchAsync(...) //New QueryAsync(...) ``` #### BoxFolderManager/IBoxFolderManager ``` //Old GetTrashItemsAsync(string id, int limit, int offset = 0, IEnumerable<string> fields = null) //New GetTrashItemsAsync(int limit, int offset = 0, IEnumerable<string> fields = null, bool autoPaginate = false, string sort = null, BoxSortDirection? direction = null) ``` ``` //Old GetItemsAsync(...) //New GetFolderItemsAsync(...) ``` #### BoxTermsOfServiceManager/IBoxTermsOfServiceManager ``` //Old CreateBoxTermsOfServiceUserStatusesAsync(BoxTermsOfServiceUserStatusesRequest termsOfServicesUserStatusesRequest) //New CreateBoxTermsOfServiceUserStatusesAsync(BoxTermsOfServiceUserStatusCreateRequest termsOfServiceUserStatusCreateRequest) ``` #### OAuthSession ``` //Old OAuthSession(string access_token, string refresh_token, int expires_in, string token_type, AuthVersion authVersion) //New OAuthSession(string access_token, string refresh_token, int expires_in, string token_type) ``` #### BoxRetentionPoliciesManager/IBoxRetentionPoliciesManager ``` //Old Task<BoxCollectionMarkerBased<BoxFileVersion>> GetFileVersionsUnderRetentionForAssignmentAsync(...) //New Task<BoxCollectionMarkerBased<BoxFile>> GetFileVersionsUnderRetentionForAssignmentAsync(...) ``` ### Deprecated fields Some old, deprecated fields have been removed from version 5.x.x. Read this section further to see a new, alternative fields. #### BoxConfigBuilder/IBoxConfigBuilder ``` //Old BoxAuthTokenApiUri //New BoxApiHostUri ``` #### Constants ``` //Old MasterInviteAccept //New AdminInviteAccept ``` ``` //Old MasterInviteReject //New AdminInviteReject ``` ``` //Old V1AuthString //New //V1 Auth is no longer support in the API. ``` #### IBoxConfig ``` //Old BoxAuthTokenApiUri //New BoxApiHostUri ``` #### BoxPermissionsRequest ``` //Old BoxPermissionType? Preview //New //Deprecated field. Value is always true ``` #### OAuthSession ``` //Old AuthVersion //New //Box API have now one auth version so there is no need to differentiate between them. ``` #### BoxFileVersion ``` //Old BoxFileVersion //New //No alternative as this field was used only in GetFileVersionsUnderRetentionForAssignmentAsync(...). //This method now returns proper BoxFile object instead. ``` ## Box.V2 ### Minimal .NET runtime version upgrade If you are still using .NET Framework version lower than 4.6.2 you need to upgrade to the 4.6.2+ version. You can do it by changing target framework in the .csproj file of your project. For SDK-style projects Before ``` <TargetFramework>net45<TargetFramework/> ``` After ``` <TargetFramework>net462<TargetFramework/> ``` See [SDK-style target framework](https://learn.microsoft.com/en-us/dotnet/standard/frameworks) for more information. For non SDK-style projects Before ``` <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> ``` After ``` <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion> ``` See [MSBuild target framework](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-target-framework-and-target-platform?view=vs-2022) for more information We recommend to upgrade to the newest version possible. See [.NET Framework lifecycle](https://learn.microsoft.com/en-us/lifecycle/products/microsoft-net-framework) ## Box.V2.Core No changes --- ## Untitled *Type: page* Contributor Covenant Code of Conduct Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and… # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [oss@box.com](mailto:oss@box.com). The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.4, available at [http://contributor-covenant.org/version/1/4](http://contributor-covenant.org/version/1/4/) --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 5.6.0 (2024-04-0… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## 5.6.0 (2024-04-05) ### New Features and Enhancements - Add privacy manifest files ([#924](https://github.com/box/box-ios-sdk/issues/924)) ([cbef168](https://github.com/box/box-ios-sdk/commit/cbef168bb872941899be26116c647ac29f5dd44b)) - Add support for `visionOS` ([#916](https://github.com/box/box-ios-sdk/issues/916)) ([a05b243](https://github.com/box/box-ios-sdk/commit/a05b2433f1b2d0c1ec72f946e0706d03a4548703)) - Add support for additional fields in `SignRequest` ([#919](https://github.com/box/box-ios-sdk/issues/919)) ([36f464c](https://github.com/box/box-ios-sdk/commit/36f464c23a161f5d0fcc6858c3615d884ce8ee07)) - Make fields from `TokenInfo` publicly available ([#920](https://github.com/box/box-ios-sdk/issues/920)) ([eb26f47](https://github.com/box/box-ios-sdk/commit/eb26f47bbde6749f44f149e95b3610e41c16d2f2)) ## 5.5.0 (2023-08-08) ### New Features and Enhancements - Add missing values in `SignRequestSignerInputContentType` and `SignRequestStatus` along with the tests ([#907](https://github.com/box/box-ios-sdk/issues/907)) ([56a8250](https://github.com/box/box-ios-sdk/commit/56a82500c0abe648825d8300979601a25f792c84)) ### Bug Fixes - Identify iPhone Simulator on Apple Silicon ([#902](https://github.com/box/box-ios-sdk/issues/902)) ([7731a7f](https://github.com/box/box-ios-sdk/commit/7731a7f434add74e163a76511fe1e2a3f26517f7)) - Make code compatible with macOS. ([#900](https://github.com/box/box-ios-sdk/issues/900)) ([3b0016e](https://github.com/box/box-ios-sdk/commit/3b0016e44e674db0ea429273c03e5a29177372bf)) - Remove use of deprecated string scanner API. ([#901](https://github.com/box/box-ios-sdk/issues/901)) ([af5f0e5](https://github.com/box/box-ios-sdk/commit/af5f0e52d184fbd27f56d972fb93b3e543547773)) ### 5.4.2 (2023-04-19) ### Bug Fixes - An emoty string `nextMarker` should be treated as end-of-paging. ([#893](https://github.com/box/box-ios-sdk/issues/893)) ([49c17de](https://github.com/box/box-ios-sdk/commit/49c17de588fcffcd2d151ce9047ebc09965f80ce)) ### 5.4.1 (2023-02-24) ### Bug Fixes - Fix `listAssignments` and `assign` methods in `RetentionPolicyModule` ([#886](https://github.com/box/box-ios-sdk/issues/886)) ([b668888](https://github.com/box/box-ios-sdk/commit/b668888f35136dd1239526b70cc31a10bdd04744)) ## 5.4.0 (2022-11-08) ### New Features and Enhancements - Add `content_type` field to Sign Requests signer ([#871](https://github.com/box/box-ios-sdk/issues/871)) ([1ec5b01](https://github.com/box/box-ios-sdk/commit/1ec5b0149f01cd3a18f5cba39b77e01678655932)) - Add `redirect_url` and `declined_redirect_url` to Sign Request ([#870](https://github.com/box/box-ios-sdk/issues/870)) ([f94d988](https://github.com/box/box-ios-sdk/commit/f94d98862d2fdb2603f4684b963d29d04e0fdb3d)) - Add support for `sign` webhook triggers ([#875](https://github.com/box/box-ios-sdk/issues/875)) ([994bfaf](https://github.com/box/box-ios-sdk/commit/994bfaf3ead983f5014808f6c9e5ffe167ab8e42)) - Added method to remove retention policy assignment ([#873](https://github.com/box/box-ios-sdk/issues/873)) ([c5f146c](https://github.com/box/box-ios-sdk/commit/c5f146c960bb1f940418975078d83fb63ff3bdec)) - Added support for Modifiable Retention Policies ([#872](https://github.com/box/box-ios-sdk/issues/872)) ([e2b7a17](https://github.com/box/box-ios-sdk/commit/e2b7a178c6592c9f7d1e7ce691c215680b3f45d0)) ## 5.3.0 (2022-08-19) ### New Features and Enhancements - add `version_number` to `FileVersion` ([#853](https://github.com/box/box-ios-sdk/issues/853)) ([ac81667](https://github.com/box/box-ios-sdk/commit/ac81667ea409cbbe3de9be0c316c630ec6fbc2f5)) - Add support for async API in `FoldersModule` ([#851](https://github.com/box/box-ios-sdk/issues/851)) ([58b9dde](https://github.com/box/box-ios-sdk/commit/58b9dde412eddc76915c99b960702f4af95b62a4)) - Add support for file request API ([#867](https://github.com/box/box-ios-sdk/issues/867)) ([ec7813e](https://github.com/box/box-ios-sdk/commit/ec7813e31706c08aaaeac75debdba8d7802786cb)) - Add support for upload and delete Avatar API ([#863](https://github.com/box/box-ios-sdk/issues/863)) ([1e967f5](https://github.com/box/box-ios-sdk/commit/1e967f5a3eaafbeb894cf8289032ad8ce8664266)) - Add support of Editable Shared Link ([#861](https://github.com/box/box-ios-sdk/issues/861)) ([bc6ea18](https://github.com/box/box-ios-sdk/commit/bc6ea18bf2e10bebeb62401a55001139f05c76df)) - Expose `send()` method public in `BoxClient` ([#843](https://github.com/box/box-ios-sdk/issues/843)) ([23caaca](https://github.com/box/box-ios-sdk/commit/23caaca5b6fe8ec1b23470193bc011a62c66d49f)) ### Bug Fixes - Respect Content-Type coming from custom headers ([#841](https://github.com/box/box-ios-sdk/issues/841)) ([a7c69a7](https://github.com/box/box-ios-sdk/commit/a7c69a73c6142d4b82c718d2d311098dd2b70250)) ### 5.2.1 (2022-04-22) ### Bug Fixes - Expose fields from `BoxResponse` for custom API calls ([#833](https://github.com/box/box-ios-sdk/issues/833)) ([bae1536](https://github.com/box/box-ios-sdk/commit/bae1536236a22de198281012b0ee43c84b0e3485)) ## 5.2.0 (2022-03-18) ### New Features and Enhancements - Add `disposition_at` field to the `File` object ([#814](https://github.com/box/box-ios-sdk/issues/814)) ([3c90df0](https://github.com/box/box-ios-sdk/commit/3c90df038b9f490a9d38af85404fa1d6ddcd5d0d)) - Add support for Client Credentials Grant authentication method ([#821](https://github.com/box/box-ios-sdk/issues/821)) ([f6d7542](https://github.com/box/box-ios-sdk/commit/f6d75424e8c0d91517e3ffb8df67f77ad3f2374b)) ## 5.1.0 (2022-01-17) ### New Features and Enhancements - Allow to customize URL for the `OAuth2` authorization page ([#811](https://github.com/box/box-ios-sdk/issues/811)) ([1901d29](https://github.com/box/box-ios-sdk/commit/1901d296a2be4b0f2eef25eda06928aebc81de9a)) - **Events:** Add support for `admin_logs_streaming` stream type ([#800](https://github.com/box/box-ios-sdk/issues/800)) ([0a3118e](https://github.com/box/box-ios-sdk/commit/0a3118ef95c2eb42b0080d0352784849e85eb422)) - **RetentionPolicy:** New API for get files and file versions under retention ([#807](https://github.com/box/box-ios-sdk/issues/807)) ([38327f0](https://github.com/box/box-ios-sdk/commit/38327f09a92dba7827e1866940a643d624757762)) - **SharedLink:** add support for `vanity_name` ([#799](https://github.com/box/box-ios-sdk/issues/799)) ([3ea6eb2](https://github.com/box/box-ios-sdk/commit/3ea6eb2a1c2b713fd0769e93a2dc4ee51da695fd)) ### Bug Fixes - **SignRequest:** Fix encoding `date_value` to `yyyy-mm-dd` format in `prefillTag` ([#806](https://github.com/box/box-ios-sdk/issues/806)) ([4f902a4](https://github.com/box/box-ios-sdk/commit/4f902a47482de55ec69b5522e6cf5affd653b4c8)) ## 5.0.0 (2021-10-28) ### ⚠ BREAKING CHANGES - Update PagingIterator to return pages and simplify logic ([#737](https://github.com/box/box-ios-sdk/pull/737)) - Remove insensitive language field `collaborationWhiteList` in BoxClient. Use `collaborationAllowList` instead. ([#790](https://github.com/box/box-ios-sdk/pull/790)) ### New Features and Enhancements - Replace insensitive event types ([#785](https://github.com/box/box-ios-sdk/pull/785)) - Add SignAPI support ([#792](https://github.com/box/box-ios-sdk/pull/792)) ## 4.4.0 (2021-04-20) ### New Features and Enhancements - Add support for search param to get shared link items ([#756](https://github.com/box/box-ios-sdk/pull/756)) - Add support for folder lock functionality ([#759](https://github.com/box/box-ios-sdk/pull/759)) - Add support for copyInstanceOnItemCopy field for metadata templates ([#763](https://github.com/box/box-ios-sdk/pull/763)) - Add support for stream upload of new file versions and add support for 'If-Match' header when uploading new file versions ([#766](https://github.com/box/box-ios-sdk/pull/766)) - Add additional details field for `Event` model ([#770](https://github.com/box/box-ios-sdk/pull/770)) ### Bug Fixes - Pass only a scheme to iOS Authentication APIs ([#755](https://github.com/box/box-ios-sdk/pull/755)) - Update `listEnterpriseGroups()` to use documented parameter for filtering by name ([#757](https://github.com/box/box-ios-sdk/pull/757)) - Fix bug for OAuth where the callback is not called if token has been revoked ([#762](https://github.com/box/box-ios-sdk/pull/762)) ## 4.3.0 (2021-02-01) ### New Features and Enhancements - Add support for OAuth 2 custom callback URL ([#746](https://github.com/box/box-ios-sdk/pull/746)) - Add support for zip download ([#749](https://github.com/box/box-ios-sdk/pull/749)) ### Bug Fixes - Update gems to patch kramdown vulnerability ([#742](https://github.com/box/box-ios-sdk/pull/742)) - Update gems to patch activesupport vulnerability ([#745](https://github.com/box/box-ios-sdk/pull/745)) ## 4.2.0 (2020-11-16) ### New Features and Enhancements - Add error information to OAuth web session failures ### Bug Fixes - Fix bug with creating collaboration - Fix bug with getting enterprise events ## 4.1.0 (2020-05-15) ### New Features and Enhancements - Add ability to cancel uploads and downloads - Add support for the uploader display name field for Files and File Versions - Add support for the classification field for Files and Folders - Add path parameter sanitization ### Bug Fixes - Fix logging of API responses ## 4.0.0 (2020-02-13) ### ⚠ BREAKING CHANGES - Change `status` field for task assignments from a String to an Enum - Remove macOS, tvOS, and watchOS support ### New Features and Enhancements - Make authentication session classes `OAuth2Session`, `SingleTokenSession`, and `DelegatedAuthSession` public ## 3.1.0 (2020-01-09) ### New Features and Enhancements - Add shared link downscoping - Add closure parameter for progress of uploads and downloads - Add marker based pagination to list users endpoint ## 3.0.0 (2019-11-18) ### New Features and Enhancements - Added file specific icons for the Sample Apps. ## 3.0.0-rc.3 (2019-11-14) ### ⚠ BREAKING CHANGES - For Module methods that returned a collection of objects, changed from returning a PaginationIterator to returning a PagingIterator in a completion. - Modules are now automatically instantiated with the BoxClient object and no longer allow the client app to instantiate them - Related RetentionPolicy classes no longer allow rawData to be set by the client app - UploadPartDescription made private - Fixed bug with exponential backoff and changed SDK configuration item "retryAfterTime" to "retryBaseInterval" ### New Features and Enhancements - RetentionPolicyModule methods made public - Added additional supporting types - Improved support for logging to file, allow for custom file path, and fixed some related bugs - Improved console logging formatting - Updated Sample Apps to use new PagingIterator responses ## 3.0.0-rc.2 (2019-10-30) ### ⚠ BREAKING CHANGES - Changed SDK errors from customValue enum cases to specific enum cases ### New Features and Enhancements - Added Xcode 11 + iOS 13 support to Travis CI ## 3.0.0-rc.1 (2019-10-18) ### ⚠ BREAKING CHANGES - Changed TaskAssignment.resolutionState from String to new AssignmentState enum type - Changed Group.groupType from String to new GroupType enum type - Changed Folder.allowedSharedLinkAccessLevels from [String] to new [SharedLinkAccess] enum type - Changed File.allowedInviteeRoles from [String] to new [CollaborationRole] enum type - Network responses with 4xx or 5xx status codes are now transformed into an API Error - CollaborationItem changed from class to enum - CommentItem changed from class to enum - FolderItem changed from class to enum - WebhookItem changed from class to enum - TaskItem changed from class to enum - JSON decoding errors now emit expected type - Public method names changed to a new convention in many of the "module" classes - Redesigned error classes and error hierarchy - Temporarily removed progress closure for uploads and downloads ### New Features and Enhancements Added Xcode 11 support (SDK builds still target iOS 11.0) Removed AlamoFire dependency Added support for Device Pins Added SDK Configuration URL validation Added SDK-level constants rootFolder and currentUser for convenience Added support for Collaboration Whitelist endpoints Added support for Retention Policy endpoints Added support for Tasks endpoints Added support for Webhooks endpoints Added support for Groups and Group Membership endpoints Added support for Legal Holds endpoints Added support for Terms of Service endpoints Added support for Terms of Service User Status endpoints Added support for Watermarking endpoints Added support for Storage Policy endpoints Added support for Metadata Cascade Policy endpoints Added support for User endpoints Added support for Events endpoints Added Error Views in Sample Apps Improved structure and usability of Sample Apps ## 3.0.0-alpha.3 (2019-08-29) ### ⚠ BREAKING CHANGES - Changed File Entry Container "entries" from optional to not optional ### New Features and Enhancements - Added support for Web Links - Added support for Trash endpoints - Added support for Recent Items - Added support for File Version endpoints - Added support for Delete File endpoint - Added support for Chunked Upload Endpoints - Added support for upload preflight check - Added support for downloading a representation of a file - Added support for custom OAuth2 Callback URL - Added KeychainTokenStore for OAuth2SampleApp ## 3.0.0-alpha.2 (2019-08-08) ### ⚠ BREAKING CHANGES Moved some constants to different namespaces: - `Box.rootFolder` is now `BoxSDK.Constants.rootFolder` - `Box.currentUser` is now `BoxSDK.Constants.currentUser` Updated the arguments that `client.files.updateFileInfo()` takes for consistency with the rest of the SDK Changed the type of the `expiresAt` arguments in `client.files.lockFile()` from `String` to `Date` Removed unused arguments from `client.files.unlockFile()` Changed the type of the `unsharedAt` and `password` arguments of `client.files.setSharedLink()` and `client.folders.setSharedLink()` to accept `.null` values Replaced the `access`, `password`, `unsharedAt`, and `canDownload` arguments of `client.folders.updateFolder()` with a single `sharedLink` argument to enable setting the entire shared link field to `.null` in order to remove the shared link Replaced `client.getFavoritesCollectionId()` with `client.collections.getFavoritesCollection()` Removed `client.collections.addItemsToCollection()` and `client.collections.deleteItemsFromCollection()` Changed the result type for `client.files.addFileToFavorites()`, `client.files.addFileToCollection()`, `client.files.removeFileFromFavorites()`, and `client.files.removeFileFromCollection()` from `Void` to `File` Changed the result type for `client.folders.addFolderToFavorites()`, `client.folders.addFolderToCollection()`, `client.folders.removeFolderFromFavorites()`, and `client.folders.removeFolderFromCollection()` from `Void` to `Folder` ### New Features and Enhancements - Added support for [token downscoping](./docs/usage/authentication.md#token-exchange) - Added a `KeychainTokenStore` implementation to enable persisting authentication state on the Keychain - The SDK now automatically clears the token store after destroying a client and revoking its tokens ## [3.0.0-alpha.1] (2019-07-25) Initial beta release :tada: --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - if you want to contribute code. Please be sure to file an issue first. ## Pull request best practices We want to accept your pull requests. Please follow these steps: ### Step 1: File an issue Before writing any code, please file an issue stating the problem you want to solve or the feature you want to implement. This allows us to give you feedback before you spend any time writing code. There may be a known limitation that can't be addressed, or a bug that has already been fixed in a different way. The issue allows us to communicate and figure out if it's worth your time to write a bunch of code for the project. ### Step 2: Fork this repository in GitHub This will create your own copy of our repository. ### Step 3: Add the upstream source The upstream source is the project under the Box organization on GitHub. To add an upstream source for this project, type: ``` git remote add upstream git@github.com:box/box-ios-sdk.git ``` This will come in useful later. ### Step 4: Create a feature branch Create a branch with a descriptive name, such as `add-search`. ### Step 5: Push your feature branch to your fork We use [semantic-versioning](https://semver.org/) and the [conventional commit message format](https://www.conventionalcommits.org/en/v1.0.0/). Keep a separate feature branch for each issue you want to address. As you develop code, continue to push code to your remote feature branch. Example: ``` tag: short description longer description here if necessary. ``` The message summary should be a one-sentence description of the change, and it must be 72 characters in length or shorter. For a list of tags, please [click here](https://github.com/commitizen/conventional-commit-types/blob/master/index.json). Note that you must include the `!` for breaking changes (e.g. `feat!: removed old apis`). Shown below are examples of the release type that will be done based on a commit message. #### Commit Types "Semantic versioning" means that changes to the version number of the package (e.g. `3.42.11` to `3.43.0`) are done according to rules that indicate how the change will affect consumers. Read more on the [semver page](https://semver.org/). The version number is broken into 3 positions — `Major.Minor.Patch`. In semantic release terms, changes to the numbers follow `Breaking.Feature.Fix`. The `release` script parses commit messages and decides what type of release to make based on the types of commits detected since the last release. The rules for commit types are: - Anything that changes or removes an API, option, or output format is a breaking change denoted by `!`. - Anything that adds new functionality in a backwards-compatible way is a feature (`feat`). Consumers have to upgrade to the new version to use the feature, but nothing will break if they do so. - Bugfixes (`fix`) for existing behavior are a patch. Consumers don't have to do anything but upgrade. - Other prefixes, such as `docs` or `chore`, don't trigger releases and don't appear in the changelog. These tags signal that there are **no external changes to *any* APIs** (including non-breaking ones). In most cases, commits will be a `feat` or `fix`. Make sure to include the `!` in the title if there are non-backwards-compatible changes in the commit. | Commit message | Release type | New version | | --- | --- | --- | | feat!: remove old files endpoints | Major ("breaking") | X+1.0.0 | | feat: add new file upload endpoint | Minor ("feature") | X.Y+1.0 | | fix: file streaming during download | Patch ("fix") | X.Y.Z+1 | | docs: document files api | No release | X.Y.Z | | chore: remove commented code from file upload | No release | X.Y.Z | | refactor: rename a variable (invisible change) | No release | X.Y.Z | ### Step 6: Rebase Before sending a pull request, rebase against upstream, such as: ``` git fetch upstream git rebase upstream/main ``` This will add your changes on top of what's already in upstream, minimizing merge issues. ### Step 7: Run the tests Make sure that all tests are passing before submitting a pull request. ### Step 8: Send the pull request Send the pull request from your feature branch to us. Be sure to include a description that lets us know what work you did. Keep in mind that we like to see one issue addressed per pull request, as this helps keep our git history clean and we can more easily track down issues. --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Box iOS SDK Project Status Platforms License Swift Package Manager Carthage compatible CocoaPods compatible Build Status Coverage Getting… # Box iOS SDK [](http://opensource.box.com/badges) [](https://cocoapods.org/pods/BoxSDK) [](https://raw.githubusercontent.com/box/box-ios-sdk/main/LICENSE) [](https://github.com/apple/swift-package-manager) [](https://github.com/Carthage/Carthage) [](https://cocoapods.org/pods/BoxSDK) [](https://travis-ci.com/box/box-swift-sdk) [](https://coveralls.io/github/box/box-ios-sdk?branch=main) Getting Started Docs: [https://developer.box.com/guides/mobile/ios/quick-start/](https://developer.box.com/guides/mobile/ios/quick-start/) # NOTE: The Box iOS SDK in **Objective-C** (prior to v3.0.0) has been moved from the main branch to the [objective-c-maintenance branch](https://github.com/box/box-ios-sdk/tree/objective-c-maintenance). Going forward, the main branch will contain the iOS SDK in **Swift**, starting with v3.0.0. Box iOS SDK - [Box iOS SDK](#box-ios-sdk) [NOTE:](#note) - [Requirements](#requirements) [Installing the SDK](#installing-the-sdk) - [Carthage](#carthage) - [CocoaPods](#cocoapods) [Swift Package Manager](#swift-package-manager) - [Importing BoxSDK into Project](#importing-boxsdk-into-project) - [Adding BoxSDK as a Dependency](#adding-boxsdk-as-a-dependency) [Getting Started](#getting-started) [Sample Apps](#sample-apps) - [OAuth2 Sample App](#oauth2-sample-app) - [JWT Auth Sample App](#jwt-auth-sample-app) [FIPS 140-2 Compliance](#fips-140-2-compliance) [Versions](#versions) - [Supported Version](#supported-version) - [Version schedule](#version-schedule) [Copyright and License](#copyright-and-license) ## Requirements - iOS 11.0+ / Mac OS X 10.13+ / tvOS 11.0+ / watchOS 4.0+ - Xcode 10.0+ ## Installing the SDK ### Carthage **Step 1**: Add to your `Cartfile` ``` git "https://github.com/box/box-ios-sdk.git" ~> 5.0 ``` **Step 2**: Update dependencies ``` $ carthage update --use-xcframeworks --platform iOS ``` **Step 3**: Drag the built xcframework from Carthage/Build into your project. For more detailed instructions, please see the [official documentation for Carthage](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos). ### CocoaPods **Step 1**: Add to your `Podfile` ``` pod 'BoxSDK', '~> 5.0' ``` **Step 2**: Install pod by running the following command in the directory with the `Podfile` ``` $ pod install ``` For more detailed instructions, please see the [official documentation for Cocoapods](https://guides.cocoapods.org/using/using-cocoapods.html). ### Swift Package Manager #### Importing BoxSDK into Project **Step 1**: Click on Xcode project file **Step 2**: Click on Swift Packages and click on the plus to add a package **Step 3**: Enter the following repository url `https://github.com/box/box-ios-sdk.git` and click next **Step 4**: Leave the default settings to get the most recent release and click next to finish importing The process should look like below: #### Adding BoxSDK as a Dependency For detailed instructions, please see the [official documentation for SPM](https://swift.org/package-manager/). ## Getting Started To get started with the SDK, get a Developer Token from the Configuration page of your app in the [Box Developer Console](https://app.box.com/developers/console). You can use this token to make test calls for your own Box account. ``` import BoxSDK let client = BoxSDK.getClient(token: "YOUR_DEVELOPER_TOKEN") client.users.getCurrentUser() { result in switch result { case let .error(error): print("Error: \(error)") case let .success(user): print("\(user.name) (\(user.login)) is logged in") } } ``` The usage docs that show how to make calls to the Box API with the SDK can be found [here](https://github.com/box/box-ios-sdk/tree/main/BoxSDK/docs/usage). The Jazzy docs that show class, method, variable, etc definitions can be found [here](https://opensource.box.com/box-ios-sdk/). ## Sample Apps ### OAuth2 Sample App A sample app using OAuth2 Authentication can be found in the repository [here](https://github.com/box/box-ios-sdk/tree/main/BoxSDK/SampleApps/OAuth2SampleApp). This app demonstrates how to use the SDK to make calls, and can be run directly by entering your own credentials to log in. To execute the sample app: **Step 1**: Run carthage ``` $ cd SampleApps/OAuth2SampleApp $ carthage update --use-xcframeworks --platform iOS ``` **Step 2**: Open Xcode Project File ``` $ open OAuth2SampleApp.xcodeproj ``` **Step 3**: Insert your client ID and client secret First, find your OAuth2 app's client ID and secret from the [Box Developer Console](https://app.box.com/developers/console). Then, add these values to the sample app in the `Constants.swift` file in the sample app: ``` static let clientId = "YOUR CLIENT ID GOES HERE" static let clientSecret = "YOUR CLIENT SECRET GOES HERE" ``` **Step 4**: Set redirect URL Using the same client ID from the previous step, set the redirect URL for your application in the [Box Developer Console](https://app.box.com/developers/console) to `boxsdk-<<YOUR CLIENT ID>>://boxsdkoauth2redirect`, where `<<YOUR CLIENT ID>>` is replaced with your client ID. For example, if your client ID were `vvxff7v61xi7gqveejo8jh9d2z9xhox5` the redirect URL should be `boxsdk-vvxff7v61xi7gqveejo8jh9d2z9xhox5://boxsdkoauth2redirect` **Step 5**: Run the sample app ### JWT Auth Sample App A sample app using JWT Authentication can be found in the repository [here](https://github.com/box/box-ios-sdk/tree/main/BoxSDK/SampleApps/JWTSampleApp). This app demonstrates how to set up JWT authentication with a remote authorization service, and will not run until you provide the code to retrieve tokens. To execute the sample app: **Step 1**: Run carthage ``` $ cd SampleApps/JWTSampleApp $ carthage update --use-xcframeworks --platform iOS ``` **Step 2**: Open Xcode Project File ``` $ open JWTSampleApp.xcodeproj ``` **Step 3**: Insert your client ID and client secret First, find your OAuth2 app's client ID and secret from the [Box Developer Console](https://app.box.com/developers/console). Then, add these values to the sample app in the `Constants.swift` file in the sample app: ``` static let clientId = "YOUR CLIENT ID GOES HERE" static let clientSecret = "YOUR CLIENT SECRET GOES HERE" ``` **Step 4**: Add code for retrieving access tokens In the `ViewController.swift` file in the sample app, edit the `obtainJWTTokenFromExternalSources()` method: ``` func obtainJWTTokenFromExternalSources() -> DelegatedAuthClosure { return { uniqueID, completion in #error("Obtain a JWT Token from your own service or a Developer Token for your app in the Box Developer Console at https://app.box.com/developers/console and return it in the completion.") // The code below is an example implementation of the delegate function // Please provide your own implementation // ... } } ``` **Step 5**: Run the sample app ## FIPS 140-2 Compliance The Box iOS SDK uses the CommonCrypto library, which relies on Apple's corecrypto cryptographic module. This module has undergone multiple validations by the Cryptographic Module Validation Program (CMVP) and is confirmed to be compliant with FIPS 140-2 standards. For further information, please refer to [Apple's security certification](https://support.apple.com/en-gb/guide/certifications/apc30d0ed034/web) and [iOS security certifications](https://support.apple.com/en-gb/guide/certifications/apc3fa917cb49/1/web/1.0). ## Versions We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. See [version strategy](https://developer.box.com/d64027e54d383b70ba5ad7e1f71c646b/VERSIONS.md) for details which is effective from 30 July 2022. ### Supported Version Only the current MAJOR version of SDK is supported. New features, functionality, bug fixes, and security updates will only be added to the current MAJOR version. A current release is on the leading edge of our SDK development, and is intended for customers who are in active development and want the latest and greatest features. Instead of stating a release date for a new feature, we set a fixed minor or patch release cadence of maximum 2-3 months (while we may release more often). At the same time, there is no schedule for major or breaking release. Instead, we will communicate one quarter in advance the upcoming breaking change to allow customers to plan for the upgrade. We always recommend that all users run the latest available minor release for whatever major version is in use. We highly recommend upgrading to the latest SDK major release at the earliest convenient time and before the EOL date. ### Version schedule | Version | Supported Environments | State | First Release | EOL/Terminated | | --- | --- | --- | --- | --- | | 5 | iOS 11.0+ / Mac OS X 10.13+ / tvOS 11.0+ / watchOS 4.0+ | Supported | 28 Oct 2021 | TBD | | 4 | | EOL | 13 Feb 2020 | 28 Oct 2021 | | 3 | | EOL | 20 Nov 2019 | 13 Feb 2020 | ## Copyright and License Copyright 2019 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- ## Untitled *Type: page* Integration Tests Running integration tests locally Create Platform Application To run integration tests locally you will need a Custom App… # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created at [https://cloud.app.box.com/developers/console](https://cloud.app.box.com/developers/console) with `Server Authentication (Client Credentials Grant)` selected as authentication method. Once created you can edit properties of the application. In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. In section `Advanced Features` enable `Make API calls using the as-user header`. Now select `Authorization` and submit application to be reviewed by account admin. ### Completing the configuration file Next, you will need to fill the `Configuration.json` file which is located under the following path `./IntegrationTests/Resources/Configuration.json` and look like this: ``` { "ccg": { "clientId": "", "clientSecret": "", "enterpriseId": "", "userId": "" }, "data": { "collaboratorId": "" } } ``` - `clientId` - you can find this in `Configuration` tab, in `Client ID` field - `clientSecret` - you can find this in `Configuration` tab, after tapped to `Fetch Client Secret` button - `enterpriseId` - you can find this in `General Settings` tab in field `Enterprise ID` - `userId` - you can find this in `General Settings` tab in field `User ID` - `collaboratorId` - please enter the ID of your designated collaborator here for testing purposes only. It is not required, however if you skip this field, then a few test will fail. You should pass either `enterpriseId` if you want to use Service Account account in your tests or `userId` if you want making calls as an App User or Managed User. In case when both these parameters will be filled, `enterpriseId` will be used. For more information about CCG authentication, please read [this document](../docs/usage/authentication.md#client-credentials-grant). ### Running Tests There are two ways to run tests: #### 1) From XCode First, open the `BoxSDK.xcworkspace` file and select the `BoxSDKIntegrationTests-iOS` scheme (`Product -> Scheme -> BoxSDKIntegrationTests-iOS`). Then run tests by selecting `Product -> Tests`. Make sure you have selected the target simulator before running these tests. #### 2) From command line Before run tests from command line, you should select the target simulator to run these tests on. In my case, I have `XCode 13.2.1` installed with `iOS SDK 15.2` and I want to run tests on iPhone 11 Simulator. So my destination target will be `platform=iOS Simulator,OS=15.2,name=iPhone 11`. ``` xcodebuild -workspace BoxSDK.xcworkspace \ -scheme BoxSDKIntegrationTests-iOS \ -destination "platform=iOS Simulator,OS=15.2,name=iPhone 11" \ -configuration Debug ENABLE_TESTABILITY=YES test ``` --- ## Untitled *Type: page* fastlane documentation Installation Make sure you have the latest version of the Xcode command line tools installed: For fastlane… ## fastlane documentation # Installation Make sure you have the latest version of the Xcode command line tools installed: ``` xcode-select --install ``` For *fastlane* installation instructions, see [Installing *fastlane*](https://docs.fastlane.tools/#installing-fastlane) # Available Actions ## iOS ### ios make_pull_request ``` [bundle exec] fastlane ios make_pull_request ``` Create PR with release changes ### ios make_release ``` [bundle exec] fastlane ios make_release ``` Create new release on github ### ios make_publish_pod ``` [bundle exec] fastlane ios make_publish_pod ``` Publish to version of cocoapods This README.md is auto-generated and will be re-generated every time [*fastlane*](https://fastlane.tools) is run. More information about *fastlane* can be found on [fastlane.tools](https://fastlane.tools). The documentation of *fastlane* can be found on [docs.fastlane.tools](https://docs.fastlane.tools). --- ## Untitled *Type: page* Authentication Authentication Ways to Authenticate Developer Token Server Auth with JWT Traditional 3-Legged OAuth2 Client Credentials Grant… # Authentication [Authentication](#authentication) [Ways to Authenticate](#ways-to-authenticate) - [Developer Token](#developer-token) - [Server Auth with JWT](#server-auth-with-jwt) - [Traditional 3-Legged OAuth2](#traditional-3-legged-oauth2) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) [Token Store](#token-store) [As-User](#as-user) [Token Exchange](#token-exchange) [Revoking Tokens](#revoking-tokens) The Box API uses two flavors of OAuth2 for authentication, both of which can can be difficult to implement. The SDK makes it easier by providing classes that handle obtaining tokens and automatically refreshing them when possible. See the [Auth Types documentation](https://developer.box.com/docs/authentication-types-and-security) for a detailed overview of how the Box API handles authentication and how to choose between the different authentication types. ## Ways to Authenticate ### Developer Token The fastest way to get started using the API is with developer tokens. A developer token is a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for use in production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. The following example creates an SDK client with a developer token: ``` import BoxSDK let client = BoxSDK.getClient(token: "YOUR_DEVELOPER_TOKEN") ``` ### Server Auth with JWT Server auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/docs/service-account) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. JWT Authentication requires a private key for signing the JSON Web Token, which is then exchanged for a valid Box access token that can be used to call the API. It is not secure to store this private key in a mobile app that is publicly distributed, so in order to use JWT Authentication the SDK requires that generation of the access token happens in some other service or process. The SDK can then make a request to that service for access tokens to use. To use the SDK with JWT Auth, you'll need to provide a block of code that is responsible for requesting a new token when one is needed. This block can call out to a web service or other endpoint that is responsible for generating the token. The block receives the unique ID of the user who needs to be authenticated, and a completion function to call with the results of the authentication. ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE") func getTokensFromAuthServer(uniqueID: String, completion: @escaping (Result<AccessTokenTuple, Error>) -> Void) { // Call auth service with unique ID; it passes back the access token and time-to-live (TTL) in seconds completion(.success((accessToken: accessToken, expiresIn: accessTokenTTLinSeconds))) } // Create client with unique ID — note that this can be any value your application understands. The unique // ID is a mechanism for your application to keep track of or map your users to Box sdk.getDelegatedAuthClient(authClosure: getTokensFromAuthServer, uniqueID: "myUser12345") { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` As an alternative, you can call `async` version of `getDelegatedAuthClient(authClosure:uniqueID:)` method: ``` do { let client = try await sdk.getDelegatedAuthClient(authClosure: getTokensFromAuthServer, uniqueID: "myUser12345") // Use client to make API calls } catch { // Handle error creating client } ``` ### Traditional 3-Legged OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/docs/oauth-20). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. The SDK provides a built-in flow for opening a secure web view, into which the user enters their Box login credentials. This requires that the application using the SDK registers itself for a custom URL scheme of the format `boxsdk-<<CLIENT ID>>://boxsdkoauth2redirect`. ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE") sdk.getOAuth2Client() { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` As an alternative, you can call `async` version of `getOAuth2Client()` method: ``` do { let client = try await sdk.getOAuth2Client(tokenStore: KeychainTokenStore()) // Use client to make API calls } catch { // Handle error creating client } ``` If your application requires a custom URL scheme that differs from the default format `boxsdk-<<CLIENT ID>>://boxsdkoauth2redirect`, you have the option to pass in a custom callback URL string when creating the SDK client. This is the URL to which Box will redirect the user when authentication completes. This requires that the application using the SDK registers itself for the same custom callback URL. ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE", callbackURL: "YOUR CALLBACK URL HERE") sdk.getOAuth2Client() { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` ### Client Credentials Grant Server auth with CCG allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account. Obtained token is valid for specified amount of time and it will be refreshed automatically by default. A detailed guide for this process is available in the [Setup with Client Credentials Grant](https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/). #### Obtaining Service Account token By default, your application has a [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID: ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE") sdk.getCCGClientForAccountService(enterpriseId: "YOUR ENTERPRISE ID HERE") { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` As an alternative, you can call `async` version of `getCCGClientForAccountService(enterpriseId:)` method: ``` do { let client = try await sdk.getCCGClientForAccountService(enterpriseId: "YOUR ENTERPRISE ID HERE") // Use client to make API calls } catch { // Handle error creating client } ``` Remember that you can still make calls on behalf of managed users, which are part of your enterprise, by using [As-User](#as-user) behavior. #### Obtaining User token To obtain client for making calls as an App User or Managed User you will have to provide user ID: ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE") sdk.getCCGClientForUser(userId: "YOUR USER ID HERE") { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` As an alternative, you can call `async` version of `getCCGClientForUser(userId:)` method: ``` do { let client = try await sdk.getCCGClientForUser(userId: "YOUR USER ID HERE") // Use client to make API calls } catch { // Handle error creating client } ``` ## Token Store In order to maintain authentication and ensure that your users do not need to log in again every time they use your application, you should persist their token information to some sort of durable store (e.g. the Keychain). The SDK provides a `TokenStore` interface which allows you to read and write tokens to whatever store your application uses at the correct points in the SDK's token handling logic. The interface requires three methods: The SDK provides a default `KeychainTokenStore` implementation that stores the user's tokens on the device Keychain, but you can also create your own custom token store by implementing something that conforms to the `TokenStore` protocol: ``` // The token store constructor should create a specific store instance for the user being authenticated — it may need // to take in a user ID or other unique identifier public protocol TokenStore { // Read the user's tokens from the data store and pass them to the completion func read(completion: @escaping (Result<TokenInfo, Error>) -> Void) // Write the token information to the store. The tokenInfo argument can be serialized for storage. // Call the completion after the write has completed. func write(tokenInfo: TokenInfo, completion: @escaping (Result<Void, Error>) -> Void) // Delete the user's token information from the store, and call the completion after the write. func clear(completion: @escaping (Result<Void, Error>) -> Void) } ``` ## As-User The `As-User` header is used to make API calls from one user account on behalf of another user. This is used by enterprise administrators and Service Accounts to make API calls on behalf of managed users or app users. This requires the API request to contain an `As-User: USER-ID` header with each API call, which the SDK handles automatically. For more details, see the [documentation on As-User](https://developer.box.com/reference#as-user-1). The following examples assume that the `client` has been instantiated with an access token belonging to an admin-role user or Service Account with appropriate privileges to make As-User calls. The `BoxClient#asUser(withId: String)` method clones the client to impersonate a given user. Note that a new client is created, and the original client instance is left unmodified. All calls made with the new instance of client will be made in context of the impersonated user. ``` let asUserClient = client.asUser(withId: "USER ID"); asUserClient.users.getCurrentUser() { result in guard case let .success(user) = result else { print("Could not retrieve user info!") return } print("Call was made as \(user.name) (\(user.login))") } ``` ## Token Exchange You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). To exchange the token held by a client for a new token with only `item_preview` scope, restricted to a single file: ``` client.exchangeToken(scope: ["item_preview"], resource: "https://api.box.com/2.0/files/123456789") { result in guard case let .success(tokenInfo) = result else { print("Error exchanging tokens") return } print("Got new access token: \(tokenInfo.accessToken)") } ``` ## Revoking Tokens Access tokens for a client can be revoked when needed. This removes the client's authentication, and the client can no longer be used after this operation. ``` client.destroy() { result in guard case .success = result else { print("Tokens could not be revoked!") } print("Tokens were successfully revoked") } ``` --- ## Untitled *Type: page* Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. Get Comment Create Comment Update… # Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. - [Get Comment](#get-comment) - [Create Comment](#create-comment) - [Update Comment](#update-comment) - [Delete Comment](#delete-comment) ## Get Comment To retrieve information about a comment, call [`client.comments.get(commentId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CommentsModule.html#/s:6BoxSDK14CommentsModuleC3get9commentId6fields10completionySS_SaySSGSgys6ResultOyAA7CommentCAA0A8SDKErrorCGctF) with the ID of the comment. ``` client.comments.get(commentId: "55555") { (result: Result<Comment, BoxSDKError>) in guard case let .success(comment) = result else { print("Error retrieving comment") return } print("Comment reads: \"\(comment.message)\"") } ``` ## Create Comment To create a comment, call [`client.comments.create(itemId:itemType:message:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CommentsModule.html#/s:6BoxSDK14CommentsModuleC6create6itemId0F4Type7message6fields10completionySS_S2SSaySSGSgys6ResultOyAA7CommentCAA0A8SDKErrorCGctF) with the type and ID of the item to add a comment to, as well as the comment message. ``` client.comments.create( itemId: "11111", itemType: "file", message: "Thanks!" ) { (result: Result<Comment, BoxSDKError>) in guard case let .success(comment) = result else { print("Error creating comment") return } print("Added comment to \(comment.item.name): \"\(comment.message)\"") } ``` ## Update Comment To update a comment, call [`client.comments.update(commentId:message:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CommentsModule.html#/s:6BoxSDK14CommentsModuleC6update9commentId7message6fields10completionySS_SSSaySSGSgys6ResultOyAA7CommentCAA0A8SDKErrorCGctF) with the ID of the comment to update and the properties to update. ``` client.comments.update( commentId: "55555", message: "Updated message" ) { (result: Result<Comment, BoxSDKError>) in guard case let .success(comment) = result else { print("Error updating comment") return } print("Comment message updated") } ``` ## Delete Comment To delete a comment, call [`client.comments.delete(commentId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CommentsModule.html#/s:6BoxSDK14CommentsModuleC6delete9commentId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the comment to delete. ``` client.comments.delete(commentId: "55555") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting comment") return } print("Comment deleted") } ``` --- ## Untitled *Type: page* Collaborations Collaborations are used to share folders and files between users or groups. They also define what permissions a user has for… # Collaborations Collaborations are used to share folders and files between users or groups. They also define what permissions a user has for a folder or file. - [Get Collaboration](#get-collaboration) - [Add Collaboration](#add-collaboration) - [Update Collaboration](#update-collaboration) - [Delete Collaboration](#delete-collaboration) - [Get Pending Collaborations](#get-pending-collaborations) ## Get Collaboration To retrieve a Collaboration record from the API, call [`client.collaborations.get(collaborationId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC3get15collaborationId6fields10completionySS_SaySSGSgys6ResultOyAA13CollaborationCAA0A8SDKErrorCGctF) with the ID of the collaboration. ``` client.collaborations.get(collaborationId: "12345") { (result: Result<Collaboration, BoxSDKError>) in guard case let .success(collaboration) = result else { print("Error retrieving collaboration") return } let collaborator: String switch collaboration.accessibleBy.collaboratorValue { case let .user(user): collaborator = "user \(user.name)" case let .group(group): collaborator = "group \(group.name)" } let itemName: String switch collaboration.item { case let .file(file): itemName = file.name case let .folder(folder): itemName = folder.name case let .webLink(webLink): itemName = webLink.name } print("Collaboration \(collaboration.id) gives \(collaborator) access to \(itemName)") } ``` ## Add Collaboration To add a collaborator to an item, call [`client.collaborations.create(itemType:itemId:role:accessibleBy:accessibleByType:canViewPath:fields:notify:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC6create8itemType0F2Id4role12accessibleBy0jkG011canViewPath6fields6notify10completionySS_SSAA17CollaborationRoleOSSAA010AccessibleK0OSbSgSaySSGSgARys6ResultOyAA0R0CAA0A8SDKErrorCGctF) with the type and ID of the item, as well as the type and ID of the collaborator — a user or a group. A `role` for the collaborator must be specified, which will determine the permissions the collaborator receives on the item. To collaborate a user, pass in a user id and the `.user` accessible by type. ``` client.collaborations.create( itemType: "folder", itemId: "22222", role: .editor, accessibleBy: "33333", accessibleByType: .user ) { (result: Result<Collaboration, BoxSDKError>) in guard case let .success(collaboration) = result else { print("Error creating collaboration") return } print("Collaboration successfully created") } ``` To collaborate a group, pass in a group id and the `.group` accessible by type. ``` client.collaborations.create( itemType: "folder", itemId: "22222", role: .editor, accessibleBy: "44444", accessibleByType: .group ) { (result: Result<Collaboration, BoxSDKError>) in guard case let .success(collaboration) = result else { print("Error creating collaboration") return } print("Collaboration successfully created") } ``` ## Update Collaboration To update a collaboration record, call [`client.users.update(collaborationId:role:status:canViewPath:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC6update15collaborationId4role6status11canViewPath6fields10completionySS_AA17CollaborationRoleOAA0O6StatusOSgSbSgSaySSGSgys6ResultOyAA0O0CAA0A8SDKErrorCGctF) with the ID of the collaboration to update and the properties to update, including at least the `role`. ``` client.collaborations.update(collaborationId: "12345", role: .viewer) { (result: Result<Collaboration, BoxSDKError>) in guard case let .success(collaboration) = result else { print("Error updating collaboration") return } print("Updated collaboration") } ``` ## Delete Collaboration To delete a collaboration, removing the collaborator's access to the relevant item, call [`client.collaborations.delete(collaborationId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC6delete15collaborationId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the collaboration to delete. ``` client.collaborations.delete(collaborationId: "12345") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting collaboration") return } print("Collaboration deleted") } ``` ## Get Pending Collaborations To retrieve a list of the pending collaborations requiring the user to accept or reject them, call [`client.collaborations.listPendingForEnterprise(offset:limit:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC24listPendingForEnterprise6offset5limit6fields10completionySiSg_AISaySSGSgys6ResultOyAA14PagingIteratorCyAA13CollaborationCGAA0A8SDKErrorCGctF). The method returns an iterator, which is used to get pending collaborations. ``` let iterator = client.collaborations.listPendingForEnterprise() iterator.next { result in switch result { case let .success(page): for collaboration in page.entries { print("Collaboration created by \(collaboration.createdBy?.name)") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Configuration The iOS SDK provides dedicated method, that helps you to customize SDK configuration. All you need is to call sdk… # Configuration The iOS SDK provides dedicated method, that helps you to customize SDK configuration. All you need is to call [`sdk.updateConfiguration(apiBaseURL:uploadApiBaseURL:oauth2AuthorizeURL:maxRetryAttempts:tokenRefreshThreshold:consoleLogDestination:fileLogDestination:clientAnalyticsInfo:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxSDK.html#/s:6BoxSDKAAC19updateConfiguration10apiBaseURL09uploadApifG0015oauth2AuthorizeG016maxRetryAttempts21tokenRefreshThreshold21consoleLogDestination04filesT019clientAnalyticsInfoy10Foundation0G0VSg_A2OSiSgSdSgAA07ConsolesT0CSgAA04FilesT0CSgAA06ClientwX0VSgtKF) method on `BoxSDK` instance with correct parameters, right after creating a `BoxSDK` instance, but before creating a `BoxClient`. [URLs configuration](#urls-configuration) - [Api Base URL](#api-base-url) - [Upload Api Base URL](#upload-api-base-url) - [OAuth Authorize URL](#oauth-authorize-url) [Max retry attempts](#max-retry-attempts) [Token Refresh Threshold](#token-refresh-threshold) [Logging](#logging) - [Console Logging](#console-logging) - [File Logging](#file-logging) [Client Analytics Info](#client-analytics-info) ## URLs configuration The `sdk.updateConfiguration()` method allows you to change base URLs from defaults to the ones you will specify. Just call this method on the `BoxSDK` instance with any of these parameters: ``` do { try sdk.updateConfiguration( apiBaseURL: URL(string: "https://my-company.com"), uploadApiBaseURL: URL(string: "https://my-company.com/upload"), oauth2AuthorizeURL: URL(string: "https://my-company.com/oauth2") ) } catch { print("An error occurred \(error)") } ``` The `updateConfiguration()` will throw an exception if any of passed URLs will be invalid. ### Api Base URL The `apiBaseURL` sets URL to which all API calls will be directed. Final URL that is used to access Box is built using `apiBaseURL` and the API Version (`2.0`). For example, by default the `apiBaseURL` is set to `https://api.box.com`, so after appending the currently supported API version the URL is : `https://api.box.com/2.0`. ### Upload Api Base URL The `uploadApiBaseURL` is used to configure the base URL used when uploading files. Final URL used to access Box is built using `uploadApiBaseURL`, the `/api/` path and API Version (`2.0`). For example, by default the `uploadApiBaseURL` is set to `https://upload.box.com`, so after appending `/api/` path and the currently supported API version the URL is : `https://upload.box.com/api/2.0`. ### OAuth Authorize URL The `oauth2AuthorizeURL` is an URL for the OAuth2 authorization page, where users are redirected to enter their credentials to obtain OAuth2 authorization tokens. By default is set to `https://account.box.com/api/oauth2/authorize`. ## Max retry attempts The default maximum number of retries in case of failed API call is `5`. To change this please call `sdk.updateConfiguration()` method with `maxRetryAttempts` parameter and your new value e.g. `10`: ``` do { try sdk.updateConfiguration( maxRetryAttempts: 10 ) } catch { print("An error occurred \(error)") } ``` ## Token Refresh Threshold You can specify how many seconds before the token expires, it should be refreshed. By default it is set to `60` seconds. To change this value, please call `sdk.updateConfiguration()` method with `tokenRefreshThreshold` parameter and your new value, e.g. `120`: ``` do { try sdk.updateConfiguration( tokenRefreshThreshold: 120 ) } catch { print("An error occurred \(error)") } ``` ## Logging ### Console Logging There could be a situation when the default console Box SDK logging is not sufficient for your needs. You can then create your own class that inherits form [`ConsoleLogDestination`](https://opensource.box.com/box-ios-sdk/Classes/ConsoleLogDestination.html) class and you can overwrite `write` method for you needs (as this is a method that writes logs into the console). If you named this class e.g. `CustomConsoleLogDestination` then call: ``` do { try sdk.updateConfiguration( consoleLogDestination: CustomConsoleLogDestination() ) } catch { print("An error occurred \(error)") } ``` ### File Logging By default, logging to a file is disabled in the Box SDK. To turn it on, you just need to pass the `fileLogDestination` parameter to the new instance of [`FileLogDestination`](https://opensource.box.com/box-ios-sdk/Classes/FileLogDestination.html). To create a new instance of `FileLogDestination`, you need to pass the `fileURL` parameter, which is the file path URL to write the logs to. ``` let fileLoggerURL = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask).first!.appendingPathComponent("box_sdk_log.txt") do { try sdk.updateConfiguration( fileLogDestination: FileLogDestination(fileURL: fileLoggerURL) ) } catch { print("An error occurred \(error)") } ``` ## Client Analytics Info If for some reasons you want to track your application usage on server, there is a way for that. You just need to create an instance of [`ClientAnalyticsInfo`](https://opensource.box.com/box-ios-sdk/Structs/ClientAnalyticsInfo.html) struct with `appName` and `appVersion` parameters related to your app and pass it to `sdk.updateConfiguration()` method. Those values will be added to `X-Box-UA` request header after `agent` and `env` values. Take a look at the following code: ``` let analyticsInfo = ClientAnalyticsInfo(appName: "MyCustomApp", appVersion: "1.2.0") do { try sdk.updateConfiguration(clientAnalyticsInfo: analyticsInfo) } catch { print("An error occurred \(error)") } ``` After this change, the `client=MyCustomApp/1.2.0` will be appended to the `X-Box-UA` request header value. If you run this code on `iPhone 11 Pro Max` and using SDK version `5.2.0` the final value for `X-Box-UA` header will be `agent=box-swift-sdk/5.2.0; env=iPhone Simulator/15.2; client=MyCustomApp/1.2.0`. --- ## Untitled *Type: page* Device Pins Get Device Pin Info Get Device Pins for Enterprise Delete Device Pin Get Device Pin Info To retrieve information about a device… # Device Pins - [Get Device Pin Info](#get-device-pin-info) - [Get Device Pins for Enterprise](#get-device-pins-for-enterprise) - [Delete Device Pin](#delete-device-pin) ## Get Device Pin Info To retrieve information about a device pin, call [`client.devicepins.get(devicePinId: String, fields: [String]?, completion: @escaping Callback<DevicePin>)`](https://opensource.box.com/box-ios-sdk/Classes/DevicePinsModule.html#/s:6BoxSDK16DevicePinsModuleC3get11devicePinId6fields10completionySS_SaySSGSgys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the device pin. You can control which fields are returned on the resulting `Device Pin` object by passing the desired field names in the optional `fields` parameter. ``` client.devicePins.get(devicePinId: "11111", fields: ["product_name"]) { (result: Result<DevicePin, BoxSDKError>) in guard case let .success(devicePin) = result else { print("Error retrieving device pin information") return } print("Device Pin for \(devicePin.productName) was created at \(devicePin.createdAt)") } ``` ## Get Device Pins for Enterprise To retrieve information about the device pins active for the enterprise, call [`client.devicePins.listForEnterprise(enterpriseId: String, marker: String?, limit: Int?, direction: OrdeDirection?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/DevicePinsModule.html#/s:6BoxSDK16DevicePinsModuleC17listForEnterprise12enterpriseId6marker5limit9direction6fields10completionySS_SSSgSiSgAA14OrderDirectionOSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0C3PinCGAA0A8SDKErrorCGctF) with the ID of the enterpise. This method will return an iterator, which is used to retrieve device pins for the enterprise. ``` let iterator = client.devicePins.listForEnterprise(enterpriseId: "12345", direction: .ascending) iterator.next { results in switch results { case let .success(page): for devicePin in page.entries { print("Device type: \(devicePin.productName)") } case let .failure(error): print(error) } } ``` ## Delete Device Pin To delete a device pin, call [`client.devicePins.delete(devicePinId: String, completion: @escaping: Callback<Void>)`](https://opensource.box.com/box-ios-sdk/Classes/DevicePinsModule.html#/s:6BoxSDK16DevicePinsModuleC6delete11devicePinId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the device pin to delete. ``` client.devicePins.delete(devicePinId: "12345") { result: Result<Void, BoxSDKError> in guard case .success = result else { print("Error deleting device pin") return } print("Device Pin successfully deleted") } ``` --- ## Untitled *Type: page* File Requests File request objects represent a file request associated with a folder. Get a File Request's Information Copy a File Request's… # File Requests File request objects represent a file request associated with a folder. - [Get a File Request's Information](#get-a-file-requests-information) - [Copy a File Request's Information](#copy-a-file-requests-information) - [Update a File Request's Information](#update-a-file-requests-information) - [Delete a File Request](#delete-a-file-request) ## Get a File Request's Information To retrieve information about a file request, call [`client.fileRequests.get(fileRequestId::completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FileRequestsModule.html#/s:6BoxSDK18FileRequestsModuleC3get13fileRequestId10completionySS_ys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the file request. ``` client.fileRequests.get(fileRequestId: "123456") { result in guard case let .success(fileRequest) = result else { print("Error getting file request") return } print("File request title: \(fileRequest.title ?? "n/a"), description: \(fileRequest.description ?? "n/a")") } ``` ## Copy a File Request's Information To copy an existing file request that is already present on one folder, and applies it to another folder, call [`client.fileRequests.copy(fileRequestId:copyRequest:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FileRequestsModule.html#/s:6BoxSDK18FileRequestsModuleC4copy13fileRequestId0fH010completionySS_AA0ch4CopyH0Vys6ResultOyAA0cH0CAA0A8SDKErrorCGctF). You must provide the ID of file request you want to copy, and an instance of the [`FileRequestCopyRequest`](https://opensource.box.com/box-ios-sdk/Structs/FileRequestCopyRequest.html#/s:6BoxSDK015FileRequestCopyD0V5titleSSSgvp) class, where you can set fields to replace fields from source file request. ``` let destinationFolder = FolderEntity(id: "33333") let copyRequest = FileRequestCopyRequest( title: "New file request title", description: "New file request description", isEmailRequired: true, isDescriptionRequired: false, folder: destinationFolder ) client.fileRequests.copy(fileRequestId: "123456", copyRequest: copyRequest) { result in guard case let .success(fileRequest) = result else { print("Error copying file request") return } print("Copied file request title: \(fileRequest.title ?? "n/a"), description: \(fileRequest.description ?? "n/a")") } ``` ## Update a File Request's Information To update a file request, call [`client.fileRequests.update(fileRequestId:ifMatch:updateRequest:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FileRequestsModule.html#/s:6BoxSDK18FileRequestsModuleC6update13fileRequestId7ifMatch0fH010completionySS_SSSgAA0ch6UpdateH0Vys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the file request and with an instance of the [`FileRequestUpdateRequest`](https://opensource.box.com/box-ios-sdk/Structs/FileRequestUpdateRequest.html) class, where you can set fields you want to update. If you want to make sure that an item hasn't changed recently before making changes, you can pass the last observed `etag` value to the `ifMatch` parameter. This call can be used to activate or deactivate a file request. ``` let updateRequest = FileRequestUpdateRequest( title: "Updated file request title", description: "Updated file request description", status: .inactive, isEmailRequired: false, isDescriptionRequired: true ) client.fileRequests.update(fileRequestId: "123456", updateRequest: updateRequest) { result in guard case let .success(fileRequest) = result else { print("Error updating file request") return } print("Updated file request title: \(fileRequest.title ?? "n/a"), description: \(fileRequest.description ?? "n/a")") } ``` ## Delete a File Request To delete a file request permanently, call [`client.fileRequests.delete(fileRequestId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FileRequestsModule.html#/s:6BoxSDK18FileRequestsModuleC6delete13fileRequestId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file request to delete. ``` client.fileRequests.delete(fileRequestId: "123456") { result in guard case .success = result else { print("Error removing file request") return } print("File request removed") } ``` --- ## Untitled *Type: page* Custom API Calls There are a few situations, where a user might want to make a custom API call — utilizing the SDK's authentication handling… # Custom API Calls There are a few situations, where a user might want to make a custom API call — utilizing the SDK's authentication handling, but creating the API request manually: - When new endpoints and parameters have been introduced to the API, but they are not yet supported directly by the SDK - Beta endpoints, that are not yet suitable for inclusion in the SDK - Hitting URLs specified directly in the response of another API call, e.g. Representation Info and Download URLs For these reasons BoxClient exposes this functionality through a set of methods on the client mapping to HTTP verbs: ``` client.get(/*...*/) client.post(/*...*/) client.put(/*...*/) client.delete(/*...*/) client.options(/*...*/) ``` and additionally a HTTP GET method call for downloading: ``` client.download(/*...*/) ``` Moreover, the SDK exposes a low-level method that is used under the hood by the all previous methods. However because of its complexity, we recommend that you should only use this method if all the other options do not suit your needs. ``` client.send(/*...*/) ``` [Custom API Calls](#custom-api-calls) - [Create URL](#create-url) - [Deserialize Response Body](#deserialize-response-body) [API Calls](#api-calls) - [Custom GET](#custom-get) - [Custom POST](#custom-post) - [Custom PUT](#custom-put) - [Custom DELETE](#custom-delete) - [Custom OPTIONS](#custom-options) - [Download](#download) - [Send](#send) ## Create URL When you want to execute custom API call, you must specify a destination URL. You can create it by yourself: ``` let fileId = "<YOUR_FILE_ID_HERE>" let url = URL(string: "https://api.box.com/2.0/files/\(fileId)")! ``` or you can use SDK's predefined method: [`URL.boxAPIEndpoint(_ endpoint:configuration)`](https://opensource.box.com/box-ios-sdk/Extensions/URL.html#/s:10Foundation3URLV6BoxSDKE14boxAPIEndpoint_13configurationACSS_AD0C16SDKConfigurationVtFZ) ``` let fileId = "<YOUR_FILE_ID_HERE>" let url = URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration) ``` The `boxAPIEndpoint` method requires to pass an endpoint path and configuration from the current `BoxClient` instance. It internally fetches `apiBaseURL` and appends to it the endpoint path you passed. The default value of `apiBaseURL` is `https://api.box.com`, but you can change it with [`sdk.updateConfiguration(apiBaseURL:uploadApiBaseURL:oauth2AuthorizeURL:maxRetryAttempts:tokenRefreshThreshold:consoleLogDestination:fileLogDestination:clientAnalyticsInfo:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxSDK.html#/s:6BoxSDKAAC19updateConfiguration10apiBaseURL09uploadApifG0015oauth2AuthorizeG016maxRetryAttempts21tokenRefreshThreshold21consoleLogDestination04filesT019clientAnalyticsInfoy10Foundation0G0VSg_A2OSiSgSdSgAA07ConsolesT0CSgAA04FilesT0CSgAA06ClientwX0VSgtKF) method. ## Deserialize Response Body All exposed custom API methods return a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) object or an error if request fails. The `BoxResponse` type has a `body` property of type `Data?`. If you want to deserialize its json content to specific custom type, you can use SDK's [`ObjectDeserializer.deserialize(data:)`](https://opensource.box.com/box-ios-sdk/Enums/ObjectDeserializer.html#/s:6BoxSDK18ObjectDeserializerO11deserialize4datas6ResultOyxAA0A8SDKErrorCG10Foundation4DataVSg_tAA0A5ModelRzlFZ) method to deserialize `Data?` to any type that conforms to `BoxModel`, or [`ObjectDeserializer.deserialize(response:)`](https://opensource.box.com/box-ios-sdk/Enums/ObjectDeserializer.html#/s:6BoxSDK18ObjectDeserializerO11deserialize8responses6ResultOyxAA0A8SDKErrorCGAA0A8ResponseV_tSeRzlFZ) to deserialize `BoxResponse` to any type that conforms to `Decodable`. ``` let fileId = "<YOUR_FILE_ID_HERE>" client.get(url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration)) { (result: Result<BoxResponse, BoxSDKError>) in let fileResult: Result<File, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body)} switch fileResult { case .success(let file): print("File \(file.name) was created at \(file.createdAt)") case .failure(let error): print("Error retrieving file information") } } ``` As you can see, we are using `flatMap` operator on `Result` type to deserialize origin `body` to the specific type, which is `File` in our case. The [`ObjectDeserializer.deserialize(data: Data?)`](https://opensource.box.com/box-ios-sdk/Enums/ObjectDeserializer.html#/s:6BoxSDK18ObjectDeserializerO11deserialize4datas6ResultOyxAA0A8SDKErrorCG10Foundation4DataVSg_tAA0A5ModelRzlFZ) method returns `Result<ReturnType, BoxSDKError>`, where `ReturnType` is inferenced as a `File`. ## API Calls ### Custom GET To perform a custom HTTP GET method, call [`client.get(url:httpHeaders:queryParameters:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC3get3url11httpHeaders15queryParameters10completiony10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the destination `url` and with headers or query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. If you want to deserialize it to a specific type, you can do so as in the example below: ``` let fileId = "<YOUR_FILE_ID_HERE>" // Get information about a file. client.get(url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration)) { (result: Result<BoxResponse, BoxSDKError>) in let fileResult: Result<File, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body)} switch fileResult { case .success(let file): print("File \(file.name) was created at \(file.createdAt)") case .failure(let error): print("Error retrieving file information") } } ``` As an alternative, to manually deserialize a response body, you can use [`ResponseHandler.default(wrapping completion:)`](https://opensource.box.com/box-ios-sdk/Enums/ResponseHandler.html#/s:6BoxSDK15ResponseHandlerO7default8wrappingys6ResultOyAA0aC0VAA0A8SDKErrorCGcyAGyxAKGc_tAA0A5ModelRzlFZ) method: ``` let fileId = "<YOUR_FILE_ID_HERE>" // Get information about a file. client.get( url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration), completion: ResponseHandler.default( wrapping: { (result: Result<File, BoxSDKError>) in switch result { case .success(let file): print("File \(file.name) was created at \(file.createdAt)") case .failure(let error): print("Error retrieving file information") } } ) ) ``` This method will make sure that the response is successful (status code 2xx) and will deserialize the response body into the appropriate type. In these examples above, we used existing SDKs type `File`, but this can be replaced with any custom type that conforms to either `Decodable` or `BoxModel`. ### Custom POST To perform a custom HTTP POST method, call [`client.post(url:httpHeaders:queryParameters:json:completion)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC4post3url11httpHeaders15queryParameters4json10completiony10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGypSgys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the `url`, `json` body and with headers or query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. If you want to deserialize it to a specific type, you can do so as shown in the examples below: ``` var body: [String: Any] = [:] body["parent"] = ["id": "<YOUR_FOLDER_ID_HERE>"] body["url"] = "https://example.com" body["name"] = "example name" // Creates a new web link with the specified url on the specified folder. client.post(url: URL.boxAPIEndpoint("/2.0/web_links", configuration: client.configuration), json: body) { result in let webLinkResult: Result<WebLink, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) } switch webLinkResult { case .success(let webLink): print("WebLink \(webLink.name) was created") case .failure(let error): print("Error creating a webLink \(error)") } } ``` or ``` var body: [String: Any] = [:] body["parent"] = ["id": "<YOUR_FOLDER_ID_HERE>"] body["url"] = "https://example.com" body["name"] = "example name" // Creates a new web link with the specified url on the specified folder. client.post( url: URL.boxAPIEndpoint("/2.0/web_links", configuration: client.configuration), json: body, completion: ResponseHandler.default( wrapping: { (result: Result<WebLink, BoxSDKError>) in switch result { case .success(let webLink): print("WebLink \(webLink.name) was created") case .failure(let error): print("Error creating a webLink \(error)") } } ) ) ``` In these examples we deserialized `body` as `WebLink` type, but you can deserialize response's body to any custom type that conforms to either `Decodable` or `BoxModel`. ### Custom PUT To perform a custom HTTP PUT method, call [`client.put(url:httpHeaders:queryParameters:json:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC3put3url11httpHeaders15queryParameters4json10completiony10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGypSgys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the `url`, `json` body and with headers or query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. If you want to deserialize it to a specific type, you can do so as shown in the examples below: ``` let taskId = "<YOUR_TASK_ID_HERE>" var body = [String: Any]() body["message"] = "Please to this ASAP!" body["action"] = "review" // Updates a specific task. client.put(url: URL.boxAPIEndpoint("/2.0/tasks/\(taskId)", configuration: client.configuration), json: body) { result in let taskResult: Result<Task, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) } switch taskResult { case .success(let task): print("Task \(task.id) was updated") case .failure(let error): print("Error updating a task \(error)") } } ``` or ``` let taskId = "<YOUR_TASK_ID_HERE>" var body = [String: Any]() body["message"] = "Please to this ASAP!" body["action"] = "review" // Updates a specific task. client.put( url: URL.boxAPIEndpoint("/2.0/tasks/\(taskId)", configuration: client.configuration), json: body, completion: ResponseHandler.default( wrapping: { (result: Result<Task, BoxSDKError>) in switch result { case .success(let task): print("Task \(task.id) was updated") case .failure(let error): print("Error updating a task \(error)") } } ) ) ``` In these examples we deserialized `body` as `Task` type, but we can deserialize it to any custom type that conforms to either `Decodable` or `BoxModel`. ### Custom DELETE To perform a custom HTTP DELETE method, call [`client.delete(url:httpHeaders:queryParameters:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC6delete3url11httpHeaders15queryParameters10completiony10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the `url` and with headers and query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. In most cases the `body` property on success will be just nil, so to handle this you can do as follows: ``` let fileId = "<YOUR_FILE_ID_HERE>" // Discards a file to the trash. client.delete(url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration)) { result in switch result { case .success: print("The file was deleted") case .failure(let error): print("Error deleting a file \(error)") } } ``` ### Custom OPTIONS To perform a custom HTTP OPTIONS method, call [`client.options(url:httpHeaders:queryParameters:json:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC7options3url11httpHeaders15queryParameters4json10completionAA0A11NetworkTaskC10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGypSgys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the `url`, `json` body and with headers or query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. ``` var body: [String: Any] = ["parent": ["id": "<YOUR_FOLDER_ID_HERE>"]] body["name"] = "<YOUR_FILE_NAME_HERE>" // Verifies that new file will be accepted by Box before you send all the bytes over the wire. client.options(url: URL.boxAPIEndpoint("/2.0/files/content", configuration: client.configuration)) { result in switch result { case .success: print("The file is verified successfully") case .failure(let error): print("Error verifying a file \(error)") } } ``` This example will return an empty response when the checks pass or an error when the checks fail. In case of an empty response, the user can proceed with making an upload call. ### Download To perform a HTTP GET method call for downloading on the API, call [`client.download(url:downloadDestinationURL:httpHeaders:queryParameters:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC7options3url11httpHeaders15queryParameters4json10completionAA0A11NetworkTaskC10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGypSgys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF). You must specify `url` of the API endpoint to call `downloadDestinationURL`, which specifies the URL on a disk, where the data will be saved. The `completion` is a callback, which returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) object or an error if request fails. Headers and query parameters are optional, so add them if needed. ``` let fileId = "<YOUR_FILE_ID_HERE>" let destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("<FILE_NAME_HERE>") // Download a file to a specified folder. client.download( url: URL.boxAPIEndpoint("/2.0/files/\(fileId)/content", configuration: client.configuration), downloadDestinationURL: destinationURL ) { result in switch result { case .success: print("The file was downloaded") case .failure(let error): print("Error downloaded a file \(error)") } } ``` This example will return an empty response on success or an error on failure. ### Send To perform a send method, call [`client.send(request:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC4send7request10completionyAA0A7RequestC_ys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the [`request`](https://opensource.box.com/box-ios-sdk/Classes/BoxRequest.html#/s:6BoxSDK0A7RequestC10httpMethod3url0D7Headers11queryParams4body19downloadDestination4task8progressAcA10HTTPMethodO_10Foundation3URLVSDyS2SGSDySSAA25QueryParameterConvertible_pSgGAC8BodyTypeOAPSgySo16NSURLSessionTaskCcySo10NSProgressCctcfc) object, which represents the Box SDK API request. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. When creating a `BoxRequest` instance, please call [`init(httpMethod:url:httpHeaders:queryParams:body:downloadDestination:task:progress:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxRequest.html#/s:6BoxSDK0A7RequestC10httpMethod3url0D7Headers11queryParams4body19downloadDestination4task8progressAcA10HTTPMethodO_10Foundation3URLVSDyS2SGSDySSAA25QueryParameterConvertible_pSgGAC8BodyTypeOAPSgySo16NSURLSessionTaskCcySo10NSProgressCctcfc) with the parameters you need, leaving unused parameters with their default value. Below is an example of how we can use `send()` method to update a particular file: ``` let fileId = "<YOUR_FILE_ID_HERE>" var body: [String: Any] = [:] body["name"] = "new_file_name.txt" body["description"] = "new description" let request = BoxRequest( httpMethod: .put, url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration), queryParams: ["fields": "name,description"], body: .jsonObject(body) ) client.send(request: request) { result in let fileResult: Result<File, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) } switch fileResult { case let .success(fileItem): print("The file was updated successfully") case let .failure(error): print("Error updating a file \(error)") } } ``` This is an another example showing the use of the `send()` method to download a file: ``` let fileId = "<YOUR_FILE_ID_HERE>" let filename = "<YOUR_DESTINATION_FILE_NAME>" let destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(filename) let task = BoxDownloadTask() let request = BoxRequest( httpMethod: .get, url: URL.boxAPIEndpoint("/2.0/files/\(fileId)/content", configuration: client.configuration), downloadDestination: destinationURL, task: task.receiveTask, progress: { progress in let completed = String(format: "%.2f", progress.fractionCompleted * 100) print("Completed... \(completed)%") } ) client.send(request: request) { result in switch result { case .success: print("The file was downloaded") case let .failure(error): print("Error downloaded a file \(error)") } } // If you want to cancel downloading a file, please call `task.cancel()` method. ``` --- ## Untitled *Type: page* Groups Groups contain a set of users and can be used in place of users in some operations such as collaborations. Create Group Update Group… # Groups Groups contain a set of users and can be used in place of users in some operations such as collaborations. - [Create Group](#create-group) - [Update Group](#update-group) - [Get Group Info](#get-group-info) - [Get Enterprise Groups](#get-enterprise-groups) - [Delete Group](#delete-group) [Group Membership](#group-membership) - [Get Group Membership Info](#get-group-membership-info) - [Create Group Membership](#create-group-membership) - [Update Group Membership](#update-group-membership) - [Delete Group Membership](#delete-group-membership) - [Get Memberships for Group](#get-memberships-for-group) - [Get Memberships for User](#get-memberships-for-user) - [Get Collaborations for Group](#get-collaborations-for-group) ## Create Group To create a new group, call [`client.groups.create(name: String, provenance: String?, externalSyncIdentifier: String?, description: String?, invitabilityLevel: GroupInvitabilityLevel?, memberViewabilityLevel: GroupMemberViewabilityLevel, fields: [String]?, completion: @escaping Callback<Group>)`][create_group] with the name of the group you wish to create. You can control which fields are returned in the resulting `Group` object by passing the `fields` parameter. ``` client.groups.create(name: "Team A", provenance: "Test", externalSyncIdentifier: "Test Sync", description: "Test Description", invitabilityLevel: .allManagedUsers, memberViewabilityLevel: .allManagedUsers) { (result: Result<Group, BoxSDKError>) in guard case let .success(group) = result else { print("Error creating new group") return } print("Group \(group.name) was created") } ``` ## Update Group To update an existing group, call [`client.groups.update(groupId: String, name: String?, provenance: NullableParameter<String>?, externalSyncIdentifier: NullableParameter<String>?, description: NullableParameter<String>?, invitabilityLevel: GroupInvitabilityLevel?, memberViewabilityLevel: GroupMemberViewabilityLevel?, fields: [String]?, completion: @escaping Callback<Group>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC6update7groupId4name10provenance22externalSyncIdentifier11description17invitabilityLevel017memberViewabilityO06fields10completionySS_SSSgAA17NullableParameterOySSGSgA2rA017GroupInvitabilityO0OSgAA0v6MemberqO0OSgSaySSGSgys6ResultOyAA0V0CAA0A8SDKErrorCGctF) with the ID of the group. You can control which fields are returned in the resulting `Group` object by passing the `fields` parameter. ``` client.groups.update(groupId: "11111", name: "Team A", provenance: .value("Test"), externalSyncIdentifier: .value("Test Sync"), description: .value("Test Description"), invitabilityLevel: .allManagedUsers, memberViewabilityLevel: .allManagedUsers) { (result: Result<Group, BoxSDKError>) in guard case let .success(group) = result else { print("Error updating the group") return } print("Group \(group.name) was updated with description: \(group.description)") } ``` ## Get Group Info To retrieve information about a group, call [`client.groups.get(groupId: String, fields: [String]?, completion: @escaping Callback<Group>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC3get7groupId6fields10completionySS_SaySSGSgys6ResultOyAA5GroupCAA0A8SDKErrorCGctF) with the ID of the group. You can control which fields are returned in the resulting `Group` object by passing the `fields` parameter. ``` client.groups.get(groupId: "12345") { (result: Result<Group, BoxSDKError>) in guard case let .success(group) = result else { print("Error getting group information") return } print("Group with name \(group.name) was retrieved.") } ``` ## Get Enterprise Groups To retrieve information about the groups within the enterprise, call [`client.groups.listForEnterprise(name: String?, offset: Int?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC17listForEnterprise4name6offset5limit6fields10completionySSSg_SiSgAKSaySSGSgys6ResultOyAA14PagingIteratorCyAA5GroupCGAA0A8SDKErrorCGctF). You can also pass in a `name` paramter to act as a filter. This method will return an iterator object, which is used to retrieve groups in the enterprise. ``` let iterator = client.groups.listForEnterprise() iterator.next { results in switch results { case let .success(page): for group in page.entries { print("Group with name \(group.name) retrieved") } case let .failure(error): print(error) } } ``` ## Delete Group To delete a group, call [`client.groups.delete(groupId: String, completion: @escaping Callback<Void>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC6delete7groupId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the group to delete. ``` client.groups.delete(groupId: "12345") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting group") return } print("Group was successfully deleted.") } ``` # Group Membership ## Get Group Membership Info To retrieve information about a specified group membership, call [`client.groups.getMembershipInfo(membershipId: String, fields: [String]?, completion: @escaping Callback<GroupMembership>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC17getMembershipInfo12membershipId6fields10completionySS_SaySSGSgys6ResultOyAA05GroupF0CAA0A8SDKErrorCGctF) with the ID of the group membership. You can control which fields are returned on the resulting `Group Membership` object by passing the desired field names in the optional `fields` parameter. ``` client.groups.getMembershipInfo(membershipId: "12345") { (result: Result<GroupMembership, BoxSDKError>) in guard case let .success(membership) = result else { print("Error retrieving group membership information") return } print("Group Membership for group \(membership.group?.name) was retrieved") } ``` ## Create Group Membership To create a new group membership, call [`client.groups.createMembership(userId: String, groupId: String, role: GroupRole?, configurablePermission: NullableParameter<ConfigurablePermissionData>?, fields: [String]?, completion: @escaping Callback<GroupMembership>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC16createMembership6userId05groupH04role22configurablePermission6fields10completionySS_SSAA9GroupRoleOSgAA17NullableParameterOyAA012ConfigurableL4DataVGSgSaySSGSgys6ResultOyAA0oF0CAA0A8SDKErrorCGctF). You can control which fields are returned on the resulting `Group Membership` object by passing the desired field names in the optional `fields` parameter. ``` client.createMembership(userId: "54321", groupId: "11111", role: .admin, configurablePermission: .value(ConfigurablePermissionData(canRunReports: true, canInstantLogin: true, canCreateAccounts: false, canEditAccounts: true))) { (result: Result<GroupMembership, BoxSDKError>) in guard case let .success(membership) = result else { print("Error creating group membership") return } print("Group membership for group \(membership.group?.name) was created") } ``` ## Update Group Membership To update an existing group membership, call [`client.groups.updateMembership(membershipId: String, role: GroupRole?, configurablePermission: NullableParameter<ConfigurablePermissionData>?, fields: [String]?, completion: @escaping Callback<GroupMembership>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC16updateMembership12membershipId4role22configurablePermission6fields10completionySS_AA9GroupRoleOSgAA17NullableParameterOyAA012ConfigurableK4DataVGSgSaySSGSgys6ResultOyAA0nF0CAA0A8SDKErrorCGctF) with the ID of the group membership to update. ``` client.groups.updateMembership(membershipId: "12345", role: .admin, configurablePermission: .value(ConfigurablePermissionData(canRunReports: true, canInstantLogin: true, canCreateAccounts: false, canEditAccounts: true))) { (result: Result<GroupMembership, BoxSDKError>) in guard case let .success(membership) = result else { print("Error updating group membership") return } print("Group membership with ID \(membership.id) was updated") } ``` ## Delete Group Membership To delete a group membership, call [`client.groups.deleteMembership(membershipId: String, completion: @escaping: Callback<Void>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC16deleteMembership12membershipId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the group membership to delete. ``` client.groups.deleteMembership(membershipId: "12345") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting group membership") return } print("Group Membership was successfully deleted.") } ``` ## Get Memberships for Group To retrieve information about the memberships in a group, call [`client.groups.listMemberships(groupID: String, offset: Int?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC15listMemberships7groupId6offset5limit6fields10completionySS_SiSgAJSaySSGSgys6ResultOyAA14PagingIteratorCyAA15GroupMembershipCGAA0A8SDKErrorCGctF) with the ID of the group to retrieve group memberships for. This method will return an iterator object, which is used to retrieve the memberships. ``` let iterator = client.groups.listMembership(groupId: "12345") iterator.next { result in switch results { case let .success(page): for membership in page.entries { print("Group Membership with ID \(membership.id) was retrieved") } case let .failure(error): print(error) } } ``` ## Get Memberships for User To retrieve information about the group memberships for a given user, call [`client.groups.listMembershipsForUser(userId: String, offset: Int?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC22listMembershipsForUser6userId6offset5limit6fields10completionySS_SiSgAJSaySSGSgys6ResultOyAA14PagingIteratorCyAA15GroupMembershipCGAA0A8SDKErrorCGctF) with the ID of the user to retreive group memberships for. This method will return an iterator object, which is used to retrieve the memberships. ``` let iterator = client.groups.listMembershipsForUser(userId: "12345") iterator.next { result in switch results { case let .success(page): for membership in page.entries { print("Group Membership with ID \(membership.id) was retrieved") } case let .failure(error): print(error) } } ``` ## Get Collaborations for Group To retrieve all group collaborations for a given group, call [`client.groups.listCollaborations(groupId: String, offset: Int?, limit: Int? fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC18listCollaborations7groupId6offset5limit6fields10completionySS_SiSgAJSaySSGSgys6ResultOyAA14PagingIteratorCyAA13CollaborationCGAA0A8SDKErrorCGctF) with the ID of the group to retrieve collaborations for. This method will return an iterator object, which is used to retrieve the collaborations. ``` let iterator = client.groups.listCollaborations(groupId: "12345") iterator.next { results in switch results { case let .success(page): for collaboration in page.entries { print("Collaboration with ID \(collaboration.id) was retrieved") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other… # Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other common file operations (move, copy, delete, etc.). - [Get File Info](#get-file-info) - [Update File](#update-file) - [Upload File](#upload-file) - [Upload New File Version](#upload-new-file-version) - [Download File](#download-file) - [Copy File](#copy-file) - [Lock File](#lock-file) - [Unlock File](#unlock-file) - [Get File Thumbnail Image](#get-file-thumbnail-image) - [Get File Embed Link](#get-file-embed-link) - [Get File Collaborations](#get-file-collaborations) - [Get File Comments](#get-file-comments) - [Get File Tasks](#get-file-tasks) - [Add File to Favorites](#add-file-to-favorites) - [Remove File from Favorites](#remove-file-from-favorites) - [Get Shared Link](#get-shared-link) - [Set Shared Link](#set-shared-link) - [Remove Shared Link](#remove-shared-link) - [List Representations](#list-representations) - [Download Zip](#download-zip) ## Get File Info To retrieve information about a file, call [`client.files.get(fileId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC3get6fileId6fields10completionySS_SaySSGSgys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. You can control which fields are returned on the resulting `File` object by passing the desired field names in the optional `fields` parameter. ``` client.files.get(fileId: "11111", fields: ["name", "created_at"]) { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error retrieving file information") return } print("File \(file.name) was created at \(file.createdAt)") } ``` ## Update File To update a file record, call [`client.files.updateFileInfo(fileId:name:description:parentId:sharedLink:tags:collections:lock:dispositionAt:ifMatch:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC6update6fileId4name11description06parentG010sharedLink4tags11collections4lock13dispositionAt7ifMatch6fields10completionySS_SSSgA2qA17NullableParameterOyAA06SharedL4DataVGSgSaySSGSgAySyAA04LockY0VGSg10Foundation4DateVSgAqYys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file to update and the properties to update. ``` client.files.update(fileId: "11111", name: "New file name.docx") { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error updating file information") return } print("File \(file.name) was updated at \(file.modifiedAt)") } ``` ## Upload File To upload a file from data in memory, call [`client.files.upload(data:name:parentId:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC6upload4data4name8parentId8progress21performPreflightCheck10completiony10Foundation4DataV_S2SySo10NSProgressCcSbys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the data to be uploaded, the name of the file, and the ID of the folder into which the file should be uploaded. Use ID `"0"` to upload a file into the root folder, "All Files". ``` let data = "test content".data(using: .utf8) let task: BoxUploadTask = client.files.upload(data: data, name: "Test File.txt", parentId: "0") { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error uploading file") return } print("File \(file.name) was uploaded at \(file.createdAt) into \"\(file.parent.name)\"") } // To cancel upload if someConditionIsSatisfied { task.cancel() } ``` To upload a file from a stream, use [`client.files.streamUpload(stream:fileSize:name:parentId:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC12streamUpload0E08fileSize4name8parentId8progress21performPreflightCheck10completionySo13NSInputStreamC_SiS2SySo10NSProgressCcSbys6ResultOyAA4FileCAA0A8SDKErrorCGctF). ``` let data = "test content".data(using: .utf8) let stream = InputStream(data: data) let task: BoxUploadTask = client.files.streamUpload( stream: stream, fileSize: 12, name: "Test File.txt", parentId: "0" ) { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error uploading file") return } print("File \(file.name) was uploaded at \(file.createdAt) into \"\(file.parent.name)\"") } // To cancel upload if someConditionIsSatisfied { task.cancel() } ``` ## Upload New File Version To upload a new version of an existing file, call [`client.files.uploadVersion(forFile:name:contentModifiedAt:data:ifMatch:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC13uploadVersion7forFile4name17contentModifiedAt4data8progress21performPreflightCheck10completionySS_SSSgAL10Foundation4DataVySo10NSProgressCcSbys6ResultOyAA0H0CAA0A8SDKErrorCGctF) with the ID of the file and the file contents to be uploaded. ``` let data = "updated file content".data(using: .utf8) let task: BoxUploadTask = client.files.uploadVersion( forFile: "11111", name: "New file name.txt", contentModifiedAt: "2019-08-07T09:19:13-07:00", data: data ) { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error uploading file version") return } print("New version of \(file.name) was uploaded") } // To cancel upload if someConditionIsSatisfied { task.cancel() } ``` To upload a new version of an existing file from a stream, use [`client.files.streamUploadVersion(stream:fileSize:forFile:name:contentModifiedAt:ifMatch:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC13uploadVersion7forFile4name17contentModifiedAt4data8progress21performPreflightCheck10completionySS_SSSgAL10Foundation4DataVySo10NSProgressCcSbys6ResultOyAA0H0CAA0A8SDKErrorCGctF). ``` let data = "updated file content".data(using: .utf8) let stream = InputStream(data: data) let task: BoxUploadTask = client.files.streamUploadVersion( stream: stream, fileSize: 12, forFile: "11111", name: "New file name.txt", contentModifiedAt: "2021-03-07T09:19:13-07:00" ) { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error uploading file version") return } print("New version of \(file.name) was uploaded") } // To cancel upload if someConditionIsSatisfied { task.cancel() } ``` ## Download File To download a file to the device, call [`client.files.download(fileId:version:destinationURL:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC8download6fileId14destinationURL7version8progress10completionySS_10Foundation0I0VSSSgySo10NSProgressCcys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file to download and a URL to the location where the file should be downloaded to. ``` let url = FileManager.default.homeDirectoryForCurrentUser let task: BoxDownloadTask = client.files.download(fileId: "11111", destinationURL: url) { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error downloading file") return } print("File downloaded successfully") } // To cancel download if someConditionIsSatisfied { task.cancel() } ``` ## Copy File To make a copy of a file, call [`client.files.copy(fileId:parentId:name:version:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC4copy6fileId06parentG04name7version6fields10completionySS_S2SSgAKSaySSGSgys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file to copy and the ID of the folder into which the copy should be placed. In case an item with the same name already exists in the destination folder, the `name` parameter can be used to provide a new name for the copied file. You can copy a specific file version by passing the version ID in the `version` parameter. ``` client.files.copy(fileId: "11111", parentId: "0") { (result: Result<File, BoxSDKError>) in guard case let .success(copiedFile) = result else { print("Error copying file") return } print("Copied file \(copiedFile.name) into folder \(copiedFile.parent.name); copy has file ID \(copiedFile.id)") } ``` ## Lock File To lock a file and prevent others from modifying it, call [`client.files.lock(fileId:expiresAt:isDownloadPrevented:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC4lock6fileId9expiresAt19isDownloadPrevented6fields10completionySS_10Foundation4DateVSgSbSgSaySSGSgys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. To also prevent others from downloading the file while it is locked, set the `isDownloadPrevented` parameter to `true`. ``` client.files.lock(fileId: "11111") { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error locking file") return } print("File \(file.name) locked") } ``` ## Unlock File To unlock a file, call [`client.files.unlock(fileId:fields:completion:)](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC6unlock6fileId6fields10completionySS_SaySSGSgys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.unlock(fileId: "11111") { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error unlocking file") return } print("File \(file.name) unlocked") } ``` ## Get File Thumbnail Image To retrieve the thumbnail image for a file, call [`client.files.getThumbnail(forFile:extension:minHeight:minWidth:maxHeight:maxWidth:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC12getThumbnail7forFile9extension9minHeight0J5Width03maxK00mL010completionySS_AA0F9ExtensionOSiSgA3Nys6ResultOy10Foundation4DataVAA0A8SDKErrorCGctF) with the ID of the file and the desired image format extension. Optionally, constraints on the image dimensions can be specified in the `minHeight`, `minWidth`, `maxHeight`, and `maxWidth` parameters. ``` client.files.getThumbnail(forFile: "11111", extension: .png) { (result: Result<Data, BoxSDKError>) in guard case let .success(thumbnailData) = result else { print("Error getting file thumbnail") return } let thumbnailImage = UIImage(data: thumbnailData) } ``` ## Get File Embed Link To retrieve a URL that can be embedded in a web page `<iframe>` to display a file preview, call [`client.files.getEmbedLink(forFile:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC12getEmbedLink7forFile10completionySS_ys6ResultOyAA08ExpiringfG0CAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.getEmbedLink(forFile: "11111") { (result: Result<ExpiringEmbedLink, BoxSDKError>) in guard case let .success(embedLink) = result else { print("Error generating file embed link") return } print("File embed URL is \(embedLink.url)") } ``` ## Get File Collaborations To retrieve a list of collaborations on a file, call [`client.files.listCollaborations(forFile:marker:limit:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC18listCollaborations7forFile6marker5limit6fields10completionySS_SSSgSiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA13CollaborationCGAA0A8SDKErrorCGctF) with the ID of the file. This method returns an iterator, which is used to retrieve file collaborations. ``` let iterator = client.files.listCollaborations(forFile: "11111") iterator.next { result in switch results { case let .success(page): for collaboration in page.entries { print("Collaboration created by \(collaboration.createdBy?.name)") } case let .failure(error): print(error) } } ``` ## Get File Comments To retrieve a list of comments on the file, call [`client.files.listComments(forFile:offset:limit:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC12listComments7forFile6offset5limit6fields10completionySS_SiSgAJSaySSGSgys6ResultOyAA14PagingIteratorCyAA7CommentCGAA0A8SDKErrorCGctF) with the ID of the file. This method returns an iterator, which is used to page through the collection of file comments. ``` let iterator = client.files.listComments(forFile: "11111") iterator.next { results in switch results { case let .success(page): for comment in page.entries { print(comment.message) } case let .failure(error): print(error) } } ``` ## Get File Tasks To retrieve a list of file tasks, call [`client.files.listTasks(forFile:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC9listTasks7forFile6fields10completionySS_SaySSGSgys6ResultOyAA14PagingIteratorCyAA4TaskCGAA0A8SDKErrorCGctF) with the ID of the file. This method returns an iterator, which is used to retrieve file comments. ``` let iterator = client.files.listTasks(forFile: "11111") iterator.next { results in switch results { case let .success(page): for task in page.entries { print("Task messsage: \(task.message)") } case let .failure(error): print(error) } } ``` ## Add File to Favorites To add a file to the user's favorites collection, call [`client.files.addToFavorites(fileId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC14addToFavorites6fileId10completionySS_ys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.addToFavorites(fileId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error adding file to favorites") return } print("File added to favorites") } ``` ## Remove File from Favorites To remove a file from the user's favorites collection, call [`client.files.removeFromFavorites(fileId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC19removeFromFavorites6fileId10completionySS_ys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.removeFromFavorites(fileId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing file from favorites") return } print("File removed from favorites") } ``` ## Get Shared Link To retrieve the shared link associated with a file, call [`client.files.getSharedLink(forFile:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC13getSharedLink7forFile10completionySS_ys6ResultOyAA0fG0CAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.getSharedLink(forFile: "11111") { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error retrieving file shared link") return } print("File shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` ## Set Shared Link To add or update the shared link for a file, call [`client.files.setSharedLink(forFile:unsharedAt:vanityName:access:password:canDownload:canEdit:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC13setSharedLink7forFile10unsharedAt10vanityName6access8password11canDownload0P4Edit10completionySS_AA17NullableParameterOy10Foundation4DateVGSgANySSGSgAA0fG6AccessOSgAUSbSgAYys6ResultOyAA0fG0CAA0A8SDKErrorCGctF) with the ID of the file and the shared link properties to set. ``` client.files.setSharedLink( forFile: "11111", access: .open, canDownload: true, canEdit: true ) { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error setting file shared link") return } print("File shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` ## Remove Shared Link To remove a file's shared link, call [`client.files.deleteSharedLink(forFile:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC16deleteSharedLink7forFile10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.deleteSharedLink(fileId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing file shared link") return } print("File shared link removed") } ``` ## List Representations To retrieve information about available preview representations for a file, call [`client.files.listRepresentations(fileId:representationHint:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC19listRepresentations6fileId18representationHint10completionySS_AA018FileRepresentationJ0OSgys6ResultOySayAA0lM0VGAA0A8SDKErrorCGctF) with the ID of the file. Omitting the `representationHint` parameter will provide summary information about all available representations; in order to retrieve the representation status and URL, the `representationHint` parameter must be passed to select the desired representation. ``` // Get full information about PDF representation client.files.listRepresentations( fileId: "11111", representationHint: "[pdf]" ) { (result: Result<[FileRepresentation], BoxSDKError>) in guard case let .success(representations) = result else { print("Error fetching representations") return } print("PDF representation generation status: \(representations[0]?.status?.state)") } ``` ## Download Zip Calling [`client.files.downloadZip(name:items:destinationURL:completion:)`][download-zip] will let you create a new zip file with the specified name and with the specified items and download it to the specified URL location where the file should be downloaded to. The created zip file does not show up in your Box account. ``` let name = "New zip name" var items: [ZipDownloadItem] = [] items.append(ZipDownloadItem( type: "file", id: "11111" )) let items: [ZipDownloadItem] = [] items.append(ZipDownloadItem( type: "folder", id: "22222" )) let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let destinationURL = documentsURL.appendingPathComponent("New zip name.zip") client.files.downloadZip(name: name, items: items, destinationURL: destinationURL) { (result: Result<ZipDownloadStatus, BoxSDKError>) in guard case .success = result else { guard case let .success(zipDownloadStatus) = result else { print("Error downloading zip") return } print("Zip download status: \(zipDownloadStatus.state)") } ``` --- ## Untitled *Type: page* Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a… # Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a folder with another user or group, and perform other common folder operations (move, copy, delete, etc.). [Folders](#folders) - [Get Folder Info](#get-folder-info) - [Get Folder Items](#get-folder-items) - [Create Folder](#create-folder) - [Delete Folder](#delete-folder) - [Copy Folder](#copy-folder) - [Get Folder Collaborations](#get-folder-collaborations) - [Add Folder to Favorites](#add-folder-to-favorites) - [Remove Folder from Favorites](#remove-folder-from-favorites) - [Get Shared Link](#get-shared-link) - [Set Shared Link](#set-shared-link) - [Remove Shared Link](#remove-shared-link) - [Get Folder Locks](#get-folder-locks) - [Create Folder Lock](#create-folder-lock) - [Delete Folder Lock](#delete-folder-lock) ## Get Folder Info To retrieve information about a folder, call [`client.folders.get(folderId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC3get8folderId6fields10completionySS_SaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with the ID of the folder. You can control which fields are returned in the resulting `Folder` object by passing the `fields` parameter. ``` client.folders.get( folderId: "22222", fields: ["name", "created_at"] ) { (result: Result<Folder, BoxSDKError>) in guard case let .success(folder) = result else { print("Error getting folder information") return } print("Folder \(folder.name) was created at \(folder.createdAt)") } ``` As an alternative, you can call `async` method [`client.folders.get(folderId:fields)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC3get8folderId6fieldsAA6FolderCSS_SaySSGSgtYaKF) ``` do { let folder = try await client.folders.get( folderId: "111111", fields: ["name", "created_at"] ) print("Folder \(folder.name) was created at \(folder.createdAt)") } catch { print("Error getting folder information") } ``` ## Get Folder Items To retrieve information about the items contained in a folder, call [`client.folders.listItems(folderId:usemarker:marker:offset:limit:sort:direction:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC9listItems8folderId9usemarker6marker6offset5limit4sort9direction6fields10completionySS_SbSgSSSgSiSgApA06FolderF7OrderByOSgAA0R9DirectionOSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0Q4ItemOGAA0A8SDKErrorCGctF) with the ID of the folder. This method will return an iterator, which is used to retrieve folder items. ``` let iterator = client.folders.listItems(folderId: "22222", sort: .name, direction: .ascending) iterator.next { results in switch results { case let .success(page): for item in page.entries { switch item { case let .file(file): print("File \(file.name) (ID: \(file.id)) is in the folder") case let .folder(folder): print("Subfolder \(folder.name) (ID: \(folder.id)) is in the folder") case let .webLink(webLink): print("Web link \(webLink.name) (ID: \(webLink.id)) is in the folder") } } case let .failure(error): print(error) } } ``` As an alternative, you can retrieve folder items by iterator in `async` way. For instance, to fetch all folder items, call: ``` let iterator = client.folders.listItems(folderId: "22222", sort: .name, direction: .ascending) var allItems: [FolderItem] = [] do { repeat { let items = try await iterator.next() allItems.append(contentsOf: items.entries) } while true } catch let error as BoxSDKError where error.message == .endOfList { print("The end of the list has been reached") } catch { print("An error occurred: \(error)") } ``` ## Create Folder To create a new folder, call [`client.folders.create(name:parentId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC6create4name8parentId6fields10completionySS_SSSaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with a name for the new folder and the ID of the folder to create the new folder in. To create a new folder inside the root folder ("All Files"), use ID `"0"`. ``` client.folders.create(name: "New Folder", parentId: "22222") { (result: Result<Folder, BoxSDKError>) in guard case let .success(folder) = result else { print("Error creating folder") return } print("Created folder \"\(folder.name)\" inside of folder \"\(folder.parent?.name)\"") } ``` As an alternative, you can call `async` method [`client.folders.create(name:parentId:fields)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC6create4name8parentId6fieldsAA6FolderCSS_SSSaySSGSgtYaKF). ``` do { let folder = try await client.folders.create(name: "New Folder", parentId: "22222") print("Created folder \"\(folder.name)\" inside of folder \"\(folder.parent?.name)\"") } catch { print("Error getting folder information") } ``` ## Delete Folder To delete a folder, call [`client.folders.delete(folderId:recursive:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC6delete8folderId9recursive10completionySS_SbSgys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the folder to delete. By default, the folder will only be deleted if it is empty and has no items in it; if you wish to delete all the items in the folder as well, pass `recursive: true`. ``` client.folders.delete(folderId: "22222", recursive: true) { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting folder") return } print("Folder and contents successfully deleted") } ``` As an alternative, you can call `async` method [`client.folders.delete(folderId:recursive)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC6delete8folderId9recursiveySS_SbSgtYaKF) ``` do { let folder = try await client.folders.delete(folderId: "22222", recursive: true) print("Folder and contents successfully deleted") } catch { print("Error deleting folder") } ``` ## Copy Folder To copy a folder from one parent folder to another, call [`client.folders.copy(folderId:destinationFolderID:name:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC4copy8folderId19destinationFolderID4name6fields10completionySS_S2SSgSaySSGSgys6ResultOyAA0I0CAA0A8SDKErrorCGctF) with the ID of the folder to copy and the ID of the destination parent folder. To avoid a name conflict in the new parent folder, pass an alternate name for the folder in the `name` parameter; the folder will be renamed to the alternate name in case of a conflict. ``` client.folders.copy( folderId: "22222", destinationFolderID: "12345" ) { (result: Result<Folder, BoxSDKError>) in guard case let .success(folderCopy) = result else { print("Error copying folder") return } print("Copied folder \(folderCopy.name) to destination \(folderCopy.parent?.name)") } ``` As an alternative, you can call `async` method [`client.folders.copy(folderId:destinationFolderId:name:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC4copy8folderId017destinationFolderG04name6fieldsAA0I0CSS_S2SSgSaySSGSgtYaKF) ``` do { let folderCopy = try await client.folders.copy(folderId: "22222", destinationFolderId: "12345") print("Copied folder \(folderCopy.name) to destination \(folderCopy.parent?.name)") } catch { print("Error copying folder") } ``` ## Get Folder Collaborations To retrieve a list of the collaborations on a folder, call [`client.folders.listCollaborations(folderId:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC18listCollaborations8folderId6fields10completionySS_SaySSGSgys6ResultOyAA14PagingIteratorCyAA13CollaborationCGAA0A8SDKErrorCGctF) with the ID of the folder. ``` let iterator = client.folders.listCollaborations(folderId: "22222") iterator.next { results in switch results { case let .success(page): for collaboration in page.entries { if let collaborator = collaboration.accessibleBy { switch collaborator.collaboratorValue { case .user(let user): print("- user: \(user.name ?? "")") case .group(let group): print("- group: \(group.name ?? "")") } } } case let .failure(error): print(error) } } ``` As an alternative, you can retrieve collaborations items by iterator in `async` way. ``` let iterator = client.folders.listCollaborations(folderId: "163571796480") do { let page = try await iterator.next() for collaboration in page.entries { if let collaborator = collaboration.accessibleBy { switch collaborator.collaboratorValue { case .user(let user): print("- user: \(user.name ?? "")") case .group(let group): print("- group: \(group.name ?? "")") } } } } catch { print("An error occurred: \(error)") } ``` ## Add Folder to Favorites To add a folder to the user's favorites, call [`client.folders.addToFavorites(folderId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC14addToFavorites8folderId6fields10completionySS_SaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.folders.addToFavorites(folderId: "22222") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error adding folder to favorites") return } print("Added folder to favorites") } ``` As an alternative, you can call `async` method [`client.folders.addToFavorites(folderId:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC14addToFavorites8folderId6fieldsAA6FolderCSS_SaySSGtYaKF). ``` do { try await client.folders.addToFavorites(folderId: "22222") print("Added folder to favorites") } catch { print("Error adding folder to favorites") } ``` ## Remove Folder from Favorites To remove a folder from the user's favorites, call [`client.folders.removeFromFavorites(folderId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC19removeFromFavorites8folderId6fields10completionySS_SaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.folders.removeFromFavorites(folderId: "22222") { result in guard case .success = result else { print("Error removing folder from favorites") return } print("Removed folder to favorites") } ``` As an alternative, you can call `async` method [`client.folders.removeFromFavorites(folderId:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC19removeFromFavorites8folderId6fieldsAA6FolderCSS_SaySSGSgtYaKF). ``` do { try await client.folders.removeFromFavorites(folderId: "22222") print("Removed folder to favorites") } catch { print("Error removing folder from favorites") } ``` ## Get Shared Link To retrieve the shared link associated with a folder, call [`client.folders.getSharedLink(forFolder:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC13getSharedLink9forFolder10completionySS_ys6ResultOyAA0fG0CAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.folders.getSharedLink(forFolder: "11111") { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error retrieving folder shared link") return } print("Folder shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` As an alternative, you can call `async` method [`client.folders.getSharedLink(forFolder:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC13getSharedLink9forFolder10completionySS_ys6ResultOyAA0fG0CAA0A8SDKErrorCGctF). ``` do { let sharedLink = try await client.folders.getSharedLink(forFolder: "11111") print("Folder shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } catch { print("Error retrieving folder shared link") } ``` ## Set Shared Link To add or update the shared link for a folder, call [`client.folders.setSharedLink(forFolder:access:unsharedAt:vanityName:password:canDownload:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC13setSharedLink9forFolder6access10unsharedAt10vanityName8password11canDownload10completionySS_AA0fG6AccessOSgAA17NullableParameterOy10Foundation4DateVGSgAPySSGSgAWSbSgys6ResultOyAA0fG0CAA0A8SDKErrorCGctF) with the ID of the folder and the shared link properties to set. ``` client.folders.setSharedLink(forFolder: "11111", access: .open) { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error setting folder shared link") return } print("Folder shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` As an alternative, you can call `async` method [`client.folders.setSharedLink(forFolder:access:unsharedAt:vanityName:password:canDownload:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC13setSharedLink9forFolder6access10unsharedAt10vanityName8password11canDownloadAA0fG0CSS_AA0fG6AccessOSgAA17NullableParameterOy10Foundation4DateVGSgAQySSGSgAXSbSgtYaKF). ``` do { let sharedLink = try await client.folders.setSharedLink(forFolder: "163571796480", access: .open) print("Folder shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } catch { print("Error setting folder shared link") } ``` ## Remove Shared Link To remove a file's shared link, call [`client.folders.deleteSharedLink(forFolder:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC16deleteSharedLink9forFolder10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.folders.deleteSharedLink(forFolder: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing folder shared link") return } print("Folder shared link removed") } ``` As an alternative, you can call `async` method [`client.folders.deleteSharedLink(forFolder:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC16deleteSharedLink9forFolderySS_tYaKF). ``` do { try await client.folders.deleteSharedLink(forFolder: "11111") print("Folder shared link removed") } catch { print("Error removing folder shared link") } ``` ## Get Folder Locks To retrieve a list of the locks on a folder, call [`client.folders.listLocks(folderId:completion:)`][get-folder-locks] with the ID of the folder. Folder locks define access restrictions placed by folder owners to prevent specific folders from being moved or deleted. ``` client.folders.listLocks(folderId: "22222") { results in switch results { case let .success(iterator): for i in 1 ... 10 { iterator.next { result in switch result { case let .success(folderLock): print("- \(folderLock.id)") case let .failure(error): print(error) } } } case let .failure(error): print(error) } } ``` As an alternative, you can retrieve all folder locks by iterator in `async` way. ``` let iterator = client.folders.listLocks(folderId: "22222") do { repeat { let page = try await iterator.next() for folderLock in page.entries { print("- \(folderLock.id)") } } while true } catch let error as BoxSDKError where error.message == .endOfList { print("The are no more items to fetch") } catch { print("An error occurred: \(error)") } ``` ## Create Folder Lock To lock a folder, call [`client.folders.createLock(folderId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC10createLock8folderId10completionySS_ys6ResultOyAA06FolderF0CAA0A8SDKErrorCGctF) with the ID of the folder. This prevents the folder from being moved and/or deleted. ``` client.folders.createLock(folderId: "22222") { (result: Result<FolderLock, BoxSDKError>) in guard case let .success(folderLock) = result else { print("Error creating folder lock") return } print("Created folder lock with id \"\(folderLock.id)\" inside of folder with id \"\(folderLock.folder?.id)\"") } ``` As an alternative, you can call `async` method [`client.folders.createLock(folderId: "22222")`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC10createLock8folderIdAA06FolderF0CSS_tYaKF). ``` do { let folderLock = try await client.folders.createLock(folderId: "163571796480") print("Created folder lock with id \"\(folderLock.id)\" inside of folder with id \"\(folderLock.folder?.id)\"") } catch { print("Error creating folder lock") } ``` ## Delete Folder Lock To remove a folder lock, call [`client.folders.deleteLock(folderLockId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC10deleteLock06folderF2Id10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the folder lock. ``` client.folders.deleteLock(folderLockId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing folder lock") return } print("Folder lock removed") } ``` As an alternative, you can call `async` method [`client.folders.deleteLock(folderId: "22222")`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC10deleteLock06folderF2IdySS_tYaKF). ``` do { try await client.folders.deleteSharedLink(forFolder: "11111") print("Folder shared link removed") } catch { print("Error removing folder shared link") } ``` --- ## Untitled *Type: page* Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of… # Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of key-value pairs that belong to files/folders. For example, an important contract file stored on Box may have key-value pairs of `"clientNumber":"820183"` and `"clientName":"BioMedical Corp"`. Metadata that belongs to a file/folder is grouped by templates. Templates allow the metadata service to provide a multitude of features, such as pre-defining sets of key-value pairs or schema enforcement on specific fields. Each file/folder can have multiple distinct template instances associated with it, and templates are also grouped by scopes. Currently, the only scopes support are `enterprise` and `global`. Enterprise scopes are defined on a per-enterprise basis, whereas global scopes are Box application-wide. In addition to `enterprise` scoped templates, every file on Box has access to the `global` `properties` template. The `properties` template contains free-form key-value string pairs, with no additional schema associated with it. This is recommended for scenarios where applications want to write metadata to file objects in a flexible way, without pre-defined template structure. - [Get Metadata Template](#get-metadata-template) - [Create Metadata Template](#create-metadata-template) - [Update Metadata Template](#update-metadata-template) - [Delete Metadata Template](#delete-metadata-template) - [List Metadata Templates](#list-metadata-templates) - [Get All Metadata on File](#get-all-metadata-on-file) - [Get Metadata Instance on File](#get-metadata-instance-on-file) - [Add Metadata Instance to File](#add-metadata-instance-to-file) - [Update Metadata Instance on File](#update-metadata-instance-on-file) - [Remove Metadata Instance from File](#remove-metadata-instance-from-file) - [Get All Metadata on Folder](#get-all-metadata-on-folder) - [Get Metadata Instance on Folder](#get-metadata-instance-on-folder) - [Add Metadata Instance to Folder](#add-metadata-instance-to-folder) - [Update Metadata Instance on Folder](#update-metadata-instance-on-folder) - [Remove Metadata Instance from Folder](#remove-metadata-instance-from-folder) ## Get Metadata Template To retrieve information about a metadata template, call [`client.metadata.getTemplateByKey(scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC16getTemplateByKey5scope08templateH010completionySS_SSys6ResultOyAA0cF0CAA0A8SDKErrorCGctF) with the scope and key of the template. ``` client.metadata.getTemplateByKey( scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<MetadataTemplate, BoxSDKError>) in guard case let .success(template) = result { print("Error retrieving metadata template") return } print("Metadata template has \(template.fields?.count) fields") } ``` Alternatively, if you know the ID of the metadata template, you can call [`client.metadata.getTemplateById(id:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC15getTemplateById2id10completionySS_ys6ResultOyAA0cF0CAA0A8SDKErrorCGctF) with the ID of the template. ``` client.metadata.getTemplateById( id: "26004e29-7b94-44a1-8a63-f9aa384c7421" ) { (result: Result<MetadataTemplate, BoxSDKError>) in guard case let .success(template) = result { print("Error retrieving metadata template") return } print("Metadata template has \(template.fields?.count) fields") } ``` ## Create Metadata Template To create a new metadata template, call [`client.metadata.createTemplate(scope:templateKey:displayName:hidden:copyInstanceOnItemCopy:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC14createTemplate5scope11templateKey11displayName6hidden6fields10completionySS_S2SSbSayAA0C5FieldVGys6ResultOyAA0cF0CAA0A8SDKErrorCGctF) with the scope and name of the template, as well as the fields the template should contain. ``` var templateFields: [MetadataField] = [] templateFields.append(MetadataField( type: "string", key: "name", displayName: "Full Name" )) templateFields.append(MetadataField( type: "date", key: "birthday", displayName: "Birthday" )) templateFields.append(MetadataField( type: "enum", key: "department", displayName: "Department", options: [ ["key": "HR"], ["key": "Sales"], ["key": "Marketing"], ] )) client.metadata.createTemplate( scope: "enterprise", templateKey: "personnelRecord", displayName: "Personnel Record", hidden: false, fields: templateFields ) { (result: Result<MetadataTemplate, BoxSDKError>) in guard case let .success(template) = result { print("Error creating metadata template") return } print("Created metadata template with ID \(template.id)") } ``` ## Update Metadata Template To update a metadata template, including to modify its fields, call [`client.metadata.updateTemplate(scope:templateKey:operation:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC14updateTemplate5scope11templateKey9operation10completionySS_SSAA0cF9OperationOys6ResultOyAA0cF0CAA0A8SDKErrorCGctF) with the scope and key of the template to update, as well as the update operation to perform. In this example, we are updating the metadata template using the ReorderEnumOptions operation. Other metadata template update operations include: addEnumOption, addField, editTemplate, reorderFields ``` client.metadata.updateTemplate( scope: "enterprise", templateKey: "personnelRecord", operation: .reorderEnumOptions(fieldKey: "department", enumOptionKeys: ["Marketing", "Sales", "HR"]) ) { (result: Result<MetadataTemplate, BoxSDKError>) in guard case let .success(template) = result { print("Error updating metadata template") return } print("Updated metadata template with ID \(template.id)") } ``` ## Delete Metadata Template To delete a metadata template, call [`client.metadata.deleteTemplate(scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC14deleteTemplate5scope11templateKey10completionySS_SSys6ResultOyytAA0A8SDKErrorCGctF) with the scope and key of the template to delete. ``` client.metadata.deleteTemplate( scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<Void, BoxSDKError>) in guard case .success = result { print("Error deleting metadata template") return } print("Metadata template deleted") } ``` ## List Metadata Templates To retrieve the collection of available metadata templates in a particular scope, call [`client.metadata.listEnterpriseTemplates(scope:marker:limit:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC23listEnterpriseTemplates5scope6marker5limit10completionySS_SSSgSiSgys6ResultOyAA14PagingIteratorCyAA0C8TemplateCGAA0A8SDKErrorCGctF) with the scope. This method will return an iterator, which is used to retrieve metadata templates. ``` let iterator = client.metadata.listEnterpriseTemplates(scope: "enterprise") iterator.next { results in switch results { case let .success(page): for template in page.entries { print("Template name: \(template.displayName)") } case let .failure(error): print(error) } } ``` Similarly, to get all templates available in the `global` scope. ``` let iterator = client.metadata.listEnterpriseTemplates(scope: "global") iterator.next { results in switch results { case let .success(page): for template in page.entries { print("Template name: \(template.displayName)") } case let .failure(error): print(error) } } ``` ## Get All Metadata on File To retrieve all metadata attached to a file, call [`client.metadata.list(forFileId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC4list9forFileId10completionySS_ys6ResultOySayAA0C6ObjectCGAA0A8SDKErrorCGctF) with the ID of the file. ``` client.metadata.list(forFileId: "11111") { (result: Result<[MetadataObject], BoxSDKError>) in guard case let .success(metadata) = result { print("Error retrieving metadata") return } print("Retrieved \(metadata.count) metadata instances:") for instance in metadata { print("- \(instance.template)") } } ``` ## Get Metadata Instance on File To retrieve a specific metadata instance attached to a file, call [`client.metadata.get(forFileWithId:scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC3get13forFileWithId5scope11templateKey10completionySS_S2Sys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the file ID, as well as the scope and key of the metadata template of the instance. ``` client.metadata.get( forFileWithId: "11111", scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error retrieving metadata") return } print("Found personnel record for \(metadata.keys["name"])") } ``` ## Add Metadata Instance to File To attach a new metadata instance to a file, call [`client.metadata.create(forFileWithId:scope:templateKey:keys:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6create13forFileWithId5scope11templateKey4keys10completionySS_S2SSDySSypGys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the ID of the file, as well as the scope and key of the metadata template to use and the metadata keys and values to attach. ``` let metadata = [ "name": "John Doe", "birthday": "2000-01-01T00:00:00Z", "department": "Sales" ] client.metadata.create( forFileWithId: "11111", scope: "enterprise", templateKey: "personnelRecord", keys: metadata ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error adding metadata") return } print("Successfully attached metadata") } ``` ## Update Metadata Instance on File To update the values in a metadata instance attached to a file, call [`client.metadata.updateforFileWithId:scope:templateKey:operations:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6update13forFileWithId5scope11templateKey10operations10completionySS_S2SSayAA0gC9OperationOGys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the ID of the file, the scope and key of the metadata template associated with the instance, and the operations to perform on the metadata. ``` client.metadata.update( forFileWithId: "11111", scope: "enterprise", templateKey: "personnelRecord", operations: [ .test(path: "/department", value: "Sales"), .replace(path: "/department", value: "Marketing") ] ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error updating metadata") return } print("Employee department updated to \(metadata.keys["department"])") } ``` ## Remove Metadata Instance from File To remove a specific metadata instance from a file, call [`client.metadata.delete(forFileWithId:scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6delete13forFileWithId5scope11templateKey10completionySS_S2Sys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file, as well as the scope and key of the metadata template associated with the instance. ``` client.metadata.delete( forFileWithId: "11111", scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<Void, BoxSDKError>) in guard case .success = result { print("Error deleting metadata instance") return } print("Metadata instance deleted") } ``` ## Get All Metadata on Folder To retrieve all metadata attached to a folder, call [`client.metadata.list(forFolderId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC4list11forFolderId10completionySS_ys6ResultOySayAA0C6ObjectCGAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.metadata.list(forFolderId: "22222") { (result: Result<[MetadataObject], BoxSDKError>) in guard case let .success(metadata) = result { print("Error retrieving metadata") return } print("Retrieved \(metadata.count) metadata instances:") for instance in metadata { print("- \(instance.template)") } } ``` ## Get Metadata Instance on Folder To retrieve a specific metadata instance attached to a folder, call [`client.metadata.get(forFolderWithId:scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC3get15forFolderWithId5scope11templateKey10completionySS_S2Sys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the folder ID, as well as the scope and key of the metadata template of the instance. ``` client.metadata.get( forFolderWithId: "22222", scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error retrieving metadata") return } print("Found personnel record for \(metadata.keys["name"])") } ``` ## Add Metadata Instance to Folder To attach a new metadata instance to a folder, call [`client.metadata.create(forFolderWithId:scope:templateKey:keys:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6create15forFolderWithId5scope11templateKey4keys10completionySS_S2SSDySSypGys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the ID of the folder, as well as the scope and key of the metadata template to use and the metadata keys and values to attach. ``` let metadata = [ "name": "John Doe", "birthday": "2000-01-01T00:00:00Z", "department": "Sales" ] client.metadata.create( forFolderWithId: "22222", scope: "enterprise", templateKey: "personnelRecord", keys: metadata ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error adding metadata") return } print("Successfully attached metadata") } ``` ## Update Metadata Instance on Folder To update the values in a metadata instance attached to a folder, call [`client.metadata.update(forFolderWithId:scope:templateKey:operations:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6update15forFolderWithId5scope11templateKey10operations10completionySS_S2SSayAA0gC9OperationOGys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the ID of the folder, the scope and key of the metadata template associated with the instance, and the operations to perform on the metadata. ``` client.metadata.update( forFolderWithId: "22222", scope: "enterprise", templateKey: "personnelRecord", operations: [ .test(path: "/department", value: "Sales"), .replace(path: "/department", value: "Marketing") ] ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error updating metadata") return } print("Employee department updated to \(metadata.keys["department"])") } ``` ## Remove Metadata Instance from Folder To remove a specific metadata instance from a folder, call [`client.metadata.delete(forFolderWithId:scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6delete15forFolderWithId5scope11templateKey10completionySS_S2Sys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the folder, as well as the scope and key of the metadata template associated with the instance. ``` client.metadata.delete( forFolderWithId: "22222", scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<Void, BoxSDKError>) in guard case .success = result { print("Error deleting metadata instance") return } print("Metadata instance deleted") } ``` --- ## Untitled *Type: page* Legal Holds Get Legal Hold Policy Info Create Legal Hold Policy Update Legal Hold Policy Delete Legal Hold Policy Get Legal Hold Policies… # Legal Holds - [Get Legal Hold Policy Info](#get-legal-hold-policy-info) - [Create Legal Hold Policy](#create-legal-hold-policy) - [Update Legal Hold Policy](#update-legal-hold-policy) - [Delete Legal Hold Policy](#delete-legal-hold-policy) - [Get Legal Hold Policies](#get-legal-hold-policies) - [Get Policy Assignment Info](#get-policy-assignment-info) - [Create Policy Assignment](#create-policy-assignment) - [Delete Policy Assignment](#delete-policy-assignment) - [Get Policy Assignments](#get-policy-assignments) - [Get File Version Legal Hold Info](#get-file-version-legal-hold-info) - [Get File Version Legal Holds](#get-file-version-legal-holds) ## Get Legal Hold Policy Info To retrieve information about a legal hold policy, call [`client.legalHolds.get(policyId: String, fields: [String]?, completion: @escaping Callback<LegalHoldPolicy>)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC3get8policyId6fields10completionySS_SaySSGSgys6ResultOyAA0C10HoldPolicyCAA0A8SDKErrorCGctF) with the ID of the policy. You can control which fields are returned in the resulting `Legal Hold Policy` object by passing the `fields` parameter. ``` client.legalHolds.get(policyId: "22222", fields: ["name", "created_at"]) { (result: Result<LegalHoldPolicy, BoxSDKError>) in guard case let .success(policy) = result else { print("Error getting policy information") return } print("Legal hold policy \(policy.id) was created at \(policy.createdAt)") } ``` ## Get Legal Hold Policies To retrieve information about the items contained in a folder, call [`client.legalHolds.listForEnterprise(policyName: String, marker: String?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC17listForEnterprise10policyName6marker5limit6fields10completionySSSg_AJSiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0C10HoldPolicyCGAA0A8SDKErrorCGctF) with the ID of the policy. This method will return an iterator object, which is used to retrieve policies in the enterprise. ``` let iterator = client.legalHolds.listForEnterprise(policyName: "policy1") iterator.next { results in switch results { case let .success(page): for policy in page.entries { print("Legal hold policy \(policy.name)") } case let .failure(error): print(error) } } ``` ## Create Legal Hold Policy To create a new legal hold policy, call [`client.legalHolds.create(policyName: String, description: String? filterStartedAt: Date?, filterEndedAt: Date?, isOngoing: Bool?, fields: [String]?, completion: @escaping Callback<LegalHoldPolicy>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC6create10policyName11description15filterStartedAt0j5EndedL09isOngoing6fields10completionySS_SSSg10Foundation4DateVSgAPSbSgSaySSGSgys6ResultOyAA0C10HoldPolicyCAA0A8SDKErrorCGctF) with a name for the legal hold policy. ``` client.legalHolds.create(name: "New Folder") { (result: Result<LegalHoldPolicy, BoxSDKError>) in guard case let .success(policy) = result else { print("Error creating legal hold policy") return } print("Created legal hold policy \"\(policy.name)\"") } ``` ## Update Legal Hold Policy To update legal hold policy, call [`client.legalHolds.update(policyId: String, policyName: String?, description: String?, releaseNotes: String?, fields: [String]?, completion: @escaping Callback<LegalHoldPolicy>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC6update8policyId0G4Name11description12releaseNotes6fields10completionySS_SSSgA2KSaySSGSgys6ResultOyAA0C10HoldPolicyCAA0A8SDKErrorCGctF). ``` client.legalHolds.update(policyId: "1234", policyName: "New Name") { (result: Result<LegalHoldPolicy, BoxSDKError>) in guard case let .success(policy) = result else { print("Error updating legal hold policy") return } print("Updated legal hold policy name is \"\(policy.name)\"") } ``` ## Delete Legal Hold Policy To delete a legal hold policy, call [`client.folders.delete(policyId: String, completion: @escaping Callback<Void>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC6delete8policyId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the legal hold policy to delete. ``` client.legalHolds.delete() { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting legal hold policy") return } print("Legal hold policy successfully deleted") } ``` ## Get Policy Assignment Info To retrieve information about a legal hold policy assignment, call [`client.legalHolds.getPolicyAssignment(assignmentId: String, fields: [String]?, completion: @escaping Callback<LegalHoldPolicyAssignment>)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC19getPolicyAssignment12assignmentId6fields10completionySS_SaySSGSgys6ResultOyAA0c4HoldgH0CAA0A8SDKErrorCGctF) with the ID of the policy assignment. You can control which fields are returned in the resulting `Legal Hold Policy Assignment` object by passing the `fields` parameter. ``` client.legalHolds.getPolicyAssignment(assignmentId: "22222", fields: ["assigned_at"]) { (result: Result<LegalHoldPolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error getting policy assignment info") return } print("Legal hold policy assignment \(assignmnent.id) was created at \(assignment.assignedAt)") } ``` ## Get Policy Assignments To retrieve legal hold policy assignments, call [`client.legalHolds.listPolicyAssignments(policyId: String, assignToType: String?, assignToId: String?, marker: String?, limit: String?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC21listPolicyAssignments8policyId12assignToType0klJ06marker5limit6fields10completionySS_SSSgA2LSiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0c4HoldG10AssignmentCGAA0A8SDKErrorCGctF) with the ID of a policy. This method will return an iterator object, which is used to retrieve policy assignments for a policy. ``` let iterator = client.legalHolds.listPolicyAssignments(policyId: "1234") iterator.next { results in switch results { case let .success(page): for assignment in page.entries { print("Policy Assignment \(assignment.id)") } case let .failure(error): print(error) } } ``` ## Assign Policy To assign a legal hold policy, call [`client.legalHolds.forceApply(policyId: String, assignToId: String, assignToType: String, fields: [String]?, completion: @escaping Callback<LegalHoldPolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC12assignPolicy8policyId0f2ToI00fJ4Type6fields10completionySS_S2SSaySSGSgys6ResultOyAA0c4HoldG10AssignmentCAA0A8SDKErrorCGctF) with an ID of a policy, an ID of a file, file version, folder, or user and the type of the box item that the policy is being assigned to. ``` client.legalHolds.forceApply(policyId: "1234", assignToId: "4568" ,assignToType: "file") { (result: Result<LegalHoldPolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error assigning legal hold policy") return } print("Assigned a legal hold policy at \"\(assignment.assignedAt)\"") } ``` ## Delete Policy Assignment To delete a legal hold policy assignment, call [`client.legalHolds.deletePolicyAssignment(policyId: String, completion: @escaping Callback<Void>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC22deletePolicyAssignment12assignmentId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the policy assignment to delete. ``` client.legalHolds.deletePolicyAssignment(assignmentId: "1234") { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting legal hold policy assignment") return } print("Legal hold policy assignment successfully deleted") } ``` ## Get File Version Legal Hold Info To retrieve information about a file version legal hold, call [`client.legalHolds.getFileVersionPolicy(legalHoldId: String, fields: [String]?, completion: @escaping Callback<FileVersionLegalHold>)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC20getFileVersionPolicy11legalHoldId6fields10completionySS_SaySSGSgys6ResultOyAA0ghcK0CAA0A8SDKErrorCGctF) with the ID of legal hold. You can control which fields are returned in the resulting `File Version Legal Hold` object by passing the `fields` parameter. ``` client.legalHolds.getFileVersionPolicy(legalHoldId: "22222") { (result: Result<FileVersionLegalHold, BoxSDKError>) in guard case let .success(legalHold) = result else { print("Error getting file version legal hold") return } print("File version legal hold ID is \(legalHold.id)") } ``` ## Get File Version Legal Holds To retrieve all of the non-deleted legal holds for a single legal hold policy, call [`client.legalHolds.listFileVersionPolicies(policyId: String, marker: String?, limit: String?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC23listFileVersionPolicies8policyId6marker5limit6fields10completionySS_SSSgSiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0ghC4HoldCGAA0A8SDKErrorCGctF) with the ID of a policy. This method will return an iterator object, which is used to retrieve legal holds for a policy. ``` let iterator = client.legalHolds.listFileVersionPolicies(policyId: "1234") iterator.next { result in switch results { case let .success(page): for hold in page.entries { print("Legal hold \(hold.id)") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention… # Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console. - [Create Retention Policy](#create-retention-policy) - [Update Retention Policy](#update-retention-policy) - [Get Retention Policy](#get-retention-policy) - [Get Retention Policies](#get-retention-policies) - [Create Retention Policy Assignment](#create-retention-policy-assignment) - [Get Retention Policy Assignment](#get-retention-policy-assignment) - [Get Retention Policy Assignments](#get-retention-policy-assignments) - [Delete Retention Policy Assignment](#delete-retention-policy-assignment) - [Get File Version Retention](#get-file-version-retention) - [Get File Version Retentions](#get-file-version-retentions) (will be deprecated in the future, use [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) and [Get File Version Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) instead) - [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) - [Get File Version Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) ## Create Retention Policy To create a retention policy, call [`client.retentionPolicy.create(name:type:length:dispositionAction:canOwnerExtendRetention:areOwnersNotified:customNotificationRecipients:retentionType:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC6create4name4type6length17dispositionAction014canOwnerExtendC017areOwnersNotified28customNotificationRecipients13retentionType10completionySS_AA0c6PolicyV0OSiSgAA011DispositionK0OSbSgASSayAA4UserCGSgAA0cV0OSgys6ResultOyAA0cX0CAA0A8SDKErrorCGctF). You can create either a `indefinite` retention policy, or a `finite`. To create a `indefinite` retention policy, you must set a `type` to `.indefinite` and a `dispositionAction` to `.removeRetention`. ``` client.retentionPolicy.create( name: "Test Indefinite Policy Name", type: .indefinite, dispositionAction: .removeRetention ) { result in guard case let .success(retentionPolicy) = result else { print("Error creating retention policy") return } print("Retention policy: \(retentionPolicy.id) was created") } ``` To create a `finite` retention policy, you must set `type` to `.finite`, set amount of time in days to apply the retention policy (`length`) and a `dispositionAction`. The disposition action can be `.permanentlyDelete` or `.removeRetention`. ``` client.retentionPolicy.create( name: "Test Finite Policy Name", type: .finite, length: 60, dispositionAction: .permanentlyDelete ) { result in guard case let .success(retentionPolicy) = result else { print("Error creating retention policy") return } print("Retention policy: \(retentionPolicy.id) was created") } ``` ## Update Retention Policy To update a retention policy, call [`client.retentionPolicy.update(policyId:name:dispositionAction:status:setRetentionTypeToNonModifiable:length:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC6update8policyId4name17dispositionAction6status03setC19TypeToNonModifiable6length10completionySS_SSSgAA011DispositionK0OSgAA0C12PolicyStatusOSgSbSiSgys6ResultOyAA0cU0CAA0A8SDKErrorCGctF). ``` client.retentionPolicy.update(policyId: "1234", name: "New Policy Name") { result in guard case let .success(retentionPolicy) = result else { print("Error updating a retention policy") return } print("Updated retention policy: \(retentionPolicy.id)") } ``` ## Get Retention Policy To retrieve information about a retention policy, call [`client.retentionPolicy.get(policyId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC3get8policyId10completionySS_ys6ResultOyAA0C6PolicyCAA0A8SDKErrorCGctF) with the ID of the retention policy. ``` client.retentionPolicy.get(policyId: "1234") { result in guard case let .success(retentionPolicy) = result else { print("Error getting retention policy") return } print("Retention policy: \(retentionPolicy.id)") } ``` ## Get Retention Policies To retrieve all retention policies for an enterprise, call [`client.retentionPolicy.list(name:type:createdByUserId:marker:limit:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC4list4name4type15createdByUserId6marker5limitAA14PagingIteratorCyAA0C11PolicyEntryCGSSSg_AA0cQ4TypeOSgA2OSiSgtF). This method will return an iterator, which is used to get the policies. As you can see in the method signature, it is possible to specify filter for the name, type and created user of the retention policy. All of mentioned fields are optional and if not set, all retention policies will be returned. You can also set a number of items per single response by setting a limit. ``` let iterator = client.retentionPolicy.list(type: .indefinite) iterator.next { results in switch results { case let .success(page): for policy in page.entries { print("Retention policy \(policy.id)") } case let .failure(error): print(error) } } ``` ## Create Retention Policy Assignment To create new retention policy assignment call [`client.retentionPolicy.assign(policyId:assignedContentId:assignContentType:filterFields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC6assign8policyId015assignedContentH00fJ4Type12filterFields10completionySS_SSAA0c20PolicyAssignmentItemK0OSayAA19MetadataFieldFilterVGSgys6ResultOyAA0coP0CAA0A8SDKErrorCGctF) method to assign the policy. Retention policy can be assigned to a specific folder, to a metadata template or to the entire enterprise. ``` client.retentionPolicy.assign(policyId: "12345", assignedContentId: "1111", assignContentType: .folder) { result in guard case let .success(retentionPolicyAssignment) = result else { print("Error creating retention policy assignment") return } print("Retention policy assignment: \(retentionPolicyAssignment.id) was created") } ``` ## Get Retention Policy Assignment To retrieve information about a retention policy assignment, call [`client.retentionPolicy.getAssignment(assignmentId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC13getAssignment12assignmentId10completionySS_ys6ResultOyAA0c6PolicyG0CAA0A8SDKErrorCGctF) with the ID of the assignment. ``` client.retentionPolicy.getAssignment(assignmentId: "123456") { result in guard case let .success(retentionPolicyAssignment) = result else { print("Error getting retention policy assignment") return } print("Retention policy assignment: \(retentionPolicyAssignment.id)") } ``` ## Get Retention Policy Assignments To get a list of all retention policy assignments associated with a specified retention policy, call [`client.retentionPolicy.listAssignments(policyId:type:marker:limit:fields)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC15listAssignments8policyId4type6marker5limit6fieldsAA14PagingIteratorCyAA0C16PolicyAssignmentCGSS_AA0cpQ8ItemTypeOSgSSSgSiSgSaySSGSgtF). This method will return an iterator, which is used to get the assignments. ``` let iterator = client.retentionPolicy.listAssignments(policyId:"12345") iterator.next { results in switch results { case let .success(page): for assignment in page.entries { print("Retention policy assignment\(assignment.id)") } case let .failure(error): print(error) } } ``` You can also filter assignments by setting `type` parameter to one of values: `.folder`, `.metadataTemplate` or `.enterprise`: ``` let iterator = client.retentionPolicy.listAssignments(policyId:"12345", type: .folder) iterator.next { results in switch results { case let .success(page): for assignment in page.entries { print("Retention policy assignment\(assignment.id)") } case let .failure(error): print(error) } } ``` ## Delete Retention Policy Assignment To remove a retention policy assignment applied to content, call [`client.retentionPolicy.deleteAssignment(assignmentId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC16deleteAssignment12assignmentId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the assignment. ``` client.retentionPolicy.deleteAssignment(assignmentId: "123456") { result in guard case let .success = result else { print("Error deleting retention policy assignment") return } print("Retention policy assignment was deleted") } ``` ## Get File Version Retention A file version retention is a record for a retained file version. To get information for a specific file version retention record, call [`client.files.getVersionRetention(retentionId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC19getVersionRetention11retentionId10completionySS_ys6ResultOyAA04FilefG0CAA0A8SDKErrorCGctF) with the ID of the file version retention. ``` client.files.getVersionRetention(retentionId: "123456"){ result in guard case let .success(retention) = result else { print("Error getting file version retention") return } print("File version retention: \(retention.id)") } ``` ## Get File Version Retentions To retrieves all file version retentions for the given enterprise, call [`client.files.listVersionRetentions(fileId:fileVersionId:policyId:dispositionAction:dispositionBefore:dispositionAfter:limit:marker:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC21listVersionRetentions6fileId0hfI006policyI017dispositionAction0K6Before0K5After5limit6markerAA14PagingIteratorCyAA04FileF9RetentionCGSSSg_A2rA011DispositionL0OSg10Foundation4DateVSgAYSiSgARtF). This method will return an iterator, which is used to get the file version retentions. ``` let iterator = client.files.listVersionRetentions() iterator.next { results in switch results { case let .success(page): for retention in page.entries { print("File version retention \(retention.id)") } case let .failure(error): print(error) } } ``` ## Get Files Under Retention For Assignment To get all files under retention for assignment policy, call the [`client.retentionPolicy.listFilesUnderRetentionForAssignment(retentionPolicyAssignmentId:limit:marker:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC014listFilesUnderC13ForAssignment015retentionPolicyJ2Id5limit6markerAA14PagingIteratorCyAA4FileCGSS_SiSgSSSgtF) method. This method will return an iterator, which is used to get the [`File`](https://opensource.box.com/box-ios-sdk/Classes/File.html) objects under retention. ``` let iterator = client.retentionPolicy.listFilesUnderRetentionForAssignment(retentionPolicyAssignmentId: "123456") iterator.next { results in switch results { case let .success(page): for file in page.entries { print("File \(file.name ?? "")") } case let .failure(error): print(error) } } ``` ## Get File Versions Under Retention For Assignment To get all file versions under retention placed in the file objects for a retention policy assignment, call the [`client.retentionPolicy.listFileVersionsUnderRetentionForAssignment(retentionPolicyAssignmentId:limit:marker:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC021listFileVersionsUnderC13ForAssignment015retentionPolicyK2Id5limit6markerAA14PagingIteratorCyAA0G0CGSS_SiSgSSSgtF) method. This method will return an iterator, which is used to get the [`FileVersion`](https://opensource.box.com/box-ios-sdk/Classes/FileVersion.html) object nested in [`File`](https://opensource.box.com/box-ios-sdk/Classes/File.html) object. ``` let iterator = client.retentionPolicy.listFileVersionsUnderRetentionForAssignment(retentionPolicyAssignmentId: "123456") iterator.next { results in switch results { case let .success(page): for file in page.entries { print("File version \(file.fileVersion?.id ?? "")") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Recent Items A recent item object represents a file that has been recently accessed by a user. Items accessed either in the last 90 days or… # Recent Items A recent item object represents a file that has been recently accessed by a user. Items accessed either in the last 90 days or the last 1000 accessed items are tracked. - [Get Recent Items](#get-recent-items) ## Get Recent Items To get recently accessed items, call [`client.recentItems.list(marker: String?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/RecentItemsModule.html#/s:6BoxSDK17RecentItemsModuleC4list6marker5limit6fields10completionySSSg_SiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0C4ItemCGAA0A8SDKErrorCGctF). This method will return an iterator object, which is used to retrieve recent items. ``` let iterator = client.recentItems.list() iterator.next { results in switch results { case let .success(page): for item in page.entries { print("Interaction type is \(item.interactionType)") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Search Content Search Content Search with Shared Link Items Metadata Search Content Search To get a list of items matching a search query… # Search - [Content Search](#content-search) - [Content Search with Shared Link Items](#content-search-with-shared-link-items) - [Metadata Search](#metadata-search) ## Content Search To get a list of items matching a search query, call [`client.search.query(query:...)`](https://opensource.box.com/box-ios-sdk/Classes/SearchModule.html#/s:6BoxSDK12SearchModuleC5queryAD5scope14fileExtensions12createdAfter0I6Before07updatedJ00lK011sizeAtLeast0mN4Most12ownerUserIDs014ancestorFolderS08searchIn8itemType0V5Trash14metadataFilter6fields6offset5limit10completionySSSg_AA0C5ScopeOSgSaySSGSg10Foundation4DateVSgA4_A4_A4_s5Int64VSgA7_A0_A0_SayAA0c7ContentY0OGSgAA0c4ItemY0OSgSbSgAA08MetadataC6FilterCSgA0_SiSgA19_ys6ResultOyAA14PagingIteratorCyAA0U4ItemOGAA0A8SDKErrorCGctF) with the string to query for. There are many possible options for advanced search filtering, which can be used to narrow down the search results. This method will return an iterator object, which is used to get the results. ``` let iterator = client.search.query(query: "Quarterly Business Review") iterator.next { results in switch results { case let .success(page): for item in page.entries { switch item { case let .file(file): print("- File \(file.name) (ID: \(file.id))") case let .folder(folder): print("- Folder \(file.name) (ID: \(file.id))") case let .webLink(webLink): print("- Web Link \(file.name) (ID: \(file.id))") } } case let .failure(error): print(error) } } ``` ## Content Search with Shared Link Items To get a list of items matching a search query, including items that a user might have accessed recently through a shared link, call [`client.search.queryWithSharedLinks(query:...)`](https://opensource.box.com/box-ios-sdk/Classes/SearchModule.html#/s:6BoxSDK12SearchModuleC5queryAD5scope14fileExtensions12createdAfter0I6Before07updatedJ00lK011sizeAtLeast0mN4Most12ownerUserIDs014ancestorFolderS08searchIn8itemType0V5Trash14metadataFilter6fields6offset5limit10completionySSSg_AA0C5ScopeOSgSaySSGSg10Foundation4DateVSgA4_A4_A4_s5Int64VSgA7_A0_A0_SayAA0c7ContentY0OGSgAA0c4ItemY0OSgSbSgAA08MetadataC6FilterCSgA0_SiSgA19_ys6ResultOyAA14PagingIteratorCyAA0U4ItemOGAA0A8SDKErrorCGctF) with the string to query for. There are many possible options for advanced search filtering, which can be used to narrow down the search results. This method will return an iterator object, which is used to get the results. ``` let iterator = client.search.queryWithSharedLinks(query: "Quarterly Business Review") iterator.next { results in switch results { case let .success(page): for searchResult in page.entries { let item = searchResult.item switch item { case let .file(file): print("- File \(file.name) (ID: \(file.id))") case let .folder(folder): print("- Folder \(file.name) (ID: \(file.id))") case let .webLink(webLink): print("- Web Link \(file.name) (ID: \(file.id))") } } case let .failure(error): print(error) } } ``` ## Metadata Search To search within metadata for specific values, use the helper methods included in the SDK to construct the metadata query and call [`client.search.query(query:...)`](https://opensource.box.com/box-ios-sdk/Classes/SearchModule.html#/s:6BoxSDK12SearchModuleC5queryAD5scope14fileExtensions12createdAfter0I6Before07updatedJ00lK011sizeAtLeast0mN4Most12ownerUserIDs014ancestorFolderS08searchIn8itemType0V5Trash14metadataFilter6fields6offset5limit10completionySSSg_AA0C5ScopeOSgSaySSGSg10Foundation4DateVSgA4_A4_A4_s5Int64VSgA7_A0_A0_SayAA0c7ContentY0OGSgAA0c4ItemY0OSgSbSgAA08MetadataC6FilterCSgA0_SiSgA19_ys6ResultOyAA14PagingIteratorCyAA0U4ItemOGAA0A8SDKErrorCGctF) with the metadata filters and optionally a search query. If no additional content query string is needed, just set the `query` parameter to `nil`. This method will return an iterator object, which is used to get the results. ``` let metadataFilters = MetadataSearchFilter() metadataFilters.addFilter(templateKey: "contract", fieldKey: "contractType", fieldValue: "NDA") metadataFilters.addFilter(templateKey: "contract", fieldKey: "date", fieldValue: "2019-01-01T00:00:00Z", relation: .greaterThan) let iterator = client.search.query(query: nil, metadataFilter: metadataFilters) iterator.next { results in switch results { case let .success(page): for item in page.entries { switch item { case let .file(file): print("- File \(file.name) (ID: \(file.id))") case let .folder(folder): print("- Folder \(file.name) (ID: \(file.id))") case let .webLink(webLink): print("- Web Link \(file.name) (ID: \(file.id))") } } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Shared Items Shared Items represent files and folders on Box available via a shared link. Get Shared Item Get Shared Item To get the file or… # Shared Items Shared Items represent files and folders on Box available via a shared link. - [Get Shared Item](#get-shared-item) ## Get Shared Item To get the file or folder information for a shared link, call [`client.sharedItems.getSharedItem(sharedLinkURL:sharedLinkPassword:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/SharedItemsModule.html#/s:6BoxSDK17SharedItemsModuleC3get13sharedLinkURL0gH8Password6fields10completionySS_SSSgSaySSGSgys6ResultOyAA0C4ItemCAA0A8SDKErrorCGctF) with the URL of the shared link. The `sharedLinkPassword` parameter should be provided if the shared link is password-protected. ``` client.sharedItems.get( sharedLinkURL: "https://app.box.com/s/qqwertyuiopasdfghjklzxcvbnm123456" ) { (result: Result<SharedItem, BoxSDKError>) in guard case let .success(item) = result else { print("Error resolving shared item") return } print("The shared link resolves to item:") switch item { case let .file(file): print("- File \(file.name) (ID: \(file.id))") case let .folder(folder): print("- Folder \(file.name) (ID: \(file.id))") case let .webLink(webLink): print("- Web Link \(file.name) (ID: \(file.id))") } } ``` --- ## Untitled *Type: page* Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files… # Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files and can be sent to one or more Box Sign Request Signers. - [Create Sign Request](#create-sign-request) - [List Sign Requests](#list-sign-requests) - [Get Sign Request by ID](#get-sign-request-by-id) - [Cancel Sign Request by ID](#cancel-sign-request-by-id) - [Resend Sign Request by ID](#resend-sign-request-by-id) ## Create Sign Request To create a sign request, call [`client.signRequests.create(signers:sourceFiles:parentFolder:parameters:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC6create7signers11sourceFiles12parentFolder10parameters10completionySayAA0C19RequestCreateSignerVG_SayAA0cnO10SourceFileVGAA0cno6ParentK0VAA0cnO10ParametersVSgys6ResultOyAA0cN0CAA0A8SDKErrorCGctF) You need to provide at least one file and up to ten files (from which the signing document will be created) with at least one signer to receive the Sign Request and a destination folder. You should use [`SignRequestCreateSourceFile`](https://opensource.box.com/box-ios-sdk/Structs/SignRequestCreateSourceFile.html) ,[`SignRequestCreateSigner`](https://opensource.box.com/box-ios-sdk/Structs/SignRequestCreateSigner.html) and [`SignRequestCreateParentFolder`](https://opensource.box.com/box-ios-sdk/Structs/SignRequestCreateParentFolder.html) types to provide the necessary data. ``` let signers = [SignRequestCreateSigner(email: "signer@mail.com", role: .approver)] let sourceFiles = [SignRequestCreateSourceFile(id: "12345"), SignRequestCreateSourceFile(id: "34567")] let parentFolder = SignRequestCreateParentFolder(id: "234") client.signRequests.create(signers: signers, sourceFiles: sourceFiles, parentFolder: parentFolder) { (result: Result<SignRequest, BoxSDKError>) in guard case let .success(signRequest) = result else { print("Error creating sign request") return } print("Sign request \(signRequest.id) was created") } ``` [`create`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC6create7signers11sourceFiles12parentFolder10parameters10completionySayAA0C19RequestCreateSignerVG_SayAA0cnO10SourceFileVGAA0cno6ParentK0VAA0cnO10ParametersVSgys6ResultOyAA0cN0CAA0A8SDKErrorCGctF) method allows you to specify optional parameters using the [`SignRequestCreateParameters`](https://opensource.box.com/box-ios-sdk/Structs/SignRequestCreateParameters.html) object. ``` let signers = [SignRequestCreateSigner(email: "signer@mail.com", role: .approver)] let sourceFiles = [SignRequestCreateSourceFile(id: "12345", fileVersionId: "5")] let parentFolder = SignRequestCreateParentFolder(id: "234") let params = SignRequestCreateParameters( isDocumentPreparationNeeded: true, emailSubject: "Sign Request from Acme", emailMessage: "Hello! Please sign the document below" ) client.signRequests.create(signers: signers, sourceFiles: sourceFiles, parentFolder: parentFolder) { (result: Result<SignRequest, BoxSDKError>) in guard case let .success(signRequest) = result else { print("Error creating sign request") return } print("Sign request \(signRequest.id) was created") } ``` If you set `isDocumentPreparationNeeded` flag to true, you need to visit `prepareUrl` before the Sign Request will be sent. ## List Sign Requests To retrieve sign requests, call [`client.signRequests.list(marker:limit:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC4list6marker5limitAA14PagingIteratorCyAA0C7RequestCGSSSg_SiSgtF). This method will return an iterator object, which is used to get the sign requests. ``` let iterator = client.signRequests.list() iterator.next { results in switch results { case let .success(page): for signRequest in page.entries { print("Sign request \(signRequest.id)") } case let .failure(error): print(error) } } ``` ## Get Sign Request by ID To retrieve information about a sign request, call [`client.signRequests.getById(id:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC7getById2id10completionySS_ys6ResultOyAA0C7RequestCAA0A8SDKErrorCGctF) with the ID of the sign request. ``` client.signRequests.getById(id: "1234") { (result: Result<SignRequest, BoxSDKError>) in guard case let .success(signRequest) = result else { print("Error getting sign request") return } print("Sign request \(signRequest.id)") } ``` ## Cancel Sign Request by ID To cancel a created sign request, call [`client.signRequests.cancelById(id:, completion:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC10cancelById2id10completionySS_ys6ResultOyAA0C7RequestCAA0A8SDKErrorCGctF) ``` client.signRequests.cancelById(id: "1234") { (result: Result<SignRequest, BoxSDKError>) in guard case let .success(signRequest) = result else { print("Error cancelling sign request") return } print("Sign request \(signRequest.id) is cancelled") } ``` ## Resend Sign Request by ID To resend a sign request to all signers that have not signed it yet, call [`client.signRequests.resendById(id:, completion:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC10resendById2id10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF). There is an 10-minute cooling-off period between re-sending reminder emails. If this method is called during the cooling-off period, a BoxAPIError will be thrown. ``` client.signRequests.resendById(id: "1234") { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error resending sign request") return } print("Sign request successfully resent") } ``` --- ## Untitled *Type: page* Terms of Services Terms of Service are custom objects that the admin of an enterprise can configure. This will prompt the end user to accept… # Terms of Services Terms of Service are custom objects that the admin of an enterprise can configure. This will prompt the end user to accept/re-accept or decline the custom Terms of Service for custom applications built on Box Platform. - [Get Terms of Service By ID](#get-terms-of-service-by-id) - [Create Terms of Service](#create-terms-of-service) - [Update Terms of Service](#update-terms-of-service) - [List Terms of Services for an Enterprise](#list-terms-of-services-for-an-enterprise) - [Create User Status on Terms of Service](#create-user-status-on-terms-of-service) - [Update User Status of Terms of Service](#update-user-status-of-terms-of-service) - [Get User Status for Terms of Service](#get-user-status-for-terms-of-service) ## Get Terms of Service By ID To retrieve information about a terms of service, call [`client.termsOfService.get(tosId:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC3get5tosId6fields10completionySS_SaySSGSgys6ResultOyAA0cD7ServiceCAA0A8SDKErrorCGctF) with the ID of the terms of service. You can control which fields are returned in the resulting `Terms of Service` object by passing the `fields` parameter. ``` client.termsOfService.get( tosID: "12345" ) { (result: Result<TermsOfService, BoxSDKError>) in guard case let .success(termsOfService) = result else { print("Error getting terms of service information") return } print("Terms of Service with id: \(termsOfService.id) was retrieved") } ``` ## Create Terms of Service To create a terms of service, call [`client.termsOfService.create(status:tosType:text:fields:completion`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC6create6status7tosType4text6fields10completionyAA0cD13ServiceStatusO_AA0cdnJ0OSSSaySSGSgys6ResultOyAA0cdN0CAA0A8SDKErrorCGctF). You can control which fields are returned in the resulting `Terms of Service` object by passing the `fields` parameter. ``` client.termsOfService.create( status: .enabled, tosType: .managed, text: "Test Terms of Service" ) { (result: Result<TermsOfService, BoxSDKError>) in guard case let .success(termsOfService) = result else { print("Error creating terms of service") return } print("Terms of Service with id: \(termsOfService.id) was created") } ``` ## Update Terms of Service To update a terms of service, call [`client.termsOfService.update(tosId:text:status:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC6update5tosId4text6status6fields10completionySS_SSAA0cD13ServiceStatusOSaySSGSgys6ResultOyAA0cdN0CAA0A8SDKErrorCGctF) with the ID of the terms of service to update. You can control which fields are returned in the resulting `Terms of Service` object by passing the `fields` parameter. ``` client.termsOfService.update( tosId: "12345", text: "Updated Text String", status: TermsOfServiceStatus.enabled ) { (result: Result<TermsOfService, BoxSDKError>) in guard calse let .success(termsOfService) = result else { print("Error updating terms of service") return } print("Terms of Service with id: \(termsOfService.id) was updated with text: \(termsOfService.text)") } ``` ## List Terms of Services for an Enterprise To retrieve a list of terms of services for an enterprise, call [`client.termsOfService.listForEnterprise(tosType:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC17listForEnterprise7tosType6fields10completionyAA0cd7ServiceK0OSg_SaySSGSgys6ResultOySayAA0cdN0CGAA0A8SDKErrorCGctF) with the type of terms of service to retrieve. If left nil, then terms of services of both types, `managed` and `external` will be retrieved. You can control which fields are returned in the resulting `Terms of Service` objects by passing the `fields` parameter. ``` let termsOfServiceItems = client.termsOfService.listForEnterprise() print("Terms of Service with ID \(termsOfServiceItems[0].id) and Terms of Service with ID \(termsOfServiceItems[1].id) was retrieved.") ``` ## Create User Status on Terms of Service To accept or decline a terms of service for a user who has never accepted/declined this terms of service before call [`client.termsOfService.createUserStatus(tosId:isAccepted:userId:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC16createUserStatus5tosId10isAccepted04userK06fields10completionySS_SbSSSgSaySSGSgys6ResultOyAA0cd7ServicehI0CAA0A8SDKErrorCGctF). You can control which fields are returned in the resulting `Terms of Service User Status` object by passing the `fields` parameter. ``` client.termsOfService.createUserStatus( tosId: "12345", isAccepted: true, userId: "54321" ) { (result: Result<TermsOfServiceUserStatus, BoxSDKError>) in guard case let .success(userStatus) = result else { print("Error accepting Terms of Service for new user") return } print("User status for accepting of Terms of Service is \(userStatus.isAccepted)") } ``` ## Update User Status of Terms of Service To update a user status on a terms of service call [`client.termsOfService.updateUserStatus(userStatusId:isAccepted:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC16updateUserStatus04userI2Id10isAccepted6fields10completionySS_SbSaySSGSgys6ResultOyAA0cd7ServicehI0CAA0A8SDKErrorCGctF). You can control which fields are returned in the resulting `Terms of Service User Status` object by passing the `fields` parameter. ``` client.termsOfService.updateUserStatus( userStatusId: "12345", isAccepted: true ) { (result: Result<TermsOfServiceUserStatus, BoxSDKError>) in guard case let .success(userStatus) = result else { print("Error updating Terms of Service User Status") return } print("User status for updating of Terms of Service is \(userStatus.isAccepted)") } ``` ## Get User Status for Terms of Service To retrieve the user status for a user on a terms of service, call [`client.termsOfService.getUserStatus(tosId:userId:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC13getUserStatus5tosId04userK06fields10completionySS_SSSgSaySSGSgys6ResultOyAA0cd7ServicehI0CAA0A8SDKErrorCGctF) with the ID of the `Terms of Service` object and the ID of the user. ``` client.termsOfService.getUserStatus( tosId: "12345", userId: "54321" ) { (result: Result<TermsOfServiceUserStatus, BoxSDKError>) in guard case let .success(userStatus) = result else { print("Error retrieving user status for Terms of Service") return } print("User status with ID \(userStatus.id) was retrieved") } ``` --- ## Untitled *Type: page* Storage Policies Get Storage Policy Info Get Storage Policies Get Storage Policy Assignment Info Get Storage Policy Assignments Create… # Storage Policies - [Get Storage Policy Info](#get-storage-policy-info) - [Get Storage Policies](#get-storage-policies) - [Get Storage Policy Assignment Info](#get-storage-policy-assignment-info) - [Get Storage Policy Assignments](#get-storage-policy-assignments) - [Create Storage Policy Assignment](#create-storage-policy-assignment) - [Assign Storage Policy](#assign-storage-policy) - [Update Storage Policy Assignment](#update-storage-policy-assignment) - [Delete Storage Policy Assignment](#delete-storage-policy-assignment) ## Get Storage Policy Info To retrieve information about a storage policy, call [`client.storagePolicies.get(storagePolicyId: String, fields: [String]?, completion: @escaping Callback<StoragePolicy>)`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC3get15storagePolicyId6fields10completionySS_SaySSGSgys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the storage policy. You can control which fields are returned in the resulting `Storage Policy` object by passing the `fields` parameter. ``` client.storagePolicies.get(storagePolicyId: "22222") { (result: Result<StoragePolicy, BoxSDKError>) in guard case let .success(policy) = result else { print("Error getting storage policy") return } print("Policy ID is \(policy.id)") } ``` ## Get Storage Policies To retrieve the storage policies in an enterprise, call [`client.storagePolicies.listForEnterprise(marker: String?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC17listForEnterprise6marker5limit6fields10completionySSSg_SiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0C6PolicyCGAA0A8SDKErrorCGctF). This method will return an iterator, which is used to get the policies. ``` let iterator = client.storagePolicies.listForEnterprise() iterator.next { results in switch results { case let .success(page): for policy in page.entries { print("Storage policy \(policy.id)") } case let .failure(error): print(error) } } ``` ## Get Storage Policy Assignment Info To get storage policy assignment, call [`client.storagePolicies.getAssignment(storagePolicyAssignmentId: String, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC13getAssignment013storagePolicyG2Id6fields10completionySS_SaySSGSgys6ResultOyAA0ciG0CAA0A8SDKErrorCGctF) with the id of a storage policy assignment. ``` client.storagePolicy.getAssignment(storagePolicyAssignmentId: "1234") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error getting storage policy assignment") return } print("Storage policy assignment ID \(assignment.id)") } ``` ## Get Storage Policy Assignments To get storage policy assignments for a user or enterprise, call [`client.storagePolicies.listAssignments(resolvedForType: String, resolvedForId: String, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC15listAssignments15resolvedForType0hI2Id6fields10completionySS_SSSaySSGSgys6ResultOyAA0C16PolicyAssignmentCAA0A8SDKErrorCGctF). This always returns a single storage policy assignment. ``` client.storagePolicy.listAssignments(resolvedForType: "user", resolvedForId: "1234") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error getting storage policy assignment") return } print("Storage policy assignment for user \(assignment.assignedTo?.id) is \(assignment.id)") } ``` ## Assign Storage Policy To assign a storage policy, call [`client.storagePolicies.assign(storagePolicyId: String, assignedToType: String, assignedToId, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC6assign15storagePolicyId14assignedToType0jkI06fields10completionySS_S2SSaySSGSgys6ResultOyAA0cH10AssignmentCAA0A8SDKErrorCGctF). ``` client.storagePolicy.assign(storagePolicyId: "1234", assignedToType: "user", assignedToId: "123") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error assigning a storage policy") return } print("Created storage policy assignment ID is \(assignment.id). The ID of the user it is assigned to \(assignment.assignedTo?.id)") } ``` ## Force Assign Storage Policy To assign a storage policy, call [`client.storagePolicies.forceAssign(storagePolicyId: String, assignedToType: String, assignedToId, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC11forceAssign15storagePolicyId14assignedToType0klJ06fields10completionySS_S2SSaySSGSgys6ResultOyAA0cI10AssignmentCAA0A8SDKErrorCGctF). The difference between this call and the createPolicyAssignment() above is that this method will guarantee an update to the assignee's policy. If an assignee already has a policy assigned to it, the createPolicyAssignment() will return a 409 Conflict error. assignPolicy() will instead make an additional updatePolicyAssignment() call to replace the existing policy with the new policy for a policy assignment. ``` client.storagePolicy.forceAssign(storagePolicyId: "1234", assignedToType: "user", assignedToId: "123") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error assigning a storage policy") return } print("Created storage policy assignment ID is \(assignment.id). The ID of the user it is assigned to \(assignment.assignedTo?.id)") } ``` ## Update Storage Policy Assignment To update storage policy assignment, call [`client.storagePolicies.updateAssignment(storagePolicyId: String, assignedToType: String, assignedToId, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC16updateAssignment013storagePolicyG2Id0hiJ06fields10completionySS_SSSgSaySSGSgys6ResultOyAA0ciG0CAA0A8SDKErrorCGctF). ``` client.storagePolicy.updateAssignment(storagePolicyAssignmentId: "1234", storagePolicyId: "123") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error updating a storage policy assignment") return } print("Updated storage policy assignment \(assignment.id)") } ``` ## Delete Storage Policy Assignment To delete a storage policy assignment, call [`client.folders.deleteAssignment(storagePolicyAssignmentId: String, completion: @escaping Callback<Void>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC16deleteAssignment013storagePolicyG2Id10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the storage policy to delete. ``` client.storagePolicies.deleteAssignment(storagePolicyAssignmentId: "22222") { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting storage policy assignment") return } print("Storage policy assignment is successfully deleted.") } ``` --- ## Untitled *Type: page* Users Users represent an individual's account on Box. Get Current User Get User Upload User Avatar Get User Avatar Delete User Avatar Create… # Users Users represent an individual's account on Box. - [Get Current User](#get-current-user) - [Get User](#get-user) - [Upload User Avatar](#upload-user-avatar) - [Get User Avatar](#get-user-avatar) - [Delete User Avatar](#delete-user-avatar) - [Create User](#create-user) - [Create App User](#create-app-user) - [Update User](#update-user) - [Change User Login](#change-user-login) - [Delete User](#delete-user) - [Get Enterprise Users](#get-enterprise-users) - [Invite User to Enterprise](#invite-user-to-enterprise) - [Move User Content](#move-user-content) - [Get User Email Aliases](#get-user-email-aliases) - [Add User Email Alias](#add-user-email-alias) - [Remove User Email Alias](#remove-user-email-alias) - [Roll User Out of Enterprise](#roll-user-out-of-enterprise) ## Get Current User To retrieve information about the currently authenticated user, call [`client.users.getCurrent(fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC10getCurrent6fields10completionySaySSGSg_ys6ResultOyAA4UserCAA0A8SDKErrorCGctF). ``` client.users.getCurrent(fields: ["name", "login"]) { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error getting user information") return } print("Authenticated as \(user.name), with login \(user.login)") } ``` ## Get User To retrieve information about a specific user, call [`client.users.get(userId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC3get6userId6fields10completionySS_SaySSGSgys6ResultOyAA4UserCAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.get(userId: "33333", fields: ["name", "login"]) { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error getting user information") return } print("Got user \(user.name), with login \(user.login)") } ``` ## Upload User Avatar To add or update the avatar for a user, call [`client.users.uploadAvatar(userId:data:name:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC12uploadAvataryXeXeF) with the ID of the user, the data to be uploaded and the name of the file. Optionally you can also pass an progress closure, where upload progress will be reported. In return, you will get an object with links to several representations of an avatar within Box account The supported image extensions are `jpg`, `jpeg` and `png`. The image size cannot exceed 1024 * 1024 pixels or 1MB. ``` let image: UIImage = <YOUR_IMAGE_HERE> // Initialize image here e.g. from UIImagePickerController let data = image.jpegData(compressionQuality: 1)! client.users.uploadAvatar(userId: "33333", data: data, name: "avatar.jpeg") { result in guard case let .success(uploadAvatar) = result else { print("Error uploading user avatar") return } print("User avatar uploaded successfully!") } ``` Alternatively, you can upload the avatar by passing the `InputStream` the method [`client.users.streamUploadAvatar(userId:stream:name:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC18streamUploadAvataryXeXeF). ``` let stream = InputStream(fileAtPath: "PATH_TO_IMAGE_FILE_HERE") client.users.streamUploadAvatar(userId: "33333", stream: data, name: "avatar.jpeg") { result in guard case let .success(uploadAvatar) = result else { print("Error uploading user avatar") return } print("User avatar uploaded successfully!") } ``` Please remember that in both of these methods, the `name` parameter should also contains file extension (.jpg, .jpeg or .png). ## Get User Avatar To retrieve the avatar image for a user, call [`client.users.getAvatar(userId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC9getAvatar6userId10completionySS_ys6ResultOy10Foundation4DataVAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.getAvatar(userId: "33333") { (result: Result<Data, BoxSDKError>) in guard case let .success(avatarData) = result else { print("Error getting user avatar") return } let avatarImage = UIImage(data: avatarData) } ``` ## Delete User Avatar To remove existing user avatar, call [`client.users.deleteAvatar(userId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC12deleteAvatar6userId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.deleteAvatar(userId: "33333") { result in guard case .success = result else { print("Error deleting avatar") return } print("Avatar successfully deleted") } ``` ## Create User As an admin user or service account, create a new user in your enterprise by calling [`client.users.create(login:name:...)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC6create5login4name4role8language13isSyncEnabled8jobTitle5phone7address11spaceAmount13trackingCodes013canSeeManagedC08timezone0J24ExternalCollabRestricted0J22ExemptFromDeviceLimits0J27ExemptFromLoginVerification6status6fields10completionySS_SSAA8UserRoleOSgSSSgSbSgA3Zs5Int64VSgSayAA4UserC12TrackingCodeVGSgA_AZA_A_A_AA10UserStatusOSgSaySSGSgys6ResultOyA4_AA0A8SDKErrorCGctF) with the login email address and name for the user. ``` client.users.create(login: "new.user@example.com", name: "New User") { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error creating user") return } print("Created user \(user.name), with login \(user.login)") } ``` ## Create App User To create an [app user](https://developer.box.com/docs/user-types#section-app-user), call [`client.users.createAppUser(name:...)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC13createAppUser4name8language8jobTitle8timezone5phone7address11spaceAmount6status26isExternalCollabRestricted013canSeeManagedC06fields10completionySS_SSSgA4Qs5Int64VSgAA0G6StatusOSgSbSgAXSaySSGSgys6ResultOyAA0G0CAA0A8SDKErrorCGctF) with the a name for that user. ``` client.users.createAppUser(name: "Doug") { (result: Result<User, BoxSDKError>) in guard case let .success(appUser) = result else { print("Error creating app user") return } print("Created app user with ID \(appUser.id)") } ``` ## Update User To update the information on a user, call [`client.users.updateUser(userId:...)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC6update6userId5login4name4role8language13isSyncEnabled8jobTitle5phone7address11spaceAmount13trackingCodes013canSeeManagedC08timezone0L24ExternalCollabRestricted0L22ExemptFromDeviceLimits0L27ExemptFromLoginVerification6status6fields10completionySS_SSSgAxA8UserRoleOSgAXSbSgA3Xs5Int64VSgSayAA4UserC12TrackingCodeVGSgA0_AXA0_A0_A0_AA10UserStatusOSgSaySSGSgys6ResultOyA5_AA0A8SDKErrorCGctF) with the ID of the user and the properties to update. The result is the updated user object. ``` // Restrict the user from collaborating content externally client.users.update(userId: "33333", isExternalCollabRestricted: true) { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error updating user") return } print("Updated user \(user.name), with login \(user.login)") } ``` ## Change User Login **Note:** In order to change the user's login email, the new email address must first be added as an email alias and the address must be confirmed. To change a user's login email, call [`client.users.changeLogin(userId:login:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC11changeLogin6userId5login6fields10completionySS_SSSaySSGSgys6ResultOyAA4UserCAA0A8SDKErrorCGctF) with the ID of the user and the new login email. ``` client.users.changeLogin(userId: "33333", login: "updated.address@example.com") { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error updating user email") return } print("User \(user.name) (ID: \(user.id)) now has login \(user.login)") } ``` ## Delete User To delete a user, which removes their access to Box, call [`client.users.delete(userId:notify:force:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC6delete6userId6notify5force10completionySS_SbSgAIys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the user. By default, the user will not be deleted if they have any content remaining in their account. To delete the user and any content that is in their account, set the `force` parameter to `true`. ``` client.users.delete(userId: "33333") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting user") return } print("User successfully deleted") } ``` ## Get Enterprise Users To retrieve the users in an enterprise, call [`client.users.listForEnterprise(filterTerm:fields:offset:limit:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC17listForEnterprise10filterTerm6fields9usemarker6marker6offset5limit10completionySSSg_SaySSGSgSbSgALSiSgAPys6ResultOyAA14PagingIteratorCyAA4UserCGAA0A8SDKErrorCGctF). The method returns an iterator object, which is used to get the users. ``` let iterator = client.users.listForEnterprise() iterator.next { result in switch results { case let .success(page): for user in page.entries { print("\(user.name) (ID: \(user.id))") } case let .failure(error): print(error) } } ``` ## Invite User to Enterprise To invite a user who already has a Box account to join an enterprise, call [`client.users.inviteToJoinEnterprise(login:enterpriseId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC22inviteToJoinEnterprise5login12enterpriseId6fields10completionySS_SSSaySSGSgys6ResultOyAA6InviteCAA0A8SDKErrorCGctF) with the login email of the user and the ID of the enterprise. ``` client.users.inviteToJoinEnterprise( login: "user@example.com", enterpriseId: "12345" ) { (result: Result<Invite, BoxSDKError>) in guard case let .success(invite) = result else { print("Error inviting user to enterprise") return } print("Invited user \(invite.actionableBy.name) to \(invite.invitedTo.name)") } ``` ## Move User Content Before deleting a user, it is recommended to move all content they own to another user. This can be done by calling [`client.users.moveItemsOwnedByUser(withID:toUserWithID:notify:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC20moveItemsOwnedByUser6withID02toi4WithK06notify6fields10completionySS_SSSbSgSaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with the ID of the source and destination users. The result of this method is a new folder created in the destination user's root folder, containing all content previously owned by the source user. ``` client.users.moveItemsOwnedByUser(withID: "33333", toUserWithID: "44444") { (result: Result<Folder, BoxSDKError>) in guard case let .success(folder) = result else { print("Error moving user content") return } print("Folder ID \(folder.id) created with migrated content") } ``` ## Get User Email Aliases To retrieve the list of email aliases associated with a user, call [`client.users.listEmailAliases(userId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC16listEmailAliases6userId10completionySS_ys6ResultOyAA14EntryContainerCyAA0F5AliasCGAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.listEmailAliases(userId: "33333") { (result: Result<EntryContainer<User>, BoxSDKError>) in guard case let .success(aliasCollection) = result else { print("Error retrieving email aliases") return } print("User has \(aliasCollection.totalCount) email aliases:") for alias in aliasCollection.entries { print("- \(alias.email) (\(alias.isConfirmed ? "Confirmed" : "Not Confirmed"))") } } ``` ## Add User Email Alias To associate a new email alias with a user, call [`client.users.createEmailAlias(userId:email:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC23createEmailAliasForUser6userId5email10completionySS_SSys6ResultOyAA0fG0CAA0A5ErrorOGctF) with the ID of the user and the email address to add as an alias. ``` client.users.createEmailAlias( userId: "33333", email: "user+alias@example.com" ) { (result: Result<EmailAlias, BoxSDKError>) in guard case let .success(alias) = result else { print("Error adding email alias") return } print("Added email alias \(alias.email) — user must confirm") } ``` ## Remove User Email Alias To remove a user's email alias, call [`client.users.deleteEmailAlias(userId:emailAliasId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC16deleteEmailAlias6userId05emailgI010completionySS_SSys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the user and the ID of the email alias to remove. ``` client.users.deleteEmailAlias(userId: "33333", emailAliasId: "99999") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing email alias") return } print("Successfully removed email alias") } ``` ## Roll User Out of Enterprise To roll a user out of an enterprise, converting them to a free user, call [`client.users.rollOutOfEnterprise(userId:notify:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC19rollOutOfEnterprise6userId6notify6fields10completionySS_SbSgSaySSGSgys6ResultOyAA4UserCAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.rollOutOfEnterprise(userId: "33333") { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error removing user from enterprise") return } print("User \(user.name) successfully removed from enterprise") } ``` --- ## Untitled *Type: page* Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link… # Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects. - [Create Web Link](#create-web-link) - [Get Web Link](#get-web-link) - [Update Web Link](#update-web-link) - [Delete Web Link](#delete-web-link) - [Set Shared Link](#set-shared-link) - [Remove Shared Link](#remove-shared-link) ## Create Web Link To create a web link with a specified name and description, call [`client.webLinks.create(url:parentId:name:description:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC6create3url8parentId4name11description6fields10completionySS_S2SSgAKSaySSGSgys6ResultOyAA0C4LinkCAA0A8SDKErrorCGctF). ``` client.webLinks.create( url: "https://www.example.com", parentId: "22222", name: "Link to Example", description: "This goes to an example page" ) { (result: Result<WebLink, BoxSDKError>) in guard case let .success(webLink) = result else { print("Error creating web link") return } print("WebLink \(webLink.name) was created at \(webLink.createdAt)") } ``` ## Get Web Link To retrieve information about a web link, call [`client.webLinks.get(webLinkId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC3get9webLinkId6fields10completionySS_SaySSGSgys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of web link. You can control which fields are returned in the resulting `WebLink` object by passing the `fields` parameter. ``` client.webLinks.get(webLinkId: "11111", fields: ["name", "created_at"]) { (result: Result<WebLink, BoxSDKError>) in guard case let .success(webLink) = result else { print("Error retrieving web link information") return } print("WebLink \(webLink.name) was created at \(webLink.createdAt)") } ``` ## Update Web Link To update a web link record, call [`client.webLinks.update(webLinkId:url:parentId:name:description:sharedLink:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC6update9webLinkId3url06parentI04name11description06sharedH06fields10completionySS_SSSgA3mA17NullableParameterOyAA06SharedH4DataVGSgSaySSGSgys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the web link to update and the properties to update. ``` client.webLinks.update(webLinkId: "11111", name: "new name for weblink") { (result: Result<WebLink, BoxSDKError>) in guard case let .success(webLink) = result else { print("Error updating web link information") return } print("WebLink \(webLink.name) was updated successfully") } ``` ## Delete Web Link To delete a web link, call [`client.webLinks.delete(webLinkId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC6delete9webLinkId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the web link to delete. ``` client.webLinks.delete(webLinkId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing web link") return } print("WebLink removed") } ``` ## Set Shared Link To add or update the shared link for a web link, call [`client.webLinks.setSharedLink(forWebLink:access:unsharedAt:vanityName:password:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC13setSharedLink03forcH06access10unsharedAt10vanityName8password10completionySS_AA0gH6AccessOSgAA17NullableParameterOy10Foundation4DateVGSgAOySSGSgAVys6ResultOyAA0gH0CAA0A8SDKErrorCGctF) with the ID of the web link and the shared link properties to set. ``` client.webLinks.setSharedLink(forWebLink: "11111", access: .open) { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error setting weblink shared link") return } print("WebLink shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` ## Remove Shared Link To remove a webLink's shared link, call [`client.webLinks.deleteSharedLink(forWebLink:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC16deleteSharedLink03forcH010completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file. ``` client.webLinks.deleteSharedLink(forWebLink: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing weblink shared link") return } print("WebLink shared link removed") } ``` --- ## Untitled *Type: page* Webhooks Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your… # Webhooks Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your application when they occur. A webhook notifies your application by sending HTTP requests to a URL of your choosing. A webhook object contains information about a webhook like the triggers, the URL, etc. - [Get Webhooks](#get-webhooks) - [Get Webhook Info](#get-webhook-info) - [Create Webhook](#create-webhook) - [Update Webhook](#update-webhook) - [Delete Webhook](#delete-webhook) ## Get Webhook Info To retrieve information about a webhook, call [`client.webhooks.get(webhookId: String, fields: [String]?, completion: @escaping Callback<Webhook>)`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC3get9webhookId6fields10completionySS_SaySSGSgys6ResultOyAA7WebhookCAA0A8SDKErrorCGctF) with the ID of the webhook. You can control which fields are returned in the resulting `Webhook` object by passing the `fields` parameter. ``` client.folders.get(webhookId: "22222", fields: ["id", "created_at"]) { (result: Result<Webhook, BoxSDKError>) in guard case let .success(webhook) = result else { print("Error getting webhook information") return } print("Webhook \(webhook.id) was created at \(webhook.createdAt)") } ``` ## List Webhooks To retrieve information about webhooks in an enterprise, call [`client.webhook.list(webhookId: String, marker: String?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC4list6marker5limit6fields10completionySSSg_SiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA7WebhookCGAA0A8SDKErrorCGctF). This method will return an iterator object, which is used to get the webhooks. ``` let iterator = client.webhooks.list() iterator.next { results in switch results { case let .success(page): for webhook in page.entries { print("Webhook \(webhook.id) was created at \(webhook.createdAt)") } case let .failure(error): print(error) } } ``` ## Create Webhook To create a new webhook, call [`client.webhooks.create(targetType: String, targetId: String, triggers: [Webhook.EventTriggers], address: String, fields: [String]?, completion: @escaping Callback<Webhook>`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC6create10targetType0F2Id8triggers7address6fields10completionySS_SSSayAA7WebhookC13EventTriggersOGSSSaySSGSgys6ResultOyAlA0A8SDKErrorCGctF) ``` client.webhooks.create(targetType: "file", targetId: "1234", triggers: [.fileDownloaded], address: "www.testurl.com") { (result: Result<Webhook, BoxSDKError>) in guard case let .success(webhook) = result else { print("Error creating webhook") return } print("Created webhook \"\(webhook.id)\"") } ``` ## Update Webhook To update a webhook, call [`client.webhooks.update(webhookId: String, targetType: String?, targetId: String?, triggers: [Webhook.EventTriggers]?, address: String?, fields: [String]?, completion: @escaping Callback<Webhook>`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC6update9webhookId10targetType0hG08triggers7address6fields10completionySS_SSSgALSayAA7WebhookC13EventTriggersOGSgALSaySSGSgys6ResultOyAnA0A8SDKErrorCGctF) ``` client.webhooks.update(webhookId: "1234", targetType: "file", targetId: "1234", address: "www.testurl.com") { (result: Result<Webhook, BoxSDKError>) in guard case let .success(webhook) = result else { print("Error updating webhook") return } print("Updated webhook address to \"\(webhook.address)\"") } ``` ## Delete Webhook To delete a webhook, call [`client.webhooks.delete(webhookId: String, completion: @escaping Callback<Void>`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC6delete9webhookId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) ``` client.webhooks.delete(webhookId: "22222") { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting webhook") return } print("Webhook successfully deleted") } ``` --- ## Untitled *Type: page* Authentication Authentication Ways to Authenticate Developer Token Server Auth with JWT Traditional 3-Legged OAuth2 Client Credentials Grant… # Authentication [Authentication](#authentication) [Ways to Authenticate](#ways-to-authenticate) - [Developer Token](#developer-token) - [Server Auth with JWT](#server-auth-with-jwt) - [Traditional 3-Legged OAuth2](#traditional-3-legged-oauth2) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) [Token Store](#token-store) [As-User](#as-user) [Token Exchange](#token-exchange) [Revoking Tokens](#revoking-tokens) The Box API uses two flavors of OAuth2 for authentication, both of which can can be difficult to implement. The SDK makes it easier by providing classes that handle obtaining tokens and automatically refreshing them when possible. See the [Auth Types documentation](https://developer.box.com/docs/authentication-types-and-security) for a detailed overview of how the Box API handles authentication and how to choose between the different authentication types. ## Ways to Authenticate ### Developer Token The fastest way to get started using the API is with developer tokens. A developer token is a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for use in production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. The following example creates an SDK client with a developer token: ``` import BoxSDK let client = BoxSDK.getClient(token: "YOUR_DEVELOPER_TOKEN") ``` ### Server Auth with JWT Server auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/docs/service-account) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. JWT Authentication requires a private key for signing the JSON Web Token, which is then exchanged for a valid Box access token that can be used to call the API. It is not secure to store this private key in a mobile app that is publicly distributed, so in order to use JWT Authentication the SDK requires that generation of the access token happens in some other service or process. The SDK can then make a request to that service for access tokens to use. To use the SDK with JWT Auth, you'll need to provide a block of code that is responsible for requesting a new token when one is needed. This block can call out to a web service or other endpoint that is responsible for generating the token. The block receives the unique ID of the user who needs to be authenticated, and a completion function to call with the results of the authentication. ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE") func getTokensFromAuthServer(uniqueID: String, completion: @escaping (Result<AccessTokenTuple, Error>) -> Void) { // Call auth service with unique ID; it passes back the access token and time-to-live (TTL) in seconds completion(.success((accessToken: accessToken, expiresIn: accessTokenTTLinSeconds))) } // Create client with unique ID — note that this can be any value your application understands. The unique // ID is a mechanism for your application to keep track of or map your users to Box sdk.getDelegatedAuthClient(authClosure: getTokensFromAuthServer, uniqueID: "myUser12345") { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` As an alternative, you can call `async` version of `getDelegatedAuthClient(authClosure:uniqueID:)` method: ``` do { let client = try await sdk.getDelegatedAuthClient(authClosure: getTokensFromAuthServer, uniqueID: "myUser12345") // Use client to make API calls } catch { // Handle error creating client } ``` ### Traditional 3-Legged OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/docs/oauth-20). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. The SDK provides a built-in flow for opening a secure web view, into which the user enters their Box login credentials. This requires that the application using the SDK registers itself for a custom URL scheme of the format `boxsdk-<<CLIENT ID>>://boxsdkoauth2redirect`. ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE") sdk.getOAuth2Client() { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` As an alternative, you can call `async` version of `getOAuth2Client()` method: ``` do { let client = try await sdk.getOAuth2Client(tokenStore: KeychainTokenStore()) // Use client to make API calls } catch { // Handle error creating client } ``` If your application requires a custom URL scheme that differs from the default format `boxsdk-<<CLIENT ID>>://boxsdkoauth2redirect`, you have the option to pass in a custom callback URL string when creating the SDK client. This is the URL to which Box will redirect the user when authentication completes. This requires that the application using the SDK registers itself for the same custom callback URL. ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE", callbackURL: "YOUR CALLBACK URL HERE") sdk.getOAuth2Client() { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` ### Client Credentials Grant Server auth with CCG allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account. Obtained token is valid for specified amount of time and it will be refreshed automatically by default. A detailed guide for this process is available in the [Setup with Client Credentials Grant](https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/). #### Obtaining Service Account token By default, your application has a [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID: ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE") sdk.getCCGClientForAccountService(enterpriseId: "YOUR ENTERPRISE ID HERE") { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` As an alternative, you can call `async` version of `getCCGClientForAccountService(enterpriseId:)` method: ``` do { let client = try await sdk.getCCGClientForAccountService(enterpriseId: "YOUR ENTERPRISE ID HERE") // Use client to make API calls } catch { // Handle error creating client } ``` Remember that you can still make calls on behalf of managed users, which are part of your enterprise, by using [As-User](#as-user) behavior. #### Obtaining User token To obtain client for making calls as an App User or Managed User you will have to provide user ID: ``` import BoxSDK let sdk = BoxSDK(clientId: "YOUR CLIENT ID HERE", clientSecret: "YOUR CLIENT SECRET HERE") sdk.getCCGClientForUser(userId: "YOUR USER ID HERE") { result in switch result { case let .success(client): // Use client to make API calls case let .failure(error): // Handle error creating client } } ``` As an alternative, you can call `async` version of `getCCGClientForUser(userId:)` method: ``` do { let client = try await sdk.getCCGClientForUser(userId: "YOUR USER ID HERE") // Use client to make API calls } catch { // Handle error creating client } ``` ## Token Store In order to maintain authentication and ensure that your users do not need to log in again every time they use your application, you should persist their token information to some sort of durable store (e.g. the Keychain). The SDK provides a `TokenStore` interface which allows you to read and write tokens to whatever store your application uses at the correct points in the SDK's token handling logic. The interface requires three methods: The SDK provides a default `KeychainTokenStore` implementation that stores the user's tokens on the device Keychain, but you can also create your own custom token store by implementing something that conforms to the `TokenStore` protocol: ``` // The token store constructor should create a specific store instance for the user being authenticated — it may need // to take in a user ID or other unique identifier public protocol TokenStore { // Read the user's tokens from the data store and pass them to the completion func read(completion: @escaping (Result<TokenInfo, Error>) -> Void) // Write the token information to the store. The tokenInfo argument can be serialized for storage. // Call the completion after the write has completed. func write(tokenInfo: TokenInfo, completion: @escaping (Result<Void, Error>) -> Void) // Delete the user's token information from the store, and call the completion after the write. func clear(completion: @escaping (Result<Void, Error>) -> Void) } ``` ## As-User The `As-User` header is used to make API calls from one user account on behalf of another user. This is used by enterprise administrators and Service Accounts to make API calls on behalf of managed users or app users. This requires the API request to contain an `As-User: USER-ID` header with each API call, which the SDK handles automatically. For more details, see the [documentation on As-User](https://developer.box.com/reference#as-user-1). The following examples assume that the `client` has been instantiated with an access token belonging to an admin-role user or Service Account with appropriate privileges to make As-User calls. The `BoxClient#asUser(withId: String)` method clones the client to impersonate a given user. Note that a new client is created, and the original client instance is left unmodified. All calls made with the new instance of client will be made in context of the impersonated user. ``` let asUserClient = client.asUser(withId: "USER ID"); asUserClient.users.getCurrentUser() { result in guard case let .success(user) = result else { print("Could not retrieve user info!") return } print("Call was made as \(user.name) (\(user.login))") } ``` ## Token Exchange You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). To exchange the token held by a client for a new token with only `item_preview` scope, restricted to a single file: ``` client.exchangeToken(scope: ["item_preview"], resource: "https://api.box.com/2.0/files/123456789") { result in guard case let .success(tokenInfo) = result else { print("Error exchanging tokens") return } print("Got new access token: \(tokenInfo.accessToken)") } ``` ## Revoking Tokens Access tokens for a client can be revoked when needed. This removes the client's authentication, and the client can no longer be used after this operation. ``` client.destroy() { result in guard case .success = result else { print("Tokens could not be revoked!") } print("Tokens were successfully revoked") } ``` --- ## Untitled *Type: page* Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. Get Comment Create Comment Update… # Comments Comment objects represent a user-created comment on a file. They can be added directly to a file. - [Get Comment](#get-comment) - [Create Comment](#create-comment) - [Update Comment](#update-comment) - [Delete Comment](#delete-comment) ## Get Comment To retrieve information about a comment, call [`client.comments.get(commentId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CommentsModule.html#/s:6BoxSDK14CommentsModuleC3get9commentId6fields10completionySS_SaySSGSgys6ResultOyAA7CommentCAA0A8SDKErrorCGctF) with the ID of the comment. ``` client.comments.get(commentId: "55555") { (result: Result<Comment, BoxSDKError>) in guard case let .success(comment) = result else { print("Error retrieving comment") return } print("Comment reads: \"\(comment.message)\"") } ``` ## Create Comment To create a comment, call [`client.comments.create(itemId:itemType:message:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CommentsModule.html#/s:6BoxSDK14CommentsModuleC6create6itemId0F4Type7message6fields10completionySS_S2SSaySSGSgys6ResultOyAA7CommentCAA0A8SDKErrorCGctF) with the type and ID of the item to add a comment to, as well as the comment message. ``` client.comments.create( itemId: "11111", itemType: "file", message: "Thanks!" ) { (result: Result<Comment, BoxSDKError>) in guard case let .success(comment) = result else { print("Error creating comment") return } print("Added comment to \(comment.item.name): \"\(comment.message)\"") } ``` ## Update Comment To update a comment, call [`client.comments.update(commentId:message:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CommentsModule.html#/s:6BoxSDK14CommentsModuleC6update9commentId7message6fields10completionySS_SSSaySSGSgys6ResultOyAA7CommentCAA0A8SDKErrorCGctF) with the ID of the comment to update and the properties to update. ``` client.comments.update( commentId: "55555", message: "Updated message" ) { (result: Result<Comment, BoxSDKError>) in guard case let .success(comment) = result else { print("Error updating comment") return } print("Comment message updated") } ``` ## Delete Comment To delete a comment, call [`client.comments.delete(commentId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CommentsModule.html#/s:6BoxSDK14CommentsModuleC6delete9commentId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the comment to delete. ``` client.comments.delete(commentId: "55555") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting comment") return } print("Comment deleted") } ``` --- ## Untitled *Type: page* Collaborations Collaborations are used to share folders and files between users or groups. They also define what permissions a user has for… # Collaborations Collaborations are used to share folders and files between users or groups. They also define what permissions a user has for a folder or file. - [Get Collaboration](#get-collaboration) - [Add Collaboration](#add-collaboration) - [Update Collaboration](#update-collaboration) - [Delete Collaboration](#delete-collaboration) - [Get Pending Collaborations](#get-pending-collaborations) ## Get Collaboration To retrieve a Collaboration record from the API, call [`client.collaborations.get(collaborationId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC3get15collaborationId6fields10completionySS_SaySSGSgys6ResultOyAA13CollaborationCAA0A8SDKErrorCGctF) with the ID of the collaboration. ``` client.collaborations.get(collaborationId: "12345") { (result: Result<Collaboration, BoxSDKError>) in guard case let .success(collaboration) = result else { print("Error retrieving collaboration") return } let collaborator: String switch collaboration.accessibleBy.collaboratorValue { case let .user(user): collaborator = "user \(user.name)" case let .group(group): collaborator = "group \(group.name)" } let itemName: String switch collaboration.item { case let .file(file): itemName = file.name case let .folder(folder): itemName = folder.name case let .webLink(webLink): itemName = webLink.name } print("Collaboration \(collaboration.id) gives \(collaborator) access to \(itemName)") } ``` ## Add Collaboration To add a collaborator to an item, call [`client.collaborations.create(itemType:itemId:role:accessibleBy:accessibleByType:canViewPath:fields:notify:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC6create8itemType0F2Id4role12accessibleBy0jkG011canViewPath6fields6notify10completionySS_SSAA17CollaborationRoleOSSAA010AccessibleK0OSbSgSaySSGSgARys6ResultOyAA0R0CAA0A8SDKErrorCGctF) with the type and ID of the item, as well as the type and ID of the collaborator — a user or a group. A `role` for the collaborator must be specified, which will determine the permissions the collaborator receives on the item. To collaborate a user, pass in a user id and the `.user` accessible by type. ``` client.collaborations.create( itemType: "folder", itemId: "22222", role: .editor, accessibleBy: "33333", accessibleByType: .user ) { (result: Result<Collaboration, BoxSDKError>) in guard case let .success(collaboration) = result else { print("Error creating collaboration") return } print("Collaboration successfully created") } ``` To collaborate a group, pass in a group id and the `.group` accessible by type. ``` client.collaborations.create( itemType: "folder", itemId: "22222", role: .editor, accessibleBy: "44444", accessibleByType: .group ) { (result: Result<Collaboration, BoxSDKError>) in guard case let .success(collaboration) = result else { print("Error creating collaboration") return } print("Collaboration successfully created") } ``` ## Update Collaboration To update a collaboration record, call [`client.users.update(collaborationId:role:status:canViewPath:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC6update15collaborationId4role6status11canViewPath6fields10completionySS_AA17CollaborationRoleOAA0O6StatusOSgSbSgSaySSGSgys6ResultOyAA0O0CAA0A8SDKErrorCGctF) with the ID of the collaboration to update and the properties to update, including at least the `role`. ``` client.collaborations.update(collaborationId: "12345", role: .viewer) { (result: Result<Collaboration, BoxSDKError>) in guard case let .success(collaboration) = result else { print("Error updating collaboration") return } print("Updated collaboration") } ``` ## Delete Collaboration To delete a collaboration, removing the collaborator's access to the relevant item, call [`client.collaborations.delete(collaborationId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC6delete15collaborationId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the collaboration to delete. ``` client.collaborations.delete(collaborationId: "12345") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting collaboration") return } print("Collaboration deleted") } ``` ## Get Pending Collaborations To retrieve a list of the pending collaborations requiring the user to accept or reject them, call [`client.collaborations.listPendingForEnterprise(offset:limit:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/CollaborationsModule.html#/s:6BoxSDK20CollaborationsModuleC24listPendingForEnterprise6offset5limit6fields10completionySiSg_AISaySSGSgys6ResultOyAA14PagingIteratorCyAA13CollaborationCGAA0A8SDKErrorCGctF). The method returns an iterator, which is used to get pending collaborations. ``` let iterator = client.collaborations.listPendingForEnterprise() iterator.next { result in switch result { case let .success(page): for collaboration in page.entries { print("Collaboration created by \(collaboration.createdBy?.name)") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Custom API Calls There are a few situations, where a user might want to make a custom API call — utilizing the SDK's authentication handling… # Custom API Calls There are a few situations, where a user might want to make a custom API call — utilizing the SDK's authentication handling, but creating the API request manually: - When new endpoints and parameters have been introduced to the API, but they are not yet supported directly by the SDK - Beta endpoints, that are not yet suitable for inclusion in the SDK - Hitting URLs specified directly in the response of another API call, e.g. Representation Info and Download URLs For these reasons BoxClient exposes this functionality through a set of methods on the client mapping to HTTP verbs: ``` client.get(/*...*/) client.post(/*...*/) client.put(/*...*/) client.delete(/*...*/) client.options(/*...*/) ``` and additionally a HTTP GET method call for downloading: ``` client.download(/*...*/) ``` Moreover, the SDK exposes a low-level method that is used under the hood by the all previous methods. However because of its complexity, we recommend that you should only use this method if all the other options do not suit your needs. ``` client.send(/*...*/) ``` [Custom API Calls](#custom-api-calls) - [Create URL](#create-url) - [Deserialize Response Body](#deserialize-response-body) [API Calls](#api-calls) - [Custom GET](#custom-get) - [Custom POST](#custom-post) - [Custom PUT](#custom-put) - [Custom DELETE](#custom-delete) - [Custom OPTIONS](#custom-options) - [Download](#download) - [Send](#send) ## Create URL When you want to execute custom API call, you must specify a destination URL. You can create it by yourself: ``` let fileId = "<YOUR_FILE_ID_HERE>" let url = URL(string: "https://api.box.com/2.0/files/\(fileId)")! ``` or you can use SDK's predefined method: [`URL.boxAPIEndpoint(_ endpoint:configuration)`](https://opensource.box.com/box-ios-sdk/Extensions/URL.html#/s:10Foundation3URLV6BoxSDKE14boxAPIEndpoint_13configurationACSS_AD0C16SDKConfigurationVtFZ) ``` let fileId = "<YOUR_FILE_ID_HERE>" let url = URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration) ``` The `boxAPIEndpoint` method requires to pass an endpoint path and configuration from the current `BoxClient` instance. It internally fetches `apiBaseURL` and appends to it the endpoint path you passed. The default value of `apiBaseURL` is `https://api.box.com`, but you can change it with [`sdk.updateConfiguration(apiBaseURL:uploadApiBaseURL:oauth2AuthorizeURL:maxRetryAttempts:tokenRefreshThreshold:consoleLogDestination:fileLogDestination:clientAnalyticsInfo:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxSDK.html#/s:6BoxSDKAAC19updateConfiguration10apiBaseURL09uploadApifG0015oauth2AuthorizeG016maxRetryAttempts21tokenRefreshThreshold21consoleLogDestination04filesT019clientAnalyticsInfoy10Foundation0G0VSg_A2OSiSgSdSgAA07ConsolesT0CSgAA04FilesT0CSgAA06ClientwX0VSgtKF) method. ## Deserialize Response Body All exposed custom API methods return a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) object or an error if request fails. The `BoxResponse` type has a `body` property of type `Data?`. If you want to deserialize its json content to specific custom type, you can use SDK's [`ObjectDeserializer.deserialize(data:)`](https://opensource.box.com/box-ios-sdk/Enums/ObjectDeserializer.html#/s:6BoxSDK18ObjectDeserializerO11deserialize4datas6ResultOyxAA0A8SDKErrorCG10Foundation4DataVSg_tAA0A5ModelRzlFZ) method to deserialize `Data?` to any type that conforms to `BoxModel`, or [`ObjectDeserializer.deserialize(response:)`](https://opensource.box.com/box-ios-sdk/Enums/ObjectDeserializer.html#/s:6BoxSDK18ObjectDeserializerO11deserialize8responses6ResultOyxAA0A8SDKErrorCGAA0A8ResponseV_tSeRzlFZ) to deserialize `BoxResponse` to any type that conforms to `Decodable`. ``` let fileId = "<YOUR_FILE_ID_HERE>" client.get(url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration)) { (result: Result<BoxResponse, BoxSDKError>) in let fileResult: Result<File, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body)} switch fileResult { case .success(let file): print("File \(file.name) was created at \(file.createdAt)") case .failure(let error): print("Error retrieving file information") } } ``` As you can see, we are using `flatMap` operator on `Result` type to deserialize origin `body` to the specific type, which is `File` in our case. The [`ObjectDeserializer.deserialize(data: Data?)`](https://opensource.box.com/box-ios-sdk/Enums/ObjectDeserializer.html#/s:6BoxSDK18ObjectDeserializerO11deserialize4datas6ResultOyxAA0A8SDKErrorCG10Foundation4DataVSg_tAA0A5ModelRzlFZ) method returns `Result<ReturnType, BoxSDKError>`, where `ReturnType` is inferenced as a `File`. ## API Calls ### Custom GET To perform a custom HTTP GET method, call [`client.get(url:httpHeaders:queryParameters:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC3get3url11httpHeaders15queryParameters10completiony10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the destination `url` and with headers or query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. If you want to deserialize it to a specific type, you can do so as in the example below: ``` let fileId = "<YOUR_FILE_ID_HERE>" // Get information about a file. client.get(url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration)) { (result: Result<BoxResponse, BoxSDKError>) in let fileResult: Result<File, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body)} switch fileResult { case .success(let file): print("File \(file.name) was created at \(file.createdAt)") case .failure(let error): print("Error retrieving file information") } } ``` As an alternative, to manually deserialize a response body, you can use [`ResponseHandler.default(wrapping completion:)`](https://opensource.box.com/box-ios-sdk/Enums/ResponseHandler.html#/s:6BoxSDK15ResponseHandlerO7default8wrappingys6ResultOyAA0aC0VAA0A8SDKErrorCGcyAGyxAKGc_tAA0A5ModelRzlFZ) method: ``` let fileId = "<YOUR_FILE_ID_HERE>" // Get information about a file. client.get( url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration), completion: ResponseHandler.default( wrapping: { (result: Result<File, BoxSDKError>) in switch result { case .success(let file): print("File \(file.name) was created at \(file.createdAt)") case .failure(let error): print("Error retrieving file information") } } ) ) ``` This method will make sure that the response is successful (status code 2xx) and will deserialize the response body into the appropriate type. In these examples above, we used existing SDKs type `File`, but this can be replaced with any custom type that conforms to either `Decodable` or `BoxModel`. ### Custom POST To perform a custom HTTP POST method, call [`client.post(url:httpHeaders:queryParameters:json:completion)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC4post3url11httpHeaders15queryParameters4json10completiony10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGypSgys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the `url`, `json` body and with headers or query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. If you want to deserialize it to a specific type, you can do so as shown in the examples below: ``` var body: [String: Any] = [:] body["parent"] = ["id": "<YOUR_FOLDER_ID_HERE>"] body["url"] = "https://example.com" body["name"] = "example name" // Creates a new web link with the specified url on the specified folder. client.post(url: URL.boxAPIEndpoint("/2.0/web_links", configuration: client.configuration), json: body) { result in let webLinkResult: Result<WebLink, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) } switch webLinkResult { case .success(let webLink): print("WebLink \(webLink.name) was created") case .failure(let error): print("Error creating a webLink \(error)") } } ``` or ``` var body: [String: Any] = [:] body["parent"] = ["id": "<YOUR_FOLDER_ID_HERE>"] body["url"] = "https://example.com" body["name"] = "example name" // Creates a new web link with the specified url on the specified folder. client.post( url: URL.boxAPIEndpoint("/2.0/web_links", configuration: client.configuration), json: body, completion: ResponseHandler.default( wrapping: { (result: Result<WebLink, BoxSDKError>) in switch result { case .success(let webLink): print("WebLink \(webLink.name) was created") case .failure(let error): print("Error creating a webLink \(error)") } } ) ) ``` In these examples we deserialized `body` as `WebLink` type, but you can deserialize response's body to any custom type that conforms to either `Decodable` or `BoxModel`. ### Custom PUT To perform a custom HTTP PUT method, call [`client.put(url:httpHeaders:queryParameters:json:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC3put3url11httpHeaders15queryParameters4json10completiony10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGypSgys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the `url`, `json` body and with headers or query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. If you want to deserialize it to a specific type, you can do so as shown in the examples below: ``` let taskId = "<YOUR_TASK_ID_HERE>" var body = [String: Any]() body["message"] = "Please to this ASAP!" body["action"] = "review" // Updates a specific task. client.put(url: URL.boxAPIEndpoint("/2.0/tasks/\(taskId)", configuration: client.configuration), json: body) { result in let taskResult: Result<Task, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) } switch taskResult { case .success(let task): print("Task \(task.id) was updated") case .failure(let error): print("Error updating a task \(error)") } } ``` or ``` let taskId = "<YOUR_TASK_ID_HERE>" var body = [String: Any]() body["message"] = "Please to this ASAP!" body["action"] = "review" // Updates a specific task. client.put( url: URL.boxAPIEndpoint("/2.0/tasks/\(taskId)", configuration: client.configuration), json: body, completion: ResponseHandler.default( wrapping: { (result: Result<Task, BoxSDKError>) in switch result { case .success(let task): print("Task \(task.id) was updated") case .failure(let error): print("Error updating a task \(error)") } } ) ) ``` In these examples we deserialized `body` as `Task` type, but we can deserialize it to any custom type that conforms to either `Decodable` or `BoxModel`. ### Custom DELETE To perform a custom HTTP DELETE method, call [`client.delete(url:httpHeaders:queryParameters:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC6delete3url11httpHeaders15queryParameters10completiony10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the `url` and with headers and query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. In most cases the `body` property on success will be just nil, so to handle this you can do as follows: ``` let fileId = "<YOUR_FILE_ID_HERE>" // Discards a file to the trash. client.delete(url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration)) { result in switch result { case .success: print("The file was deleted") case .failure(let error): print("Error deleting a file \(error)") } } ``` ### Custom OPTIONS To perform a custom HTTP OPTIONS method, call [`client.options(url:httpHeaders:queryParameters:json:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC7options3url11httpHeaders15queryParameters4json10completionAA0A11NetworkTaskC10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGypSgys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the `url`, `json` body and with headers or query parameters if needed. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. ``` var body: [String: Any] = ["parent": ["id": "<YOUR_FOLDER_ID_HERE>"]] body["name"] = "<YOUR_FILE_NAME_HERE>" // Verifies that new file will be accepted by Box before you send all the bytes over the wire. client.options(url: URL.boxAPIEndpoint("/2.0/files/content", configuration: client.configuration)) { result in switch result { case .success: print("The file is verified successfully") case .failure(let error): print("Error verifying a file \(error)") } } ``` This example will return an empty response when the checks pass or an error when the checks fail. In case of an empty response, the user can proceed with making an upload call. ### Download To perform a HTTP GET method call for downloading on the API, call [`client.download(url:downloadDestinationURL:httpHeaders:queryParameters:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC7options3url11httpHeaders15queryParameters4json10completionAA0A11NetworkTaskC10Foundation3URLV_SDyS2SGSDySSAA25QueryParameterConvertible_pSgGypSgys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF). You must specify `url` of the API endpoint to call `downloadDestinationURL`, which specifies the URL on a disk, where the data will be saved. The `completion` is a callback, which returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) object or an error if request fails. Headers and query parameters are optional, so add them if needed. ``` let fileId = "<YOUR_FILE_ID_HERE>" let destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("<FILE_NAME_HERE>") // Download a file to a specified folder. client.download( url: URL.boxAPIEndpoint("/2.0/files/\(fileId)/content", configuration: client.configuration), downloadDestinationURL: destinationURL ) { result in switch result { case .success: print("The file was downloaded") case .failure(let error): print("Error downloaded a file \(error)") } } ``` This example will return an empty response on success or an error on failure. ### Send To perform a send method, call [`client.send(request:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxClient.html#/s:6BoxSDK0A6ClientC4send7request10completionyAA0A7RequestC_ys6ResultOyAA0A8ResponseVAA0A8SDKErrorCGctF) with the [`request`](https://opensource.box.com/box-ios-sdk/Classes/BoxRequest.html#/s:6BoxSDK0A7RequestC10httpMethod3url0D7Headers11queryParams4body19downloadDestination4task8progressAcA10HTTPMethodO_10Foundation3URLVSDyS2SGSDySSAA25QueryParameterConvertible_pSgGAC8BodyTypeOAPSgySo16NSURLSessionTaskCcySo10NSProgressCctcfc) object, which represents the Box SDK API request. As you can see in the `completion` parameter, the `Callback` closure returns a [`BoxResponse`](https://opensource.box.com/box-ios-sdk/Structs/BoxResponse.html#/s:6BoxSDK0A8ResponseV7requestAA0A7RequestCvp) type. You can find the `body` of the response in `body` property, which is of type `Data?`. When creating a `BoxRequest` instance, please call [`init(httpMethod:url:httpHeaders:queryParams:body:downloadDestination:task:progress:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxRequest.html#/s:6BoxSDK0A7RequestC10httpMethod3url0D7Headers11queryParams4body19downloadDestination4task8progressAcA10HTTPMethodO_10Foundation3URLVSDyS2SGSDySSAA25QueryParameterConvertible_pSgGAC8BodyTypeOAPSgySo16NSURLSessionTaskCcySo10NSProgressCctcfc) with the parameters you need, leaving unused parameters with their default value. Below is an example of how we can use `send()` method to update a particular file: ``` let fileId = "<YOUR_FILE_ID_HERE>" var body: [String: Any] = [:] body["name"] = "new_file_name.txt" body["description"] = "new description" let request = BoxRequest( httpMethod: .put, url: URL.boxAPIEndpoint("/2.0/files/\(fileId)", configuration: client.configuration), queryParams: ["fields": "name,description"], body: .jsonObject(body) ) client.send(request: request) { result in let fileResult: Result<File, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) } switch fileResult { case let .success(fileItem): print("The file was updated successfully") case let .failure(error): print("Error updating a file \(error)") } } ``` This is an another example showing the use of the `send()` method to download a file: ``` let fileId = "<YOUR_FILE_ID_HERE>" let filename = "<YOUR_DESTINATION_FILE_NAME>" let destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(filename) let task = BoxDownloadTask() let request = BoxRequest( httpMethod: .get, url: URL.boxAPIEndpoint("/2.0/files/\(fileId)/content", configuration: client.configuration), downloadDestination: destinationURL, task: task.receiveTask, progress: { progress in let completed = String(format: "%.2f", progress.fractionCompleted * 100) print("Completed... \(completed)%") } ) client.send(request: request) { result in switch result { case .success: print("The file was downloaded") case let .failure(error): print("Error downloaded a file \(error)") } } // If you want to cancel downloading a file, please call `task.cancel()` method. ``` --- ## Untitled *Type: page* Device Pins Get Device Pin Info Get Device Pins for Enterprise Delete Device Pin Get Device Pin Info To retrieve information about a device… # Device Pins - [Get Device Pin Info](#get-device-pin-info) - [Get Device Pins for Enterprise](#get-device-pins-for-enterprise) - [Delete Device Pin](#delete-device-pin) ## Get Device Pin Info To retrieve information about a device pin, call [`client.devicepins.get(devicePinId: String, fields: [String]?, completion: @escaping Callback<DevicePin>)`](https://opensource.box.com/box-ios-sdk/Classes/DevicePinsModule.html#/s:6BoxSDK16DevicePinsModuleC3get11devicePinId6fields10completionySS_SaySSGSgys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the device pin. You can control which fields are returned on the resulting `Device Pin` object by passing the desired field names in the optional `fields` parameter. ``` client.devicePins.get(devicePinId: "11111", fields: ["product_name"]) { (result: Result<DevicePin, BoxSDKError>) in guard case let .success(devicePin) = result else { print("Error retrieving device pin information") return } print("Device Pin for \(devicePin.productName) was created at \(devicePin.createdAt)") } ``` ## Get Device Pins for Enterprise To retrieve information about the device pins active for the enterprise, call [`client.devicePins.listForEnterprise(enterpriseId: String, marker: String?, limit: Int?, direction: OrdeDirection?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/DevicePinsModule.html#/s:6BoxSDK16DevicePinsModuleC17listForEnterprise12enterpriseId6marker5limit9direction6fields10completionySS_SSSgSiSgAA14OrderDirectionOSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0C3PinCGAA0A8SDKErrorCGctF) with the ID of the enterpise. This method will return an iterator, which is used to retrieve device pins for the enterprise. ``` let iterator = client.devicePins.listForEnterprise(enterpriseId: "12345", direction: .ascending) iterator.next { results in switch results { case let .success(page): for devicePin in page.entries { print("Device type: \(devicePin.productName)") } case let .failure(error): print(error) } } ``` ## Delete Device Pin To delete a device pin, call [`client.devicePins.delete(devicePinId: String, completion: @escaping: Callback<Void>)`](https://opensource.box.com/box-ios-sdk/Classes/DevicePinsModule.html#/s:6BoxSDK16DevicePinsModuleC6delete11devicePinId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the device pin to delete. ``` client.devicePins.delete(devicePinId: "12345") { result: Result<Void, BoxSDKError> in guard case .success = result else { print("Error deleting device pin") return } print("Device Pin successfully deleted") } ``` --- ## Untitled *Type: page* Configuration The iOS SDK provides dedicated method, that helps you to customize SDK configuration. All you need is to call sdk… # Configuration The iOS SDK provides dedicated method, that helps you to customize SDK configuration. All you need is to call [`sdk.updateConfiguration(apiBaseURL:uploadApiBaseURL:oauth2AuthorizeURL:maxRetryAttempts:tokenRefreshThreshold:consoleLogDestination:fileLogDestination:clientAnalyticsInfo:)`](https://opensource.box.com/box-ios-sdk/Classes/BoxSDK.html#/s:6BoxSDKAAC19updateConfiguration10apiBaseURL09uploadApifG0015oauth2AuthorizeG016maxRetryAttempts21tokenRefreshThreshold21consoleLogDestination04filesT019clientAnalyticsInfoy10Foundation0G0VSg_A2OSiSgSdSgAA07ConsolesT0CSgAA04FilesT0CSgAA06ClientwX0VSgtKF) method on `BoxSDK` instance with correct parameters, right after creating a `BoxSDK` instance, but before creating a `BoxClient`. [URLs configuration](#urls-configuration) - [Api Base URL](#api-base-url) - [Upload Api Base URL](#upload-api-base-url) - [OAuth Authorize URL](#oauth-authorize-url) [Max retry attempts](#max-retry-attempts) [Token Refresh Threshold](#token-refresh-threshold) [Logging](#logging) - [Console Logging](#console-logging) - [File Logging](#file-logging) [Client Analytics Info](#client-analytics-info) ## URLs configuration The `sdk.updateConfiguration()` method allows you to change base URLs from defaults to the ones you will specify. Just call this method on the `BoxSDK` instance with any of these parameters: ``` do { try sdk.updateConfiguration( apiBaseURL: URL(string: "https://my-company.com"), uploadApiBaseURL: URL(string: "https://my-company.com/upload"), oauth2AuthorizeURL: URL(string: "https://my-company.com/oauth2") ) } catch { print("An error occurred \(error)") } ``` The `updateConfiguration()` will throw an exception if any of passed URLs will be invalid. ### Api Base URL The `apiBaseURL` sets URL to which all API calls will be directed. Final URL that is used to access Box is built using `apiBaseURL` and the API Version (`2.0`). For example, by default the `apiBaseURL` is set to `https://api.box.com`, so after appending the currently supported API version the URL is : `https://api.box.com/2.0`. ### Upload Api Base URL The `uploadApiBaseURL` is used to configure the base URL used when uploading files. Final URL used to access Box is built using `uploadApiBaseURL`, the `/api/` path and API Version (`2.0`). For example, by default the `uploadApiBaseURL` is set to `https://upload.box.com`, so after appending `/api/` path and the currently supported API version the URL is : `https://upload.box.com/api/2.0`. ### OAuth Authorize URL The `oauth2AuthorizeURL` is an URL for the OAuth2 authorization page, where users are redirected to enter their credentials to obtain OAuth2 authorization tokens. By default is set to `https://account.box.com/api/oauth2/authorize`. ## Max retry attempts The default maximum number of retries in case of failed API call is `5`. To change this please call `sdk.updateConfiguration()` method with `maxRetryAttempts` parameter and your new value e.g. `10`: ``` do { try sdk.updateConfiguration( maxRetryAttempts: 10 ) } catch { print("An error occurred \(error)") } ``` ## Token Refresh Threshold You can specify how many seconds before the token expires, it should be refreshed. By default it is set to `60` seconds. To change this value, please call `sdk.updateConfiguration()` method with `tokenRefreshThreshold` parameter and your new value, e.g. `120`: ``` do { try sdk.updateConfiguration( tokenRefreshThreshold: 120 ) } catch { print("An error occurred \(error)") } ``` ## Logging ### Console Logging There could be a situation when the default console Box SDK logging is not sufficient for your needs. You can then create your own class that inherits form [`ConsoleLogDestination`](https://opensource.box.com/box-ios-sdk/Classes/ConsoleLogDestination.html) class and you can overwrite `write` method for you needs (as this is a method that writes logs into the console). If you named this class e.g. `CustomConsoleLogDestination` then call: ``` do { try sdk.updateConfiguration( consoleLogDestination: CustomConsoleLogDestination() ) } catch { print("An error occurred \(error)") } ``` ### File Logging By default, logging to a file is disabled in the Box SDK. To turn it on, you just need to pass the `fileLogDestination` parameter to the new instance of [`FileLogDestination`](https://opensource.box.com/box-ios-sdk/Classes/FileLogDestination.html). To create a new instance of `FileLogDestination`, you need to pass the `fileURL` parameter, which is the file path URL to write the logs to. ``` let fileLoggerURL = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask).first!.appendingPathComponent("box_sdk_log.txt") do { try sdk.updateConfiguration( fileLogDestination: FileLogDestination(fileURL: fileLoggerURL) ) } catch { print("An error occurred \(error)") } ``` ## Client Analytics Info If for some reasons you want to track your application usage on server, there is a way for that. You just need to create an instance of [`ClientAnalyticsInfo`](https://opensource.box.com/box-ios-sdk/Structs/ClientAnalyticsInfo.html) struct with `appName` and `appVersion` parameters related to your app and pass it to `sdk.updateConfiguration()` method. Those values will be added to `X-Box-UA` request header after `agent` and `env` values. Take a look at the following code: ``` let analyticsInfo = ClientAnalyticsInfo(appName: "MyCustomApp", appVersion: "1.2.0") do { try sdk.updateConfiguration(clientAnalyticsInfo: analyticsInfo) } catch { print("An error occurred \(error)") } ``` After this change, the `client=MyCustomApp/1.2.0` will be appended to the `X-Box-UA` request header value. If you run this code on `iPhone 11 Pro Max` and using SDK version `5.2.0` the final value for `X-Box-UA` header will be `agent=box-swift-sdk/5.2.0; env=iPhone Simulator/15.2; client=MyCustomApp/1.2.0`. --- ## Untitled *Type: page* Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other… # Files File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other common file operations (move, copy, delete, etc.). - [Get File Info](#get-file-info) - [Update File](#update-file) - [Upload File](#upload-file) - [Upload New File Version](#upload-new-file-version) - [Download File](#download-file) - [Copy File](#copy-file) - [Lock File](#lock-file) - [Unlock File](#unlock-file) - [Get File Thumbnail Image](#get-file-thumbnail-image) - [Get File Embed Link](#get-file-embed-link) - [Get File Collaborations](#get-file-collaborations) - [Get File Comments](#get-file-comments) - [Get File Tasks](#get-file-tasks) - [Add File to Favorites](#add-file-to-favorites) - [Remove File from Favorites](#remove-file-from-favorites) - [Get Shared Link](#get-shared-link) - [Set Shared Link](#set-shared-link) - [Remove Shared Link](#remove-shared-link) - [List Representations](#list-representations) - [Download Zip](#download-zip) ## Get File Info To retrieve information about a file, call [`client.files.get(fileId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC3get6fileId6fields10completionySS_SaySSGSgys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. You can control which fields are returned on the resulting `File` object by passing the desired field names in the optional `fields` parameter. ``` client.files.get(fileId: "11111", fields: ["name", "created_at"]) { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error retrieving file information") return } print("File \(file.name) was created at \(file.createdAt)") } ``` ## Update File To update a file record, call [`client.files.updateFileInfo(fileId:name:description:parentId:sharedLink:tags:collections:lock:dispositionAt:ifMatch:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC6update6fileId4name11description06parentG010sharedLink4tags11collections4lock13dispositionAt7ifMatch6fields10completionySS_SSSgA2qA17NullableParameterOyAA06SharedL4DataVGSgSaySSGSgAySyAA04LockY0VGSg10Foundation4DateVSgAqYys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file to update and the properties to update. ``` client.files.update(fileId: "11111", name: "New file name.docx") { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error updating file information") return } print("File \(file.name) was updated at \(file.modifiedAt)") } ``` ## Upload File To upload a file from data in memory, call [`client.files.upload(data:name:parentId:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC6upload4data4name8parentId8progress21performPreflightCheck10completiony10Foundation4DataV_S2SySo10NSProgressCcSbys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the data to be uploaded, the name of the file, and the ID of the folder into which the file should be uploaded. Use ID `"0"` to upload a file into the root folder, "All Files". ``` let data = "test content".data(using: .utf8) let task: BoxUploadTask = client.files.upload(data: data, name: "Test File.txt", parentId: "0") { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error uploading file") return } print("File \(file.name) was uploaded at \(file.createdAt) into \"\(file.parent.name)\"") } // To cancel upload if someConditionIsSatisfied { task.cancel() } ``` To upload a file from a stream, use [`client.files.streamUpload(stream:fileSize:name:parentId:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC12streamUpload0E08fileSize4name8parentId8progress21performPreflightCheck10completionySo13NSInputStreamC_SiS2SySo10NSProgressCcSbys6ResultOyAA4FileCAA0A8SDKErrorCGctF). ``` let data = "test content".data(using: .utf8) let stream = InputStream(data: data) let task: BoxUploadTask = client.files.streamUpload( stream: stream, fileSize: 12, name: "Test File.txt", parentId: "0" ) { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error uploading file") return } print("File \(file.name) was uploaded at \(file.createdAt) into \"\(file.parent.name)\"") } // To cancel upload if someConditionIsSatisfied { task.cancel() } ``` ## Upload New File Version To upload a new version of an existing file, call [`client.files.uploadVersion(forFile:name:contentModifiedAt:data:ifMatch:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC13uploadVersion7forFile4name17contentModifiedAt4data8progress21performPreflightCheck10completionySS_SSSgAL10Foundation4DataVySo10NSProgressCcSbys6ResultOyAA0H0CAA0A8SDKErrorCGctF) with the ID of the file and the file contents to be uploaded. ``` let data = "updated file content".data(using: .utf8) let task: BoxUploadTask = client.files.uploadVersion( forFile: "11111", name: "New file name.txt", contentModifiedAt: "2019-08-07T09:19:13-07:00", data: data ) { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error uploading file version") return } print("New version of \(file.name) was uploaded") } // To cancel upload if someConditionIsSatisfied { task.cancel() } ``` To upload a new version of an existing file from a stream, use [`client.files.streamUploadVersion(stream:fileSize:forFile:name:contentModifiedAt:ifMatch:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC13uploadVersion7forFile4name17contentModifiedAt4data8progress21performPreflightCheck10completionySS_SSSgAL10Foundation4DataVySo10NSProgressCcSbys6ResultOyAA0H0CAA0A8SDKErrorCGctF). ``` let data = "updated file content".data(using: .utf8) let stream = InputStream(data: data) let task: BoxUploadTask = client.files.streamUploadVersion( stream: stream, fileSize: 12, forFile: "11111", name: "New file name.txt", contentModifiedAt: "2021-03-07T09:19:13-07:00" ) { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error uploading file version") return } print("New version of \(file.name) was uploaded") } // To cancel upload if someConditionIsSatisfied { task.cancel() } ``` ## Download File To download a file to the device, call [`client.files.download(fileId:version:destinationURL:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC8download6fileId14destinationURL7version8progress10completionySS_10Foundation0I0VSSSgySo10NSProgressCcys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file to download and a URL to the location where the file should be downloaded to. ``` let url = FileManager.default.homeDirectoryForCurrentUser let task: BoxDownloadTask = client.files.download(fileId: "11111", destinationURL: url) { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error downloading file") return } print("File downloaded successfully") } // To cancel download if someConditionIsSatisfied { task.cancel() } ``` ## Copy File To make a copy of a file, call [`client.files.copy(fileId:parentId:name:version:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC4copy6fileId06parentG04name7version6fields10completionySS_S2SSgAKSaySSGSgys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file to copy and the ID of the folder into which the copy should be placed. In case an item with the same name already exists in the destination folder, the `name` parameter can be used to provide a new name for the copied file. You can copy a specific file version by passing the version ID in the `version` parameter. ``` client.files.copy(fileId: "11111", parentId: "0") { (result: Result<File, BoxSDKError>) in guard case let .success(copiedFile) = result else { print("Error copying file") return } print("Copied file \(copiedFile.name) into folder \(copiedFile.parent.name); copy has file ID \(copiedFile.id)") } ``` ## Lock File To lock a file and prevent others from modifying it, call [`client.files.lock(fileId:expiresAt:isDownloadPrevented:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC4lock6fileId9expiresAt19isDownloadPrevented6fields10completionySS_10Foundation4DateVSgSbSgSaySSGSgys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. To also prevent others from downloading the file while it is locked, set the `isDownloadPrevented` parameter to `true`. ``` client.files.lock(fileId: "11111") { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error locking file") return } print("File \(file.name) locked") } ``` ## Unlock File To unlock a file, call [`client.files.unlock(fileId:fields:completion:)](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC6unlock6fileId6fields10completionySS_SaySSGSgys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.unlock(fileId: "11111") { (result: Result<File, BoxSDKError>) in guard case let .success(file) = result else { print("Error unlocking file") return } print("File \(file.name) unlocked") } ``` ## Get File Thumbnail Image To retrieve the thumbnail image for a file, call [`client.files.getThumbnail(forFile:extension:minHeight:minWidth:maxHeight:maxWidth:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC12getThumbnail7forFile9extension9minHeight0J5Width03maxK00mL010completionySS_AA0F9ExtensionOSiSgA3Nys6ResultOy10Foundation4DataVAA0A8SDKErrorCGctF) with the ID of the file and the desired image format extension. Optionally, constraints on the image dimensions can be specified in the `minHeight`, `minWidth`, `maxHeight`, and `maxWidth` parameters. ``` client.files.getThumbnail(forFile: "11111", extension: .png) { (result: Result<Data, BoxSDKError>) in guard case let .success(thumbnailData) = result else { print("Error getting file thumbnail") return } let thumbnailImage = UIImage(data: thumbnailData) } ``` ## Get File Embed Link To retrieve a URL that can be embedded in a web page `<iframe>` to display a file preview, call [`client.files.getEmbedLink(forFile:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC12getEmbedLink7forFile10completionySS_ys6ResultOyAA08ExpiringfG0CAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.getEmbedLink(forFile: "11111") { (result: Result<ExpiringEmbedLink, BoxSDKError>) in guard case let .success(embedLink) = result else { print("Error generating file embed link") return } print("File embed URL is \(embedLink.url)") } ``` ## Get File Collaborations To retrieve a list of collaborations on a file, call [`client.files.listCollaborations(forFile:marker:limit:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC18listCollaborations7forFile6marker5limit6fields10completionySS_SSSgSiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA13CollaborationCGAA0A8SDKErrorCGctF) with the ID of the file. This method returns an iterator, which is used to retrieve file collaborations. ``` let iterator = client.files.listCollaborations(forFile: "11111") iterator.next { result in switch results { case let .success(page): for collaboration in page.entries { print("Collaboration created by \(collaboration.createdBy?.name)") } case let .failure(error): print(error) } } ``` ## Get File Comments To retrieve a list of comments on the file, call [`client.files.listComments(forFile:offset:limit:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC12listComments7forFile6offset5limit6fields10completionySS_SiSgAJSaySSGSgys6ResultOyAA14PagingIteratorCyAA7CommentCGAA0A8SDKErrorCGctF) with the ID of the file. This method returns an iterator, which is used to page through the collection of file comments. ``` let iterator = client.files.listComments(forFile: "11111") iterator.next { results in switch results { case let .success(page): for comment in page.entries { print(comment.message) } case let .failure(error): print(error) } } ``` ## Get File Tasks To retrieve a list of file tasks, call [`client.files.listTasks(forFile:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC9listTasks7forFile6fields10completionySS_SaySSGSgys6ResultOyAA14PagingIteratorCyAA4TaskCGAA0A8SDKErrorCGctF) with the ID of the file. This method returns an iterator, which is used to retrieve file comments. ``` let iterator = client.files.listTasks(forFile: "11111") iterator.next { results in switch results { case let .success(page): for task in page.entries { print("Task messsage: \(task.message)") } case let .failure(error): print(error) } } ``` ## Add File to Favorites To add a file to the user's favorites collection, call [`client.files.addToFavorites(fileId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC14addToFavorites6fileId10completionySS_ys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.addToFavorites(fileId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error adding file to favorites") return } print("File added to favorites") } ``` ## Remove File from Favorites To remove a file from the user's favorites collection, call [`client.files.removeFromFavorites(fileId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC19removeFromFavorites6fileId10completionySS_ys6ResultOyAA4FileCAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.removeFromFavorites(fileId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing file from favorites") return } print("File removed from favorites") } ``` ## Get Shared Link To retrieve the shared link associated with a file, call [`client.files.getSharedLink(forFile:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC13getSharedLink7forFile10completionySS_ys6ResultOyAA0fG0CAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.getSharedLink(forFile: "11111") { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error retrieving file shared link") return } print("File shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` ## Set Shared Link To add or update the shared link for a file, call [`client.files.setSharedLink(forFile:unsharedAt:vanityName:access:password:canDownload:canEdit:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC13setSharedLink7forFile10unsharedAt10vanityName6access8password11canDownload0P4Edit10completionySS_AA17NullableParameterOy10Foundation4DateVGSgANySSGSgAA0fG6AccessOSgAUSbSgAYys6ResultOyAA0fG0CAA0A8SDKErrorCGctF) with the ID of the file and the shared link properties to set. ``` client.files.setSharedLink( forFile: "11111", access: .open, canDownload: true, canEdit: true ) { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error setting file shared link") return } print("File shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` ## Remove Shared Link To remove a file's shared link, call [`client.files.deleteSharedLink(forFile:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC16deleteSharedLink7forFile10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file. ``` client.files.deleteSharedLink(fileId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing file shared link") return } print("File shared link removed") } ``` ## List Representations To retrieve information about available preview representations for a file, call [`client.files.listRepresentations(fileId:representationHint:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC19listRepresentations6fileId18representationHint10completionySS_AA018FileRepresentationJ0OSgys6ResultOySayAA0lM0VGAA0A8SDKErrorCGctF) with the ID of the file. Omitting the `representationHint` parameter will provide summary information about all available representations; in order to retrieve the representation status and URL, the `representationHint` parameter must be passed to select the desired representation. ``` // Get full information about PDF representation client.files.listRepresentations( fileId: "11111", representationHint: "[pdf]" ) { (result: Result<[FileRepresentation], BoxSDKError>) in guard case let .success(representations) = result else { print("Error fetching representations") return } print("PDF representation generation status: \(representations[0]?.status?.state)") } ``` ## Download Zip Calling [`client.files.downloadZip(name:items:destinationURL:completion:)`][download-zip] will let you create a new zip file with the specified name and with the specified items and download it to the specified URL location where the file should be downloaded to. The created zip file does not show up in your Box account. ``` let name = "New zip name" var items: [ZipDownloadItem] = [] items.append(ZipDownloadItem( type: "file", id: "11111" )) let items: [ZipDownloadItem] = [] items.append(ZipDownloadItem( type: "folder", id: "22222" )) let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let destinationURL = documentsURL.appendingPathComponent("New zip name.zip") client.files.downloadZip(name: name, items: items, destinationURL: destinationURL) { (result: Result<ZipDownloadStatus, BoxSDKError>) in guard case .success = result else { guard case let .success(zipDownloadStatus) = result else { print("Error downloading zip") return } print("Zip download status: \(zipDownloadStatus.state)") } ``` --- ## Untitled *Type: page* File Requests File request objects represent a file request associated with a folder. Get a File Request's Information Copy a File Request's… # File Requests File request objects represent a file request associated with a folder. - [Get a File Request's Information](#get-a-file-requests-information) - [Copy a File Request's Information](#copy-a-file-requests-information) - [Update a File Request's Information](#update-a-file-requests-information) - [Delete a File Request](#delete-a-file-request) ## Get a File Request's Information To retrieve information about a file request, call [`client.fileRequests.get(fileRequestId::completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FileRequestsModule.html#/s:6BoxSDK18FileRequestsModuleC3get13fileRequestId10completionySS_ys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the file request. ``` client.fileRequests.get(fileRequestId: "123456") { result in guard case let .success(fileRequest) = result else { print("Error getting file request") return } print("File request title: \(fileRequest.title ?? "n/a"), description: \(fileRequest.description ?? "n/a")") } ``` ## Copy a File Request's Information To copy an existing file request that is already present on one folder, and applies it to another folder, call [`client.fileRequests.copy(fileRequestId:copyRequest:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FileRequestsModule.html#/s:6BoxSDK18FileRequestsModuleC4copy13fileRequestId0fH010completionySS_AA0ch4CopyH0Vys6ResultOyAA0cH0CAA0A8SDKErrorCGctF). You must provide the ID of file request you want to copy, and an instance of the [`FileRequestCopyRequest`](https://opensource.box.com/box-ios-sdk/Structs/FileRequestCopyRequest.html#/s:6BoxSDK015FileRequestCopyD0V5titleSSSgvp) class, where you can set fields to replace fields from source file request. ``` let destinationFolder = FolderEntity(id: "33333") let copyRequest = FileRequestCopyRequest( title: "New file request title", description: "New file request description", isEmailRequired: true, isDescriptionRequired: false, folder: destinationFolder ) client.fileRequests.copy(fileRequestId: "123456", copyRequest: copyRequest) { result in guard case let .success(fileRequest) = result else { print("Error copying file request") return } print("Copied file request title: \(fileRequest.title ?? "n/a"), description: \(fileRequest.description ?? "n/a")") } ``` ## Update a File Request's Information To update a file request, call [`client.fileRequests.update(fileRequestId:ifMatch:updateRequest:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FileRequestsModule.html#/s:6BoxSDK18FileRequestsModuleC6update13fileRequestId7ifMatch0fH010completionySS_SSSgAA0ch6UpdateH0Vys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the file request and with an instance of the [`FileRequestUpdateRequest`](https://opensource.box.com/box-ios-sdk/Structs/FileRequestUpdateRequest.html) class, where you can set fields you want to update. If you want to make sure that an item hasn't changed recently before making changes, you can pass the last observed `etag` value to the `ifMatch` parameter. This call can be used to activate or deactivate a file request. ``` let updateRequest = FileRequestUpdateRequest( title: "Updated file request title", description: "Updated file request description", status: .inactive, isEmailRequired: false, isDescriptionRequired: true ) client.fileRequests.update(fileRequestId: "123456", updateRequest: updateRequest) { result in guard case let .success(fileRequest) = result else { print("Error updating file request") return } print("Updated file request title: \(fileRequest.title ?? "n/a"), description: \(fileRequest.description ?? "n/a")") } ``` ## Delete a File Request To delete a file request permanently, call [`client.fileRequests.delete(fileRequestId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FileRequestsModule.html#/s:6BoxSDK18FileRequestsModuleC6delete13fileRequestId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file request to delete. ``` client.fileRequests.delete(fileRequestId: "123456") { result in guard case .success = result else { print("Error removing file request") return } print("File request removed") } ``` --- ## Untitled *Type: page* Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a… # Folders Folder objects represent a folder from a user's account. They can be used to iterate through a folder's contents, collaborate a folder with another user or group, and perform other common folder operations (move, copy, delete, etc.). [Folders](#folders) - [Get Folder Info](#get-folder-info) - [Get Folder Items](#get-folder-items) - [Create Folder](#create-folder) - [Delete Folder](#delete-folder) - [Copy Folder](#copy-folder) - [Get Folder Collaborations](#get-folder-collaborations) - [Add Folder to Favorites](#add-folder-to-favorites) - [Remove Folder from Favorites](#remove-folder-from-favorites) - [Get Shared Link](#get-shared-link) - [Set Shared Link](#set-shared-link) - [Remove Shared Link](#remove-shared-link) - [Get Folder Locks](#get-folder-locks) - [Create Folder Lock](#create-folder-lock) - [Delete Folder Lock](#delete-folder-lock) ## Get Folder Info To retrieve information about a folder, call [`client.folders.get(folderId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC3get8folderId6fields10completionySS_SaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with the ID of the folder. You can control which fields are returned in the resulting `Folder` object by passing the `fields` parameter. ``` client.folders.get( folderId: "22222", fields: ["name", "created_at"] ) { (result: Result<Folder, BoxSDKError>) in guard case let .success(folder) = result else { print("Error getting folder information") return } print("Folder \(folder.name) was created at \(folder.createdAt)") } ``` As an alternative, you can call `async` method [`client.folders.get(folderId:fields)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC3get8folderId6fieldsAA6FolderCSS_SaySSGSgtYaKF) ``` do { let folder = try await client.folders.get( folderId: "111111", fields: ["name", "created_at"] ) print("Folder \(folder.name) was created at \(folder.createdAt)") } catch { print("Error getting folder information") } ``` ## Get Folder Items To retrieve information about the items contained in a folder, call [`client.folders.listItems(folderId:usemarker:marker:offset:limit:sort:direction:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC9listItems8folderId9usemarker6marker6offset5limit4sort9direction6fields10completionySS_SbSgSSSgSiSgApA06FolderF7OrderByOSgAA0R9DirectionOSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0Q4ItemOGAA0A8SDKErrorCGctF) with the ID of the folder. This method will return an iterator, which is used to retrieve folder items. ``` let iterator = client.folders.listItems(folderId: "22222", sort: .name, direction: .ascending) iterator.next { results in switch results { case let .success(page): for item in page.entries { switch item { case let .file(file): print("File \(file.name) (ID: \(file.id)) is in the folder") case let .folder(folder): print("Subfolder \(folder.name) (ID: \(folder.id)) is in the folder") case let .webLink(webLink): print("Web link \(webLink.name) (ID: \(webLink.id)) is in the folder") } } case let .failure(error): print(error) } } ``` As an alternative, you can retrieve folder items by iterator in `async` way. For instance, to fetch all folder items, call: ``` let iterator = client.folders.listItems(folderId: "22222", sort: .name, direction: .ascending) var allItems: [FolderItem] = [] do { repeat { let items = try await iterator.next() allItems.append(contentsOf: items.entries) } while true } catch let error as BoxSDKError where error.message == .endOfList { print("The end of the list has been reached") } catch { print("An error occurred: \(error)") } ``` ## Create Folder To create a new folder, call [`client.folders.create(name:parentId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC6create4name8parentId6fields10completionySS_SSSaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with a name for the new folder and the ID of the folder to create the new folder in. To create a new folder inside the root folder ("All Files"), use ID `"0"`. ``` client.folders.create(name: "New Folder", parentId: "22222") { (result: Result<Folder, BoxSDKError>) in guard case let .success(folder) = result else { print("Error creating folder") return } print("Created folder \"\(folder.name)\" inside of folder \"\(folder.parent?.name)\"") } ``` As an alternative, you can call `async` method [`client.folders.create(name:parentId:fields)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC6create4name8parentId6fieldsAA6FolderCSS_SSSaySSGSgtYaKF). ``` do { let folder = try await client.folders.create(name: "New Folder", parentId: "22222") print("Created folder \"\(folder.name)\" inside of folder \"\(folder.parent?.name)\"") } catch { print("Error getting folder information") } ``` ## Delete Folder To delete a folder, call [`client.folders.delete(folderId:recursive:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC6delete8folderId9recursive10completionySS_SbSgys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the folder to delete. By default, the folder will only be deleted if it is empty and has no items in it; if you wish to delete all the items in the folder as well, pass `recursive: true`. ``` client.folders.delete(folderId: "22222", recursive: true) { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting folder") return } print("Folder and contents successfully deleted") } ``` As an alternative, you can call `async` method [`client.folders.delete(folderId:recursive)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC6delete8folderId9recursiveySS_SbSgtYaKF) ``` do { let folder = try await client.folders.delete(folderId: "22222", recursive: true) print("Folder and contents successfully deleted") } catch { print("Error deleting folder") } ``` ## Copy Folder To copy a folder from one parent folder to another, call [`client.folders.copy(folderId:destinationFolderID:name:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC4copy8folderId19destinationFolderID4name6fields10completionySS_S2SSgSaySSGSgys6ResultOyAA0I0CAA0A8SDKErrorCGctF) with the ID of the folder to copy and the ID of the destination parent folder. To avoid a name conflict in the new parent folder, pass an alternate name for the folder in the `name` parameter; the folder will be renamed to the alternate name in case of a conflict. ``` client.folders.copy( folderId: "22222", destinationFolderID: "12345" ) { (result: Result<Folder, BoxSDKError>) in guard case let .success(folderCopy) = result else { print("Error copying folder") return } print("Copied folder \(folderCopy.name) to destination \(folderCopy.parent?.name)") } ``` As an alternative, you can call `async` method [`client.folders.copy(folderId:destinationFolderId:name:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC4copy8folderId017destinationFolderG04name6fieldsAA0I0CSS_S2SSgSaySSGSgtYaKF) ``` do { let folderCopy = try await client.folders.copy(folderId: "22222", destinationFolderId: "12345") print("Copied folder \(folderCopy.name) to destination \(folderCopy.parent?.name)") } catch { print("Error copying folder") } ``` ## Get Folder Collaborations To retrieve a list of the collaborations on a folder, call [`client.folders.listCollaborations(folderId:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC18listCollaborations8folderId6fields10completionySS_SaySSGSgys6ResultOyAA14PagingIteratorCyAA13CollaborationCGAA0A8SDKErrorCGctF) with the ID of the folder. ``` let iterator = client.folders.listCollaborations(folderId: "22222") iterator.next { results in switch results { case let .success(page): for collaboration in page.entries { if let collaborator = collaboration.accessibleBy { switch collaborator.collaboratorValue { case .user(let user): print("- user: \(user.name ?? "")") case .group(let group): print("- group: \(group.name ?? "")") } } } case let .failure(error): print(error) } } ``` As an alternative, you can retrieve collaborations items by iterator in `async` way. ``` let iterator = client.folders.listCollaborations(folderId: "163571796480") do { let page = try await iterator.next() for collaboration in page.entries { if let collaborator = collaboration.accessibleBy { switch collaborator.collaboratorValue { case .user(let user): print("- user: \(user.name ?? "")") case .group(let group): print("- group: \(group.name ?? "")") } } } } catch { print("An error occurred: \(error)") } ``` ## Add Folder to Favorites To add a folder to the user's favorites, call [`client.folders.addToFavorites(folderId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC14addToFavorites8folderId6fields10completionySS_SaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.folders.addToFavorites(folderId: "22222") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error adding folder to favorites") return } print("Added folder to favorites") } ``` As an alternative, you can call `async` method [`client.folders.addToFavorites(folderId:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC14addToFavorites8folderId6fieldsAA6FolderCSS_SaySSGtYaKF). ``` do { try await client.folders.addToFavorites(folderId: "22222") print("Added folder to favorites") } catch { print("Error adding folder to favorites") } ``` ## Remove Folder from Favorites To remove a folder from the user's favorites, call [`client.folders.removeFromFavorites(folderId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC19removeFromFavorites8folderId6fields10completionySS_SaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.folders.removeFromFavorites(folderId: "22222") { result in guard case .success = result else { print("Error removing folder from favorites") return } print("Removed folder to favorites") } ``` As an alternative, you can call `async` method [`client.folders.removeFromFavorites(folderId:fields:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC19removeFromFavorites8folderId6fieldsAA6FolderCSS_SaySSGSgtYaKF). ``` do { try await client.folders.removeFromFavorites(folderId: "22222") print("Removed folder to favorites") } catch { print("Error removing folder from favorites") } ``` ## Get Shared Link To retrieve the shared link associated with a folder, call [`client.folders.getSharedLink(forFolder:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC13getSharedLink9forFolder10completionySS_ys6ResultOyAA0fG0CAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.folders.getSharedLink(forFolder: "11111") { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error retrieving folder shared link") return } print("Folder shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` As an alternative, you can call `async` method [`client.folders.getSharedLink(forFolder:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC13getSharedLink9forFolder10completionySS_ys6ResultOyAA0fG0CAA0A8SDKErrorCGctF). ``` do { let sharedLink = try await client.folders.getSharedLink(forFolder: "11111") print("Folder shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } catch { print("Error retrieving folder shared link") } ``` ## Set Shared Link To add or update the shared link for a folder, call [`client.folders.setSharedLink(forFolder:access:unsharedAt:vanityName:password:canDownload:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC13setSharedLink9forFolder6access10unsharedAt10vanityName8password11canDownload10completionySS_AA0fG6AccessOSgAA17NullableParameterOy10Foundation4DateVGSgAPySSGSgAWSbSgys6ResultOyAA0fG0CAA0A8SDKErrorCGctF) with the ID of the folder and the shared link properties to set. ``` client.folders.setSharedLink(forFolder: "11111", access: .open) { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error setting folder shared link") return } print("Folder shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` As an alternative, you can call `async` method [`client.folders.setSharedLink(forFolder:access:unsharedAt:vanityName:password:canDownload:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC13setSharedLink9forFolder6access10unsharedAt10vanityName8password11canDownloadAA0fG0CSS_AA0fG6AccessOSgAA17NullableParameterOy10Foundation4DateVGSgAQySSGSgAXSbSgtYaKF). ``` do { let sharedLink = try await client.folders.setSharedLink(forFolder: "163571796480", access: .open) print("Folder shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } catch { print("Error setting folder shared link") } ``` ## Remove Shared Link To remove a file's shared link, call [`client.folders.deleteSharedLink(forFolder:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC16deleteSharedLink9forFolder10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.folders.deleteSharedLink(forFolder: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing folder shared link") return } print("Folder shared link removed") } ``` As an alternative, you can call `async` method [`client.folders.deleteSharedLink(forFolder:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC16deleteSharedLink9forFolderySS_tYaKF). ``` do { try await client.folders.deleteSharedLink(forFolder: "11111") print("Folder shared link removed") } catch { print("Error removing folder shared link") } ``` ## Get Folder Locks To retrieve a list of the locks on a folder, call [`client.folders.listLocks(folderId:completion:)`][get-folder-locks] with the ID of the folder. Folder locks define access restrictions placed by folder owners to prevent specific folders from being moved or deleted. ``` client.folders.listLocks(folderId: "22222") { results in switch results { case let .success(iterator): for i in 1 ... 10 { iterator.next { result in switch result { case let .success(folderLock): print("- \(folderLock.id)") case let .failure(error): print(error) } } } case let .failure(error): print(error) } } ``` As an alternative, you can retrieve all folder locks by iterator in `async` way. ``` let iterator = client.folders.listLocks(folderId: "22222") do { repeat { let page = try await iterator.next() for folderLock in page.entries { print("- \(folderLock.id)") } } while true } catch let error as BoxSDKError where error.message == .endOfList { print("The are no more items to fetch") } catch { print("An error occurred: \(error)") } ``` ## Create Folder Lock To lock a folder, call [`client.folders.createLock(folderId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC10createLock8folderId10completionySS_ys6ResultOyAA06FolderF0CAA0A8SDKErrorCGctF) with the ID of the folder. This prevents the folder from being moved and/or deleted. ``` client.folders.createLock(folderId: "22222") { (result: Result<FolderLock, BoxSDKError>) in guard case let .success(folderLock) = result else { print("Error creating folder lock") return } print("Created folder lock with id \"\(folderLock.id)\" inside of folder with id \"\(folderLock.folder?.id)\"") } ``` As an alternative, you can call `async` method [`client.folders.createLock(folderId: "22222")`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC10createLock8folderIdAA06FolderF0CSS_tYaKF). ``` do { let folderLock = try await client.folders.createLock(folderId: "163571796480") print("Created folder lock with id \"\(folderLock.id)\" inside of folder with id \"\(folderLock.folder?.id)\"") } catch { print("Error creating folder lock") } ``` ## Delete Folder Lock To remove a folder lock, call [`client.folders.deleteLock(folderLockId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC10deleteLock06folderF2Id10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the folder lock. ``` client.folders.deleteLock(folderLockId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing folder lock") return } print("Folder lock removed") } ``` As an alternative, you can call `async` method [`client.folders.deleteLock(folderId: "22222")`](https://opensource.box.com/box-ios-sdk/Classes/FoldersModule.html#/s:6BoxSDK13FoldersModuleC10deleteLock06folderF2IdySS_tYaKF). ``` do { try await client.folders.deleteSharedLink(forFolder: "11111") print("Folder shared link removed") } catch { print("Error removing folder shared link") } ``` --- ## Untitled *Type: page* Groups Groups contain a set of users and can be used in place of users in some operations such as collaborations. Create Group Update Group… # Groups Groups contain a set of users and can be used in place of users in some operations such as collaborations. - [Create Group](#create-group) - [Update Group](#update-group) - [Get Group Info](#get-group-info) - [Get Enterprise Groups](#get-enterprise-groups) - [Delete Group](#delete-group) [Group Membership](#group-membership) - [Get Group Membership Info](#get-group-membership-info) - [Create Group Membership](#create-group-membership) - [Update Group Membership](#update-group-membership) - [Delete Group Membership](#delete-group-membership) - [Get Memberships for Group](#get-memberships-for-group) - [Get Memberships for User](#get-memberships-for-user) - [Get Collaborations for Group](#get-collaborations-for-group) ## Create Group To create a new group, call [`client.groups.create(name: String, provenance: String?, externalSyncIdentifier: String?, description: String?, invitabilityLevel: GroupInvitabilityLevel?, memberViewabilityLevel: GroupMemberViewabilityLevel, fields: [String]?, completion: @escaping Callback<Group>)`][create_group] with the name of the group you wish to create. You can control which fields are returned in the resulting `Group` object by passing the `fields` parameter. ``` client.groups.create(name: "Team A", provenance: "Test", externalSyncIdentifier: "Test Sync", description: "Test Description", invitabilityLevel: .allManagedUsers, memberViewabilityLevel: .allManagedUsers) { (result: Result<Group, BoxSDKError>) in guard case let .success(group) = result else { print("Error creating new group") return } print("Group \(group.name) was created") } ``` ## Update Group To update an existing group, call [`client.groups.update(groupId: String, name: String?, provenance: NullableParameter<String>?, externalSyncIdentifier: NullableParameter<String>?, description: NullableParameter<String>?, invitabilityLevel: GroupInvitabilityLevel?, memberViewabilityLevel: GroupMemberViewabilityLevel?, fields: [String]?, completion: @escaping Callback<Group>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC6update7groupId4name10provenance22externalSyncIdentifier11description17invitabilityLevel017memberViewabilityO06fields10completionySS_SSSgAA17NullableParameterOySSGSgA2rA017GroupInvitabilityO0OSgAA0v6MemberqO0OSgSaySSGSgys6ResultOyAA0V0CAA0A8SDKErrorCGctF) with the ID of the group. You can control which fields are returned in the resulting `Group` object by passing the `fields` parameter. ``` client.groups.update(groupId: "11111", name: "Team A", provenance: .value("Test"), externalSyncIdentifier: .value("Test Sync"), description: .value("Test Description"), invitabilityLevel: .allManagedUsers, memberViewabilityLevel: .allManagedUsers) { (result: Result<Group, BoxSDKError>) in guard case let .success(group) = result else { print("Error updating the group") return } print("Group \(group.name) was updated with description: \(group.description)") } ``` ## Get Group Info To retrieve information about a group, call [`client.groups.get(groupId: String, fields: [String]?, completion: @escaping Callback<Group>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC3get7groupId6fields10completionySS_SaySSGSgys6ResultOyAA5GroupCAA0A8SDKErrorCGctF) with the ID of the group. You can control which fields are returned in the resulting `Group` object by passing the `fields` parameter. ``` client.groups.get(groupId: "12345") { (result: Result<Group, BoxSDKError>) in guard case let .success(group) = result else { print("Error getting group information") return } print("Group with name \(group.name) was retrieved.") } ``` ## Get Enterprise Groups To retrieve information about the groups within the enterprise, call [`client.groups.listForEnterprise(name: String?, offset: Int?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC17listForEnterprise4name6offset5limit6fields10completionySSSg_SiSgAKSaySSGSgys6ResultOyAA14PagingIteratorCyAA5GroupCGAA0A8SDKErrorCGctF). You can also pass in a `name` paramter to act as a filter. This method will return an iterator object, which is used to retrieve groups in the enterprise. ``` let iterator = client.groups.listForEnterprise() iterator.next { results in switch results { case let .success(page): for group in page.entries { print("Group with name \(group.name) retrieved") } case let .failure(error): print(error) } } ``` ## Delete Group To delete a group, call [`client.groups.delete(groupId: String, completion: @escaping Callback<Void>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC6delete7groupId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the group to delete. ``` client.groups.delete(groupId: "12345") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting group") return } print("Group was successfully deleted.") } ``` # Group Membership ## Get Group Membership Info To retrieve information about a specified group membership, call [`client.groups.getMembershipInfo(membershipId: String, fields: [String]?, completion: @escaping Callback<GroupMembership>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC17getMembershipInfo12membershipId6fields10completionySS_SaySSGSgys6ResultOyAA05GroupF0CAA0A8SDKErrorCGctF) with the ID of the group membership. You can control which fields are returned on the resulting `Group Membership` object by passing the desired field names in the optional `fields` parameter. ``` client.groups.getMembershipInfo(membershipId: "12345") { (result: Result<GroupMembership, BoxSDKError>) in guard case let .success(membership) = result else { print("Error retrieving group membership information") return } print("Group Membership for group \(membership.group?.name) was retrieved") } ``` ## Create Group Membership To create a new group membership, call [`client.groups.createMembership(userId: String, groupId: String, role: GroupRole?, configurablePermission: NullableParameter<ConfigurablePermissionData>?, fields: [String]?, completion: @escaping Callback<GroupMembership>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC16createMembership6userId05groupH04role22configurablePermission6fields10completionySS_SSAA9GroupRoleOSgAA17NullableParameterOyAA012ConfigurableL4DataVGSgSaySSGSgys6ResultOyAA0oF0CAA0A8SDKErrorCGctF). You can control which fields are returned on the resulting `Group Membership` object by passing the desired field names in the optional `fields` parameter. ``` client.createMembership(userId: "54321", groupId: "11111", role: .admin, configurablePermission: .value(ConfigurablePermissionData(canRunReports: true, canInstantLogin: true, canCreateAccounts: false, canEditAccounts: true))) { (result: Result<GroupMembership, BoxSDKError>) in guard case let .success(membership) = result else { print("Error creating group membership") return } print("Group membership for group \(membership.group?.name) was created") } ``` ## Update Group Membership To update an existing group membership, call [`client.groups.updateMembership(membershipId: String, role: GroupRole?, configurablePermission: NullableParameter<ConfigurablePermissionData>?, fields: [String]?, completion: @escaping Callback<GroupMembership>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC16updateMembership12membershipId4role22configurablePermission6fields10completionySS_AA9GroupRoleOSgAA17NullableParameterOyAA012ConfigurableK4DataVGSgSaySSGSgys6ResultOyAA0nF0CAA0A8SDKErrorCGctF) with the ID of the group membership to update. ``` client.groups.updateMembership(membershipId: "12345", role: .admin, configurablePermission: .value(ConfigurablePermissionData(canRunReports: true, canInstantLogin: true, canCreateAccounts: false, canEditAccounts: true))) { (result: Result<GroupMembership, BoxSDKError>) in guard case let .success(membership) = result else { print("Error updating group membership") return } print("Group membership with ID \(membership.id) was updated") } ``` ## Delete Group Membership To delete a group membership, call [`client.groups.deleteMembership(membershipId: String, completion: @escaping: Callback<Void>)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC16deleteMembership12membershipId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the group membership to delete. ``` client.groups.deleteMembership(membershipId: "12345") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting group membership") return } print("Group Membership was successfully deleted.") } ``` ## Get Memberships for Group To retrieve information about the memberships in a group, call [`client.groups.listMemberships(groupID: String, offset: Int?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC15listMemberships7groupId6offset5limit6fields10completionySS_SiSgAJSaySSGSgys6ResultOyAA14PagingIteratorCyAA15GroupMembershipCGAA0A8SDKErrorCGctF) with the ID of the group to retrieve group memberships for. This method will return an iterator object, which is used to retrieve the memberships. ``` let iterator = client.groups.listMembership(groupId: "12345") iterator.next { result in switch results { case let .success(page): for membership in page.entries { print("Group Membership with ID \(membership.id) was retrieved") } case let .failure(error): print(error) } } ``` ## Get Memberships for User To retrieve information about the group memberships for a given user, call [`client.groups.listMembershipsForUser(userId: String, offset: Int?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC22listMembershipsForUser6userId6offset5limit6fields10completionySS_SiSgAJSaySSGSgys6ResultOyAA14PagingIteratorCyAA15GroupMembershipCGAA0A8SDKErrorCGctF) with the ID of the user to retreive group memberships for. This method will return an iterator object, which is used to retrieve the memberships. ``` let iterator = client.groups.listMembershipsForUser(userId: "12345") iterator.next { result in switch results { case let .success(page): for membership in page.entries { print("Group Membership with ID \(membership.id) was retrieved") } case let .failure(error): print(error) } } ``` ## Get Collaborations for Group To retrieve all group collaborations for a given group, call [`client.groups.listCollaborations(groupId: String, offset: Int?, limit: Int? fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/GroupsModule.html#/s:6BoxSDK12GroupsModuleC18listCollaborations7groupId6offset5limit6fields10completionySS_SiSgAJSaySSGSgys6ResultOyAA14PagingIteratorCyAA13CollaborationCGAA0A8SDKErrorCGctF) with the ID of the group to retrieve collaborations for. This method will return an iterator object, which is used to retrieve the collaborations. ``` let iterator = client.groups.listCollaborations(groupId: "12345") iterator.next { results in switch results { case let .success(page): for collaboration in page.entries { print("Collaboration with ID \(collaboration.id) was retrieved") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Recent Items A recent item object represents a file that has been recently accessed by a user. Items accessed either in the last 90 days or… # Recent Items A recent item object represents a file that has been recently accessed by a user. Items accessed either in the last 90 days or the last 1000 accessed items are tracked. - [Get Recent Items](#get-recent-items) ## Get Recent Items To get recently accessed items, call [`client.recentItems.list(marker: String?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/RecentItemsModule.html#/s:6BoxSDK17RecentItemsModuleC4list6marker5limit6fields10completionySSSg_SiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0C4ItemCGAA0A8SDKErrorCGctF). This method will return an iterator object, which is used to retrieve recent items. ``` let iterator = client.recentItems.list() iterator.next { results in switch results { case let .success(page): for item in page.entries { print("Interaction type is \(item.interactionType)") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Legal Holds Get Legal Hold Policy Info Create Legal Hold Policy Update Legal Hold Policy Delete Legal Hold Policy Get Legal Hold Policies… # Legal Holds - [Get Legal Hold Policy Info](#get-legal-hold-policy-info) - [Create Legal Hold Policy](#create-legal-hold-policy) - [Update Legal Hold Policy](#update-legal-hold-policy) - [Delete Legal Hold Policy](#delete-legal-hold-policy) - [Get Legal Hold Policies](#get-legal-hold-policies) - [Get Policy Assignment Info](#get-policy-assignment-info) - [Create Policy Assignment](#create-policy-assignment) - [Delete Policy Assignment](#delete-policy-assignment) - [Get Policy Assignments](#get-policy-assignments) - [Get File Version Legal Hold Info](#get-file-version-legal-hold-info) - [Get File Version Legal Holds](#get-file-version-legal-holds) ## Get Legal Hold Policy Info To retrieve information about a legal hold policy, call [`client.legalHolds.get(policyId: String, fields: [String]?, completion: @escaping Callback<LegalHoldPolicy>)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC3get8policyId6fields10completionySS_SaySSGSgys6ResultOyAA0C10HoldPolicyCAA0A8SDKErrorCGctF) with the ID of the policy. You can control which fields are returned in the resulting `Legal Hold Policy` object by passing the `fields` parameter. ``` client.legalHolds.get(policyId: "22222", fields: ["name", "created_at"]) { (result: Result<LegalHoldPolicy, BoxSDKError>) in guard case let .success(policy) = result else { print("Error getting policy information") return } print("Legal hold policy \(policy.id) was created at \(policy.createdAt)") } ``` ## Get Legal Hold Policies To retrieve information about the items contained in a folder, call [`client.legalHolds.listForEnterprise(policyName: String, marker: String?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC17listForEnterprise10policyName6marker5limit6fields10completionySSSg_AJSiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0C10HoldPolicyCGAA0A8SDKErrorCGctF) with the ID of the policy. This method will return an iterator object, which is used to retrieve policies in the enterprise. ``` let iterator = client.legalHolds.listForEnterprise(policyName: "policy1") iterator.next { results in switch results { case let .success(page): for policy in page.entries { print("Legal hold policy \(policy.name)") } case let .failure(error): print(error) } } ``` ## Create Legal Hold Policy To create a new legal hold policy, call [`client.legalHolds.create(policyName: String, description: String? filterStartedAt: Date?, filterEndedAt: Date?, isOngoing: Bool?, fields: [String]?, completion: @escaping Callback<LegalHoldPolicy>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC6create10policyName11description15filterStartedAt0j5EndedL09isOngoing6fields10completionySS_SSSg10Foundation4DateVSgAPSbSgSaySSGSgys6ResultOyAA0C10HoldPolicyCAA0A8SDKErrorCGctF) with a name for the legal hold policy. ``` client.legalHolds.create(name: "New Folder") { (result: Result<LegalHoldPolicy, BoxSDKError>) in guard case let .success(policy) = result else { print("Error creating legal hold policy") return } print("Created legal hold policy \"\(policy.name)\"") } ``` ## Update Legal Hold Policy To update legal hold policy, call [`client.legalHolds.update(policyId: String, policyName: String?, description: String?, releaseNotes: String?, fields: [String]?, completion: @escaping Callback<LegalHoldPolicy>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC6update8policyId0G4Name11description12releaseNotes6fields10completionySS_SSSgA2KSaySSGSgys6ResultOyAA0C10HoldPolicyCAA0A8SDKErrorCGctF). ``` client.legalHolds.update(policyId: "1234", policyName: "New Name") { (result: Result<LegalHoldPolicy, BoxSDKError>) in guard case let .success(policy) = result else { print("Error updating legal hold policy") return } print("Updated legal hold policy name is \"\(policy.name)\"") } ``` ## Delete Legal Hold Policy To delete a legal hold policy, call [`client.folders.delete(policyId: String, completion: @escaping Callback<Void>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC6delete8policyId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the legal hold policy to delete. ``` client.legalHolds.delete() { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting legal hold policy") return } print("Legal hold policy successfully deleted") } ``` ## Get Policy Assignment Info To retrieve information about a legal hold policy assignment, call [`client.legalHolds.getPolicyAssignment(assignmentId: String, fields: [String]?, completion: @escaping Callback<LegalHoldPolicyAssignment>)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC19getPolicyAssignment12assignmentId6fields10completionySS_SaySSGSgys6ResultOyAA0c4HoldgH0CAA0A8SDKErrorCGctF) with the ID of the policy assignment. You can control which fields are returned in the resulting `Legal Hold Policy Assignment` object by passing the `fields` parameter. ``` client.legalHolds.getPolicyAssignment(assignmentId: "22222", fields: ["assigned_at"]) { (result: Result<LegalHoldPolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error getting policy assignment info") return } print("Legal hold policy assignment \(assignmnent.id) was created at \(assignment.assignedAt)") } ``` ## Get Policy Assignments To retrieve legal hold policy assignments, call [`client.legalHolds.listPolicyAssignments(policyId: String, assignToType: String?, assignToId: String?, marker: String?, limit: String?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC21listPolicyAssignments8policyId12assignToType0klJ06marker5limit6fields10completionySS_SSSgA2LSiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0c4HoldG10AssignmentCGAA0A8SDKErrorCGctF) with the ID of a policy. This method will return an iterator object, which is used to retrieve policy assignments for a policy. ``` let iterator = client.legalHolds.listPolicyAssignments(policyId: "1234") iterator.next { results in switch results { case let .success(page): for assignment in page.entries { print("Policy Assignment \(assignment.id)") } case let .failure(error): print(error) } } ``` ## Assign Policy To assign a legal hold policy, call [`client.legalHolds.forceApply(policyId: String, assignToId: String, assignToType: String, fields: [String]?, completion: @escaping Callback<LegalHoldPolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC12assignPolicy8policyId0f2ToI00fJ4Type6fields10completionySS_S2SSaySSGSgys6ResultOyAA0c4HoldG10AssignmentCAA0A8SDKErrorCGctF) with an ID of a policy, an ID of a file, file version, folder, or user and the type of the box item that the policy is being assigned to. ``` client.legalHolds.forceApply(policyId: "1234", assignToId: "4568" ,assignToType: "file") { (result: Result<LegalHoldPolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error assigning legal hold policy") return } print("Assigned a legal hold policy at \"\(assignment.assignedAt)\"") } ``` ## Delete Policy Assignment To delete a legal hold policy assignment, call [`client.legalHolds.deletePolicyAssignment(policyId: String, completion: @escaping Callback<Void>`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC22deletePolicyAssignment12assignmentId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the policy assignment to delete. ``` client.legalHolds.deletePolicyAssignment(assignmentId: "1234") { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting legal hold policy assignment") return } print("Legal hold policy assignment successfully deleted") } ``` ## Get File Version Legal Hold Info To retrieve information about a file version legal hold, call [`client.legalHolds.getFileVersionPolicy(legalHoldId: String, fields: [String]?, completion: @escaping Callback<FileVersionLegalHold>)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC20getFileVersionPolicy11legalHoldId6fields10completionySS_SaySSGSgys6ResultOyAA0ghcK0CAA0A8SDKErrorCGctF) with the ID of legal hold. You can control which fields are returned in the resulting `File Version Legal Hold` object by passing the `fields` parameter. ``` client.legalHolds.getFileVersionPolicy(legalHoldId: "22222") { (result: Result<FileVersionLegalHold, BoxSDKError>) in guard case let .success(legalHold) = result else { print("Error getting file version legal hold") return } print("File version legal hold ID is \(legalHold.id)") } ``` ## Get File Version Legal Holds To retrieve all of the non-deleted legal holds for a single legal hold policy, call [`client.legalHolds.listFileVersionPolicies(policyId: String, marker: String?, limit: String?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/LegalHoldsModule.html#/s:6BoxSDK16LegalHoldsModuleC23listFileVersionPolicies8policyId6marker5limit6fields10completionySS_SSSgSiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0ghC4HoldCGAA0A8SDKErrorCGctF) with the ID of a policy. This method will return an iterator object, which is used to retrieve legal holds for a policy. ``` let iterator = client.legalHolds.listFileVersionPolicies(policyId: "1234") iterator.next { result in switch results { case let .success(page): for hold in page.entries { print("Legal hold \(hold.id)") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of… # Metadata Metadata allows users and applications to define and store custom data associated with their files/folders. Metadata consists of key-value pairs that belong to files/folders. For example, an important contract file stored on Box may have key-value pairs of `"clientNumber":"820183"` and `"clientName":"BioMedical Corp"`. Metadata that belongs to a file/folder is grouped by templates. Templates allow the metadata service to provide a multitude of features, such as pre-defining sets of key-value pairs or schema enforcement on specific fields. Each file/folder can have multiple distinct template instances associated with it, and templates are also grouped by scopes. Currently, the only scopes support are `enterprise` and `global`. Enterprise scopes are defined on a per-enterprise basis, whereas global scopes are Box application-wide. In addition to `enterprise` scoped templates, every file on Box has access to the `global` `properties` template. The `properties` template contains free-form key-value string pairs, with no additional schema associated with it. This is recommended for scenarios where applications want to write metadata to file objects in a flexible way, without pre-defined template structure. - [Get Metadata Template](#get-metadata-template) - [Create Metadata Template](#create-metadata-template) - [Update Metadata Template](#update-metadata-template) - [Delete Metadata Template](#delete-metadata-template) - [List Metadata Templates](#list-metadata-templates) - [Get All Metadata on File](#get-all-metadata-on-file) - [Get Metadata Instance on File](#get-metadata-instance-on-file) - [Add Metadata Instance to File](#add-metadata-instance-to-file) - [Update Metadata Instance on File](#update-metadata-instance-on-file) - [Remove Metadata Instance from File](#remove-metadata-instance-from-file) - [Get All Metadata on Folder](#get-all-metadata-on-folder) - [Get Metadata Instance on Folder](#get-metadata-instance-on-folder) - [Add Metadata Instance to Folder](#add-metadata-instance-to-folder) - [Update Metadata Instance on Folder](#update-metadata-instance-on-folder) - [Remove Metadata Instance from Folder](#remove-metadata-instance-from-folder) ## Get Metadata Template To retrieve information about a metadata template, call [`client.metadata.getTemplateByKey(scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC16getTemplateByKey5scope08templateH010completionySS_SSys6ResultOyAA0cF0CAA0A8SDKErrorCGctF) with the scope and key of the template. ``` client.metadata.getTemplateByKey( scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<MetadataTemplate, BoxSDKError>) in guard case let .success(template) = result { print("Error retrieving metadata template") return } print("Metadata template has \(template.fields?.count) fields") } ``` Alternatively, if you know the ID of the metadata template, you can call [`client.metadata.getTemplateById(id:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC15getTemplateById2id10completionySS_ys6ResultOyAA0cF0CAA0A8SDKErrorCGctF) with the ID of the template. ``` client.metadata.getTemplateById( id: "26004e29-7b94-44a1-8a63-f9aa384c7421" ) { (result: Result<MetadataTemplate, BoxSDKError>) in guard case let .success(template) = result { print("Error retrieving metadata template") return } print("Metadata template has \(template.fields?.count) fields") } ``` ## Create Metadata Template To create a new metadata template, call [`client.metadata.createTemplate(scope:templateKey:displayName:hidden:copyInstanceOnItemCopy:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC14createTemplate5scope11templateKey11displayName6hidden6fields10completionySS_S2SSbSayAA0C5FieldVGys6ResultOyAA0cF0CAA0A8SDKErrorCGctF) with the scope and name of the template, as well as the fields the template should contain. ``` var templateFields: [MetadataField] = [] templateFields.append(MetadataField( type: "string", key: "name", displayName: "Full Name" )) templateFields.append(MetadataField( type: "date", key: "birthday", displayName: "Birthday" )) templateFields.append(MetadataField( type: "enum", key: "department", displayName: "Department", options: [ ["key": "HR"], ["key": "Sales"], ["key": "Marketing"], ] )) client.metadata.createTemplate( scope: "enterprise", templateKey: "personnelRecord", displayName: "Personnel Record", hidden: false, fields: templateFields ) { (result: Result<MetadataTemplate, BoxSDKError>) in guard case let .success(template) = result { print("Error creating metadata template") return } print("Created metadata template with ID \(template.id)") } ``` ## Update Metadata Template To update a metadata template, including to modify its fields, call [`client.metadata.updateTemplate(scope:templateKey:operation:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC14updateTemplate5scope11templateKey9operation10completionySS_SSAA0cF9OperationOys6ResultOyAA0cF0CAA0A8SDKErrorCGctF) with the scope and key of the template to update, as well as the update operation to perform. In this example, we are updating the metadata template using the ReorderEnumOptions operation. Other metadata template update operations include: addEnumOption, addField, editTemplate, reorderFields ``` client.metadata.updateTemplate( scope: "enterprise", templateKey: "personnelRecord", operation: .reorderEnumOptions(fieldKey: "department", enumOptionKeys: ["Marketing", "Sales", "HR"]) ) { (result: Result<MetadataTemplate, BoxSDKError>) in guard case let .success(template) = result { print("Error updating metadata template") return } print("Updated metadata template with ID \(template.id)") } ``` ## Delete Metadata Template To delete a metadata template, call [`client.metadata.deleteTemplate(scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC14deleteTemplate5scope11templateKey10completionySS_SSys6ResultOyytAA0A8SDKErrorCGctF) with the scope and key of the template to delete. ``` client.metadata.deleteTemplate( scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<Void, BoxSDKError>) in guard case .success = result { print("Error deleting metadata template") return } print("Metadata template deleted") } ``` ## List Metadata Templates To retrieve the collection of available metadata templates in a particular scope, call [`client.metadata.listEnterpriseTemplates(scope:marker:limit:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC23listEnterpriseTemplates5scope6marker5limit10completionySS_SSSgSiSgys6ResultOyAA14PagingIteratorCyAA0C8TemplateCGAA0A8SDKErrorCGctF) with the scope. This method will return an iterator, which is used to retrieve metadata templates. ``` let iterator = client.metadata.listEnterpriseTemplates(scope: "enterprise") iterator.next { results in switch results { case let .success(page): for template in page.entries { print("Template name: \(template.displayName)") } case let .failure(error): print(error) } } ``` Similarly, to get all templates available in the `global` scope. ``` let iterator = client.metadata.listEnterpriseTemplates(scope: "global") iterator.next { results in switch results { case let .success(page): for template in page.entries { print("Template name: \(template.displayName)") } case let .failure(error): print(error) } } ``` ## Get All Metadata on File To retrieve all metadata attached to a file, call [`client.metadata.list(forFileId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC4list9forFileId10completionySS_ys6ResultOySayAA0C6ObjectCGAA0A8SDKErrorCGctF) with the ID of the file. ``` client.metadata.list(forFileId: "11111") { (result: Result<[MetadataObject], BoxSDKError>) in guard case let .success(metadata) = result { print("Error retrieving metadata") return } print("Retrieved \(metadata.count) metadata instances:") for instance in metadata { print("- \(instance.template)") } } ``` ## Get Metadata Instance on File To retrieve a specific metadata instance attached to a file, call [`client.metadata.get(forFileWithId:scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC3get13forFileWithId5scope11templateKey10completionySS_S2Sys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the file ID, as well as the scope and key of the metadata template of the instance. ``` client.metadata.get( forFileWithId: "11111", scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error retrieving metadata") return } print("Found personnel record for \(metadata.keys["name"])") } ``` ## Add Metadata Instance to File To attach a new metadata instance to a file, call [`client.metadata.create(forFileWithId:scope:templateKey:keys:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6create13forFileWithId5scope11templateKey4keys10completionySS_S2SSDySSypGys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the ID of the file, as well as the scope and key of the metadata template to use and the metadata keys and values to attach. ``` let metadata = [ "name": "John Doe", "birthday": "2000-01-01T00:00:00Z", "department": "Sales" ] client.metadata.create( forFileWithId: "11111", scope: "enterprise", templateKey: "personnelRecord", keys: metadata ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error adding metadata") return } print("Successfully attached metadata") } ``` ## Update Metadata Instance on File To update the values in a metadata instance attached to a file, call [`client.metadata.updateforFileWithId:scope:templateKey:operations:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6update13forFileWithId5scope11templateKey10operations10completionySS_S2SSayAA0gC9OperationOGys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the ID of the file, the scope and key of the metadata template associated with the instance, and the operations to perform on the metadata. ``` client.metadata.update( forFileWithId: "11111", scope: "enterprise", templateKey: "personnelRecord", operations: [ .test(path: "/department", value: "Sales"), .replace(path: "/department", value: "Marketing") ] ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error updating metadata") return } print("Employee department updated to \(metadata.keys["department"])") } ``` ## Remove Metadata Instance from File To remove a specific metadata instance from a file, call [`client.metadata.delete(forFileWithId:scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6delete13forFileWithId5scope11templateKey10completionySS_S2Sys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file, as well as the scope and key of the metadata template associated with the instance. ``` client.metadata.delete( forFileWithId: "11111", scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<Void, BoxSDKError>) in guard case .success = result { print("Error deleting metadata instance") return } print("Metadata instance deleted") } ``` ## Get All Metadata on Folder To retrieve all metadata attached to a folder, call [`client.metadata.list(forFolderId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC4list11forFolderId10completionySS_ys6ResultOySayAA0C6ObjectCGAA0A8SDKErrorCGctF) with the ID of the folder. ``` client.metadata.list(forFolderId: "22222") { (result: Result<[MetadataObject], BoxSDKError>) in guard case let .success(metadata) = result { print("Error retrieving metadata") return } print("Retrieved \(metadata.count) metadata instances:") for instance in metadata { print("- \(instance.template)") } } ``` ## Get Metadata Instance on Folder To retrieve a specific metadata instance attached to a folder, call [`client.metadata.get(forFolderWithId:scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC3get15forFolderWithId5scope11templateKey10completionySS_S2Sys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the folder ID, as well as the scope and key of the metadata template of the instance. ``` client.metadata.get( forFolderWithId: "22222", scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error retrieving metadata") return } print("Found personnel record for \(metadata.keys["name"])") } ``` ## Add Metadata Instance to Folder To attach a new metadata instance to a folder, call [`client.metadata.create(forFolderWithId:scope:templateKey:keys:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6create15forFolderWithId5scope11templateKey4keys10completionySS_S2SSDySSypGys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the ID of the folder, as well as the scope and key of the metadata template to use and the metadata keys and values to attach. ``` let metadata = [ "name": "John Doe", "birthday": "2000-01-01T00:00:00Z", "department": "Sales" ] client.metadata.create( forFolderWithId: "22222", scope: "enterprise", templateKey: "personnelRecord", keys: metadata ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error adding metadata") return } print("Successfully attached metadata") } ``` ## Update Metadata Instance on Folder To update the values in a metadata instance attached to a folder, call [`client.metadata.update(forFolderWithId:scope:templateKey:operations:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6update15forFolderWithId5scope11templateKey10operations10completionySS_S2SSayAA0gC9OperationOGys6ResultOyAA0C6ObjectCAA0A8SDKErrorCGctF) with the ID of the folder, the scope and key of the metadata template associated with the instance, and the operations to perform on the metadata. ``` client.metadata.update( forFolderWithId: "22222", scope: "enterprise", templateKey: "personnelRecord", operations: [ .test(path: "/department", value: "Sales"), .replace(path: "/department", value: "Marketing") ] ) { (result: Result<MetadataObject, BoxSDKError>) in guard case let .success(metadata) = result { print("Error updating metadata") return } print("Employee department updated to \(metadata.keys["department"])") } ``` ## Remove Metadata Instance from Folder To remove a specific metadata instance from a folder, call [`client.metadata.delete(forFolderWithId:scope:templateKey:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/MetadataModule.html#/s:6BoxSDK14MetadataModuleC6delete15forFolderWithId5scope11templateKey10completionySS_S2Sys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the folder, as well as the scope and key of the metadata template associated with the instance. ``` client.metadata.delete( forFolderWithId: "22222", scope: "enterprise", templateKey: "personnelRecord" ) { (result: Result<Void, BoxSDKError>) in guard case .success = result { print("Error deleting metadata instance") return } print("Metadata instance deleted") } ``` --- ## Untitled *Type: page* Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention… # Retention Policies A retention policy blocks permanent deletion of content for a specified amount of time. Admins can create retention policies and then later assign them to specific folders or their entire enterprise. To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console. - [Create Retention Policy](#create-retention-policy) - [Update Retention Policy](#update-retention-policy) - [Get Retention Policy](#get-retention-policy) - [Get Retention Policies](#get-retention-policies) - [Create Retention Policy Assignment](#create-retention-policy-assignment) - [Get Retention Policy Assignment](#get-retention-policy-assignment) - [Get Retention Policy Assignments](#get-retention-policy-assignments) - [Delete Retention Policy Assignment](#delete-retention-policy-assignment) - [Get File Version Retention](#get-file-version-retention) - [Get File Version Retentions](#get-file-version-retentions) (will be deprecated in the future, use [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) and [Get File Version Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) instead) - [Get Files Under Retention For Assignment](#get-files-under-retention-for-assignment) - [Get File Version Under Retention For Assignment](#get-file-versions-under-retention-for-assignment) ## Create Retention Policy To create a retention policy, call [`client.retentionPolicy.create(name:type:length:dispositionAction:canOwnerExtendRetention:areOwnersNotified:customNotificationRecipients:retentionType:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC6create4name4type6length17dispositionAction014canOwnerExtendC017areOwnersNotified28customNotificationRecipients13retentionType10completionySS_AA0c6PolicyV0OSiSgAA011DispositionK0OSbSgASSayAA4UserCGSgAA0cV0OSgys6ResultOyAA0cX0CAA0A8SDKErrorCGctF). You can create either a `indefinite` retention policy, or a `finite`. To create a `indefinite` retention policy, you must set a `type` to `.indefinite` and a `dispositionAction` to `.removeRetention`. ``` client.retentionPolicy.create( name: "Test Indefinite Policy Name", type: .indefinite, dispositionAction: .removeRetention ) { result in guard case let .success(retentionPolicy) = result else { print("Error creating retention policy") return } print("Retention policy: \(retentionPolicy.id) was created") } ``` To create a `finite` retention policy, you must set `type` to `.finite`, set amount of time in days to apply the retention policy (`length`) and a `dispositionAction`. The disposition action can be `.permanentlyDelete` or `.removeRetention`. ``` client.retentionPolicy.create( name: "Test Finite Policy Name", type: .finite, length: 60, dispositionAction: .permanentlyDelete ) { result in guard case let .success(retentionPolicy) = result else { print("Error creating retention policy") return } print("Retention policy: \(retentionPolicy.id) was created") } ``` ## Update Retention Policy To update a retention policy, call [`client.retentionPolicy.update(policyId:name:dispositionAction:status:setRetentionTypeToNonModifiable:length:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC6update8policyId4name17dispositionAction6status03setC19TypeToNonModifiable6length10completionySS_SSSgAA011DispositionK0OSgAA0C12PolicyStatusOSgSbSiSgys6ResultOyAA0cU0CAA0A8SDKErrorCGctF). ``` client.retentionPolicy.update(policyId: "1234", name: "New Policy Name") { result in guard case let .success(retentionPolicy) = result else { print("Error updating a retention policy") return } print("Updated retention policy: \(retentionPolicy.id)") } ``` ## Get Retention Policy To retrieve information about a retention policy, call [`client.retentionPolicy.get(policyId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC3get8policyId10completionySS_ys6ResultOyAA0C6PolicyCAA0A8SDKErrorCGctF) with the ID of the retention policy. ``` client.retentionPolicy.get(policyId: "1234") { result in guard case let .success(retentionPolicy) = result else { print("Error getting retention policy") return } print("Retention policy: \(retentionPolicy.id)") } ``` ## Get Retention Policies To retrieve all retention policies for an enterprise, call [`client.retentionPolicy.list(name:type:createdByUserId:marker:limit:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC4list4name4type15createdByUserId6marker5limitAA14PagingIteratorCyAA0C11PolicyEntryCGSSSg_AA0cQ4TypeOSgA2OSiSgtF). This method will return an iterator, which is used to get the policies. As you can see in the method signature, it is possible to specify filter for the name, type and created user of the retention policy. All of mentioned fields are optional and if not set, all retention policies will be returned. You can also set a number of items per single response by setting a limit. ``` let iterator = client.retentionPolicy.list(type: .indefinite) iterator.next { results in switch results { case let .success(page): for policy in page.entries { print("Retention policy \(policy.id)") } case let .failure(error): print(error) } } ``` ## Create Retention Policy Assignment To create new retention policy assignment call [`client.retentionPolicy.assign(policyId:assignedContentId:assignContentType:filterFields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC6assign8policyId015assignedContentH00fJ4Type12filterFields10completionySS_SSAA0c20PolicyAssignmentItemK0OSayAA19MetadataFieldFilterVGSgys6ResultOyAA0coP0CAA0A8SDKErrorCGctF) method to assign the policy. Retention policy can be assigned to a specific folder, to a metadata template or to the entire enterprise. ``` client.retentionPolicy.assign(policyId: "12345", assignedContentId: "1111", assignContentType: .folder) { result in guard case let .success(retentionPolicyAssignment) = result else { print("Error creating retention policy assignment") return } print("Retention policy assignment: \(retentionPolicyAssignment.id) was created") } ``` ## Get Retention Policy Assignment To retrieve information about a retention policy assignment, call [`client.retentionPolicy.getAssignment(assignmentId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC13getAssignment12assignmentId10completionySS_ys6ResultOyAA0c6PolicyG0CAA0A8SDKErrorCGctF) with the ID of the assignment. ``` client.retentionPolicy.getAssignment(assignmentId: "123456") { result in guard case let .success(retentionPolicyAssignment) = result else { print("Error getting retention policy assignment") return } print("Retention policy assignment: \(retentionPolicyAssignment.id)") } ``` ## Get Retention Policy Assignments To get a list of all retention policy assignments associated with a specified retention policy, call [`client.retentionPolicy.listAssignments(policyId:type:marker:limit:fields)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC15listAssignments8policyId4type6marker5limit6fieldsAA14PagingIteratorCyAA0C16PolicyAssignmentCGSS_AA0cpQ8ItemTypeOSgSSSgSiSgSaySSGSgtF). This method will return an iterator, which is used to get the assignments. ``` let iterator = client.retentionPolicy.listAssignments(policyId:"12345") iterator.next { results in switch results { case let .success(page): for assignment in page.entries { print("Retention policy assignment\(assignment.id)") } case let .failure(error): print(error) } } ``` You can also filter assignments by setting `type` parameter to one of values: `.folder`, `.metadataTemplate` or `.enterprise`: ``` let iterator = client.retentionPolicy.listAssignments(policyId:"12345", type: .folder) iterator.next { results in switch results { case let .success(page): for assignment in page.entries { print("Retention policy assignment\(assignment.id)") } case let .failure(error): print(error) } } ``` ## Delete Retention Policy Assignment To remove a retention policy assignment applied to content, call [`client.retentionPolicy.deleteAssignment(assignmentId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC16deleteAssignment12assignmentId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the assignment. ``` client.retentionPolicy.deleteAssignment(assignmentId: "123456") { result in guard case let .success = result else { print("Error deleting retention policy assignment") return } print("Retention policy assignment was deleted") } ``` ## Get File Version Retention A file version retention is a record for a retained file version. To get information for a specific file version retention record, call [`client.files.getVersionRetention(retentionId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC19getVersionRetention11retentionId10completionySS_ys6ResultOyAA04FilefG0CAA0A8SDKErrorCGctF) with the ID of the file version retention. ``` client.files.getVersionRetention(retentionId: "123456"){ result in guard case let .success(retention) = result else { print("Error getting file version retention") return } print("File version retention: \(retention.id)") } ``` ## Get File Version Retentions To retrieves all file version retentions for the given enterprise, call [`client.files.listVersionRetentions(fileId:fileVersionId:policyId:dispositionAction:dispositionBefore:dispositionAfter:limit:marker:)`](https://opensource.box.com/box-ios-sdk/Classes/FilesModule.html#/s:6BoxSDK11FilesModuleC21listVersionRetentions6fileId0hfI006policyI017dispositionAction0K6Before0K5After5limit6markerAA14PagingIteratorCyAA04FileF9RetentionCGSSSg_A2rA011DispositionL0OSg10Foundation4DateVSgAYSiSgARtF). This method will return an iterator, which is used to get the file version retentions. ``` let iterator = client.files.listVersionRetentions() iterator.next { results in switch results { case let .success(page): for retention in page.entries { print("File version retention \(retention.id)") } case let .failure(error): print(error) } } ``` ## Get Files Under Retention For Assignment To get all files under retention for assignment policy, call the [`client.retentionPolicy.listFilesUnderRetentionForAssignment(retentionPolicyAssignmentId:limit:marker:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC014listFilesUnderC13ForAssignment015retentionPolicyJ2Id5limit6markerAA14PagingIteratorCyAA4FileCGSS_SiSgSSSgtF) method. This method will return an iterator, which is used to get the [`File`](https://opensource.box.com/box-ios-sdk/Classes/File.html) objects under retention. ``` let iterator = client.retentionPolicy.listFilesUnderRetentionForAssignment(retentionPolicyAssignmentId: "123456") iterator.next { results in switch results { case let .success(page): for file in page.entries { print("File \(file.name ?? "")") } case let .failure(error): print(error) } } ``` ## Get File Versions Under Retention For Assignment To get all file versions under retention placed in the file objects for a retention policy assignment, call the [`client.retentionPolicy.listFileVersionsUnderRetentionForAssignment(retentionPolicyAssignmentId:limit:marker:)`](https://opensource.box.com/box-ios-sdk/Classes/RetentionPoliciesModule.html#/s:6BoxSDK23RetentionPoliciesModuleC021listFileVersionsUnderC13ForAssignment015retentionPolicyK2Id5limit6markerAA14PagingIteratorCyAA0G0CGSS_SiSgSSSgtF) method. This method will return an iterator, which is used to get the [`FileVersion`](https://opensource.box.com/box-ios-sdk/Classes/FileVersion.html) object nested in [`File`](https://opensource.box.com/box-ios-sdk/Classes/File.html) object. ``` let iterator = client.retentionPolicy.listFileVersionsUnderRetentionForAssignment(retentionPolicyAssignmentId: "123456") iterator.next { results in switch results { case let .success(page): for file in page.entries { print("File version \(file.fileVersion?.id ?? "")") } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Shared Items Shared Items represent files and folders on Box available via a shared link. Get Shared Item Get Shared Item To get the file or… # Shared Items Shared Items represent files and folders on Box available via a shared link. - [Get Shared Item](#get-shared-item) ## Get Shared Item To get the file or folder information for a shared link, call [`client.sharedItems.getSharedItem(sharedLinkURL:sharedLinkPassword:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/SharedItemsModule.html#/s:6BoxSDK17SharedItemsModuleC3get13sharedLinkURL0gH8Password6fields10completionySS_SSSgSaySSGSgys6ResultOyAA0C4ItemCAA0A8SDKErrorCGctF) with the URL of the shared link. The `sharedLinkPassword` parameter should be provided if the shared link is password-protected. ``` client.sharedItems.get( sharedLinkURL: "https://app.box.com/s/qqwertyuiopasdfghjklzxcvbnm123456" ) { (result: Result<SharedItem, BoxSDKError>) in guard case let .success(item) = result else { print("Error resolving shared item") return } print("The shared link resolves to item:") switch item { case let .file(file): print("- File \(file.name) (ID: \(file.id))") case let .folder(folder): print("- Folder \(file.name) (ID: \(file.id))") case let .webLink(webLink): print("- Web Link \(file.name) (ID: \(file.id))") } } ``` --- ## Untitled *Type: page* Search Content Search Content Search with Shared Link Items Metadata Search Content Search To get a list of items matching a search query… # Search - [Content Search](#content-search) - [Content Search with Shared Link Items](#content-search-with-shared-link-items) - [Metadata Search](#metadata-search) ## Content Search To get a list of items matching a search query, call [`client.search.query(query:...)`](https://opensource.box.com/box-ios-sdk/Classes/SearchModule.html#/s:6BoxSDK12SearchModuleC5queryAD5scope14fileExtensions12createdAfter0I6Before07updatedJ00lK011sizeAtLeast0mN4Most12ownerUserIDs014ancestorFolderS08searchIn8itemType0V5Trash14metadataFilter6fields6offset5limit10completionySSSg_AA0C5ScopeOSgSaySSGSg10Foundation4DateVSgA4_A4_A4_s5Int64VSgA7_A0_A0_SayAA0c7ContentY0OGSgAA0c4ItemY0OSgSbSgAA08MetadataC6FilterCSgA0_SiSgA19_ys6ResultOyAA14PagingIteratorCyAA0U4ItemOGAA0A8SDKErrorCGctF) with the string to query for. There are many possible options for advanced search filtering, which can be used to narrow down the search results. This method will return an iterator object, which is used to get the results. ``` let iterator = client.search.query(query: "Quarterly Business Review") iterator.next { results in switch results { case let .success(page): for item in page.entries { switch item { case let .file(file): print("- File \(file.name) (ID: \(file.id))") case let .folder(folder): print("- Folder \(file.name) (ID: \(file.id))") case let .webLink(webLink): print("- Web Link \(file.name) (ID: \(file.id))") } } case let .failure(error): print(error) } } ``` ## Content Search with Shared Link Items To get a list of items matching a search query, including items that a user might have accessed recently through a shared link, call [`client.search.queryWithSharedLinks(query:...)`](https://opensource.box.com/box-ios-sdk/Classes/SearchModule.html#/s:6BoxSDK12SearchModuleC5queryAD5scope14fileExtensions12createdAfter0I6Before07updatedJ00lK011sizeAtLeast0mN4Most12ownerUserIDs014ancestorFolderS08searchIn8itemType0V5Trash14metadataFilter6fields6offset5limit10completionySSSg_AA0C5ScopeOSgSaySSGSg10Foundation4DateVSgA4_A4_A4_s5Int64VSgA7_A0_A0_SayAA0c7ContentY0OGSgAA0c4ItemY0OSgSbSgAA08MetadataC6FilterCSgA0_SiSgA19_ys6ResultOyAA14PagingIteratorCyAA0U4ItemOGAA0A8SDKErrorCGctF) with the string to query for. There are many possible options for advanced search filtering, which can be used to narrow down the search results. This method will return an iterator object, which is used to get the results. ``` let iterator = client.search.queryWithSharedLinks(query: "Quarterly Business Review") iterator.next { results in switch results { case let .success(page): for searchResult in page.entries { let item = searchResult.item switch item { case let .file(file): print("- File \(file.name) (ID: \(file.id))") case let .folder(folder): print("- Folder \(file.name) (ID: \(file.id))") case let .webLink(webLink): print("- Web Link \(file.name) (ID: \(file.id))") } } case let .failure(error): print(error) } } ``` ## Metadata Search To search within metadata for specific values, use the helper methods included in the SDK to construct the metadata query and call [`client.search.query(query:...)`](https://opensource.box.com/box-ios-sdk/Classes/SearchModule.html#/s:6BoxSDK12SearchModuleC5queryAD5scope14fileExtensions12createdAfter0I6Before07updatedJ00lK011sizeAtLeast0mN4Most12ownerUserIDs014ancestorFolderS08searchIn8itemType0V5Trash14metadataFilter6fields6offset5limit10completionySSSg_AA0C5ScopeOSgSaySSGSg10Foundation4DateVSgA4_A4_A4_s5Int64VSgA7_A0_A0_SayAA0c7ContentY0OGSgAA0c4ItemY0OSgSbSgAA08MetadataC6FilterCSgA0_SiSgA19_ys6ResultOyAA14PagingIteratorCyAA0U4ItemOGAA0A8SDKErrorCGctF) with the metadata filters and optionally a search query. If no additional content query string is needed, just set the `query` parameter to `nil`. This method will return an iterator object, which is used to get the results. ``` let metadataFilters = MetadataSearchFilter() metadataFilters.addFilter(templateKey: "contract", fieldKey: "contractType", fieldValue: "NDA") metadataFilters.addFilter(templateKey: "contract", fieldKey: "date", fieldValue: "2019-01-01T00:00:00Z", relation: .greaterThan) let iterator = client.search.query(query: nil, metadataFilter: metadataFilters) iterator.next { results in switch results { case let .success(page): for item in page.entries { switch item { case let .file(file): print("- File \(file.name) (ID: \(file.id))") case let .folder(folder): print("- Folder \(file.name) (ID: \(file.id))") case let .webLink(webLink): print("- Web Link \(file.name) (ID: \(file.id))") } } case let .failure(error): print(error) } } ``` --- ## Untitled *Type: page* Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files… # Sign Requests Sign Requests are used to request e-signatures on documents from signers. A Sign Request can refer to one or more Box Files and can be sent to one or more Box Sign Request Signers. - [Create Sign Request](#create-sign-request) - [List Sign Requests](#list-sign-requests) - [Get Sign Request by ID](#get-sign-request-by-id) - [Cancel Sign Request by ID](#cancel-sign-request-by-id) - [Resend Sign Request by ID](#resend-sign-request-by-id) ## Create Sign Request To create a sign request, call [`client.signRequests.create(signers:sourceFiles:parentFolder:parameters:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC6create7signers11sourceFiles12parentFolder10parameters10completionySayAA0C19RequestCreateSignerVG_SayAA0cnO10SourceFileVGAA0cno6ParentK0VAA0cnO10ParametersVSgys6ResultOyAA0cN0CAA0A8SDKErrorCGctF) You need to provide at least one file and up to ten files (from which the signing document will be created) with at least one signer to receive the Sign Request and a destination folder. You should use [`SignRequestCreateSourceFile`](https://opensource.box.com/box-ios-sdk/Structs/SignRequestCreateSourceFile.html) ,[`SignRequestCreateSigner`](https://opensource.box.com/box-ios-sdk/Structs/SignRequestCreateSigner.html) and [`SignRequestCreateParentFolder`](https://opensource.box.com/box-ios-sdk/Structs/SignRequestCreateParentFolder.html) types to provide the necessary data. ``` let signers = [SignRequestCreateSigner(email: "signer@mail.com", role: .approver)] let sourceFiles = [SignRequestCreateSourceFile(id: "12345"), SignRequestCreateSourceFile(id: "34567")] let parentFolder = SignRequestCreateParentFolder(id: "234") client.signRequests.create(signers: signers, sourceFiles: sourceFiles, parentFolder: parentFolder) { (result: Result<SignRequest, BoxSDKError>) in guard case let .success(signRequest) = result else { print("Error creating sign request") return } print("Sign request \(signRequest.id) was created") } ``` [`create`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC6create7signers11sourceFiles12parentFolder10parameters10completionySayAA0C19RequestCreateSignerVG_SayAA0cnO10SourceFileVGAA0cno6ParentK0VAA0cnO10ParametersVSgys6ResultOyAA0cN0CAA0A8SDKErrorCGctF) method allows you to specify optional parameters using the [`SignRequestCreateParameters`](https://opensource.box.com/box-ios-sdk/Structs/SignRequestCreateParameters.html) object. ``` let signers = [SignRequestCreateSigner(email: "signer@mail.com", role: .approver)] let sourceFiles = [SignRequestCreateSourceFile(id: "12345", fileVersionId: "5")] let parentFolder = SignRequestCreateParentFolder(id: "234") let params = SignRequestCreateParameters( isDocumentPreparationNeeded: true, emailSubject: "Sign Request from Acme", emailMessage: "Hello! Please sign the document below" ) client.signRequests.create(signers: signers, sourceFiles: sourceFiles, parentFolder: parentFolder) { (result: Result<SignRequest, BoxSDKError>) in guard case let .success(signRequest) = result else { print("Error creating sign request") return } print("Sign request \(signRequest.id) was created") } ``` If you set `isDocumentPreparationNeeded` flag to true, you need to visit `prepareUrl` before the Sign Request will be sent. ## List Sign Requests To retrieve sign requests, call [`client.signRequests.list(marker:limit:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC4list6marker5limitAA14PagingIteratorCyAA0C7RequestCGSSSg_SiSgtF). This method will return an iterator object, which is used to get the sign requests. ``` let iterator = client.signRequests.list() iterator.next { results in switch results { case let .success(page): for signRequest in page.entries { print("Sign request \(signRequest.id)") } case let .failure(error): print(error) } } ``` ## Get Sign Request by ID To retrieve information about a sign request, call [`client.signRequests.getById(id:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC7getById2id10completionySS_ys6ResultOyAA0C7RequestCAA0A8SDKErrorCGctF) with the ID of the sign request. ``` client.signRequests.getById(id: "1234") { (result: Result<SignRequest, BoxSDKError>) in guard case let .success(signRequest) = result else { print("Error getting sign request") return } print("Sign request \(signRequest.id)") } ``` ## Cancel Sign Request by ID To cancel a created sign request, call [`client.signRequests.cancelById(id:, completion:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC10cancelById2id10completionySS_ys6ResultOyAA0C7RequestCAA0A8SDKErrorCGctF) ``` client.signRequests.cancelById(id: "1234") { (result: Result<SignRequest, BoxSDKError>) in guard case let .success(signRequest) = result else { print("Error cancelling sign request") return } print("Sign request \(signRequest.id) is cancelled") } ``` ## Resend Sign Request by ID To resend a sign request to all signers that have not signed it yet, call [`client.signRequests.resendById(id:, completion:)`](https://opensource.box.com/box-ios-sdk/Classes/SignRequestsModule.html#/s:6BoxSDK18SignRequestsModuleC10resendById2id10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF). There is an 10-minute cooling-off period between re-sending reminder emails. If this method is called during the cooling-off period, a BoxAPIError will be thrown. ``` client.signRequests.resendById(id: "1234") { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error resending sign request") return } print("Sign request successfully resent") } ``` --- ## Untitled *Type: page* Terms of Services Terms of Service are custom objects that the admin of an enterprise can configure. This will prompt the end user to accept… # Terms of Services Terms of Service are custom objects that the admin of an enterprise can configure. This will prompt the end user to accept/re-accept or decline the custom Terms of Service for custom applications built on Box Platform. - [Get Terms of Service By ID](#get-terms-of-service-by-id) - [Create Terms of Service](#create-terms-of-service) - [Update Terms of Service](#update-terms-of-service) - [List Terms of Services for an Enterprise](#list-terms-of-services-for-an-enterprise) - [Create User Status on Terms of Service](#create-user-status-on-terms-of-service) - [Update User Status of Terms of Service](#update-user-status-of-terms-of-service) - [Get User Status for Terms of Service](#get-user-status-for-terms-of-service) ## Get Terms of Service By ID To retrieve information about a terms of service, call [`client.termsOfService.get(tosId:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC3get5tosId6fields10completionySS_SaySSGSgys6ResultOyAA0cD7ServiceCAA0A8SDKErrorCGctF) with the ID of the terms of service. You can control which fields are returned in the resulting `Terms of Service` object by passing the `fields` parameter. ``` client.termsOfService.get( tosID: "12345" ) { (result: Result<TermsOfService, BoxSDKError>) in guard case let .success(termsOfService) = result else { print("Error getting terms of service information") return } print("Terms of Service with id: \(termsOfService.id) was retrieved") } ``` ## Create Terms of Service To create a terms of service, call [`client.termsOfService.create(status:tosType:text:fields:completion`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC6create6status7tosType4text6fields10completionyAA0cD13ServiceStatusO_AA0cdnJ0OSSSaySSGSgys6ResultOyAA0cdN0CAA0A8SDKErrorCGctF). You can control which fields are returned in the resulting `Terms of Service` object by passing the `fields` parameter. ``` client.termsOfService.create( status: .enabled, tosType: .managed, text: "Test Terms of Service" ) { (result: Result<TermsOfService, BoxSDKError>) in guard case let .success(termsOfService) = result else { print("Error creating terms of service") return } print("Terms of Service with id: \(termsOfService.id) was created") } ``` ## Update Terms of Service To update a terms of service, call [`client.termsOfService.update(tosId:text:status:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC6update5tosId4text6status6fields10completionySS_SSAA0cD13ServiceStatusOSaySSGSgys6ResultOyAA0cdN0CAA0A8SDKErrorCGctF) with the ID of the terms of service to update. You can control which fields are returned in the resulting `Terms of Service` object by passing the `fields` parameter. ``` client.termsOfService.update( tosId: "12345", text: "Updated Text String", status: TermsOfServiceStatus.enabled ) { (result: Result<TermsOfService, BoxSDKError>) in guard calse let .success(termsOfService) = result else { print("Error updating terms of service") return } print("Terms of Service with id: \(termsOfService.id) was updated with text: \(termsOfService.text)") } ``` ## List Terms of Services for an Enterprise To retrieve a list of terms of services for an enterprise, call [`client.termsOfService.listForEnterprise(tosType:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC17listForEnterprise7tosType6fields10completionyAA0cd7ServiceK0OSg_SaySSGSgys6ResultOySayAA0cdN0CGAA0A8SDKErrorCGctF) with the type of terms of service to retrieve. If left nil, then terms of services of both types, `managed` and `external` will be retrieved. You can control which fields are returned in the resulting `Terms of Service` objects by passing the `fields` parameter. ``` let termsOfServiceItems = client.termsOfService.listForEnterprise() print("Terms of Service with ID \(termsOfServiceItems[0].id) and Terms of Service with ID \(termsOfServiceItems[1].id) was retrieved.") ``` ## Create User Status on Terms of Service To accept or decline a terms of service for a user who has never accepted/declined this terms of service before call [`client.termsOfService.createUserStatus(tosId:isAccepted:userId:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC16createUserStatus5tosId10isAccepted04userK06fields10completionySS_SbSSSgSaySSGSgys6ResultOyAA0cd7ServicehI0CAA0A8SDKErrorCGctF). You can control which fields are returned in the resulting `Terms of Service User Status` object by passing the `fields` parameter. ``` client.termsOfService.createUserStatus( tosId: "12345", isAccepted: true, userId: "54321" ) { (result: Result<TermsOfServiceUserStatus, BoxSDKError>) in guard case let .success(userStatus) = result else { print("Error accepting Terms of Service for new user") return } print("User status for accepting of Terms of Service is \(userStatus.isAccepted)") } ``` ## Update User Status of Terms of Service To update a user status on a terms of service call [`client.termsOfService.updateUserStatus(userStatusId:isAccepted:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC16updateUserStatus04userI2Id10isAccepted6fields10completionySS_SbSaySSGSgys6ResultOyAA0cd7ServicehI0CAA0A8SDKErrorCGctF). You can control which fields are returned in the resulting `Terms of Service User Status` object by passing the `fields` parameter. ``` client.termsOfService.updateUserStatus( userStatusId: "12345", isAccepted: true ) { (result: Result<TermsOfServiceUserStatus, BoxSDKError>) in guard case let .success(userStatus) = result else { print("Error updating Terms of Service User Status") return } print("User status for updating of Terms of Service is \(userStatus.isAccepted)") } ``` ## Get User Status for Terms of Service To retrieve the user status for a user on a terms of service, call [`client.termsOfService.getUserStatus(tosId:userId:fields:completion)`](https://opensource.box.com/box-ios-sdk/Classes/TermsOfServicesModule.html#/s:6BoxSDK21TermsOfServicesModuleC13getUserStatus5tosId04userK06fields10completionySS_SSSgSaySSGSgys6ResultOyAA0cd7ServicehI0CAA0A8SDKErrorCGctF) with the ID of the `Terms of Service` object and the ID of the user. ``` client.termsOfService.getUserStatus( tosId: "12345", userId: "54321" ) { (result: Result<TermsOfServiceUserStatus, BoxSDKError>) in guard case let .success(userStatus) = result else { print("Error retrieving user status for Terms of Service") return } print("User status with ID \(userStatus.id) was retrieved") } ``` --- ## Untitled *Type: page* Users Users represent an individual's account on Box. Get Current User Get User Upload User Avatar Get User Avatar Delete User Avatar Create… # Users Users represent an individual's account on Box. - [Get Current User](#get-current-user) - [Get User](#get-user) - [Upload User Avatar](#upload-user-avatar) - [Get User Avatar](#get-user-avatar) - [Delete User Avatar](#delete-user-avatar) - [Create User](#create-user) - [Create App User](#create-app-user) - [Update User](#update-user) - [Change User Login](#change-user-login) - [Delete User](#delete-user) - [Get Enterprise Users](#get-enterprise-users) - [Invite User to Enterprise](#invite-user-to-enterprise) - [Move User Content](#move-user-content) - [Get User Email Aliases](#get-user-email-aliases) - [Add User Email Alias](#add-user-email-alias) - [Remove User Email Alias](#remove-user-email-alias) - [Roll User Out of Enterprise](#roll-user-out-of-enterprise) ## Get Current User To retrieve information about the currently authenticated user, call [`client.users.getCurrent(fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC10getCurrent6fields10completionySaySSGSg_ys6ResultOyAA4UserCAA0A8SDKErrorCGctF). ``` client.users.getCurrent(fields: ["name", "login"]) { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error getting user information") return } print("Authenticated as \(user.name), with login \(user.login)") } ``` ## Get User To retrieve information about a specific user, call [`client.users.get(userId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC3get6userId6fields10completionySS_SaySSGSgys6ResultOyAA4UserCAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.get(userId: "33333", fields: ["name", "login"]) { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error getting user information") return } print("Got user \(user.name), with login \(user.login)") } ``` ## Upload User Avatar To add or update the avatar for a user, call [`client.users.uploadAvatar(userId:data:name:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC12uploadAvataryXeXeF) with the ID of the user, the data to be uploaded and the name of the file. Optionally you can also pass an progress closure, where upload progress will be reported. In return, you will get an object with links to several representations of an avatar within Box account The supported image extensions are `jpg`, `jpeg` and `png`. The image size cannot exceed 1024 * 1024 pixels or 1MB. ``` let image: UIImage = <YOUR_IMAGE_HERE> // Initialize image here e.g. from UIImagePickerController let data = image.jpegData(compressionQuality: 1)! client.users.uploadAvatar(userId: "33333", data: data, name: "avatar.jpeg") { result in guard case let .success(uploadAvatar) = result else { print("Error uploading user avatar") return } print("User avatar uploaded successfully!") } ``` Alternatively, you can upload the avatar by passing the `InputStream` the method [`client.users.streamUploadAvatar(userId:stream:name:progress:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC18streamUploadAvataryXeXeF). ``` let stream = InputStream(fileAtPath: "PATH_TO_IMAGE_FILE_HERE") client.users.streamUploadAvatar(userId: "33333", stream: data, name: "avatar.jpeg") { result in guard case let .success(uploadAvatar) = result else { print("Error uploading user avatar") return } print("User avatar uploaded successfully!") } ``` Please remember that in both of these methods, the `name` parameter should also contains file extension (.jpg, .jpeg or .png). ## Get User Avatar To retrieve the avatar image for a user, call [`client.users.getAvatar(userId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC9getAvatar6userId10completionySS_ys6ResultOy10Foundation4DataVAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.getAvatar(userId: "33333") { (result: Result<Data, BoxSDKError>) in guard case let .success(avatarData) = result else { print("Error getting user avatar") return } let avatarImage = UIImage(data: avatarData) } ``` ## Delete User Avatar To remove existing user avatar, call [`client.users.deleteAvatar(userId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC12deleteAvatar6userId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.deleteAvatar(userId: "33333") { result in guard case .success = result else { print("Error deleting avatar") return } print("Avatar successfully deleted") } ``` ## Create User As an admin user or service account, create a new user in your enterprise by calling [`client.users.create(login:name:...)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC6create5login4name4role8language13isSyncEnabled8jobTitle5phone7address11spaceAmount13trackingCodes013canSeeManagedC08timezone0J24ExternalCollabRestricted0J22ExemptFromDeviceLimits0J27ExemptFromLoginVerification6status6fields10completionySS_SSAA8UserRoleOSgSSSgSbSgA3Zs5Int64VSgSayAA4UserC12TrackingCodeVGSgA_AZA_A_A_AA10UserStatusOSgSaySSGSgys6ResultOyA4_AA0A8SDKErrorCGctF) with the login email address and name for the user. ``` client.users.create(login: "new.user@example.com", name: "New User") { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error creating user") return } print("Created user \(user.name), with login \(user.login)") } ``` ## Create App User To create an [app user](https://developer.box.com/docs/user-types#section-app-user), call [`client.users.createAppUser(name:...)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC13createAppUser4name8language8jobTitle8timezone5phone7address11spaceAmount6status26isExternalCollabRestricted013canSeeManagedC06fields10completionySS_SSSgA4Qs5Int64VSgAA0G6StatusOSgSbSgAXSaySSGSgys6ResultOyAA0G0CAA0A8SDKErrorCGctF) with the a name for that user. ``` client.users.createAppUser(name: "Doug") { (result: Result<User, BoxSDKError>) in guard case let .success(appUser) = result else { print("Error creating app user") return } print("Created app user with ID \(appUser.id)") } ``` ## Update User To update the information on a user, call [`client.users.updateUser(userId:...)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC6update6userId5login4name4role8language13isSyncEnabled8jobTitle5phone7address11spaceAmount13trackingCodes013canSeeManagedC08timezone0L24ExternalCollabRestricted0L22ExemptFromDeviceLimits0L27ExemptFromLoginVerification6status6fields10completionySS_SSSgAxA8UserRoleOSgAXSbSgA3Xs5Int64VSgSayAA4UserC12TrackingCodeVGSgA0_AXA0_A0_A0_AA10UserStatusOSgSaySSGSgys6ResultOyA5_AA0A8SDKErrorCGctF) with the ID of the user and the properties to update. The result is the updated user object. ``` // Restrict the user from collaborating content externally client.users.update(userId: "33333", isExternalCollabRestricted: true) { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error updating user") return } print("Updated user \(user.name), with login \(user.login)") } ``` ## Change User Login **Note:** In order to change the user's login email, the new email address must first be added as an email alias and the address must be confirmed. To change a user's login email, call [`client.users.changeLogin(userId:login:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC11changeLogin6userId5login6fields10completionySS_SSSaySSGSgys6ResultOyAA4UserCAA0A8SDKErrorCGctF) with the ID of the user and the new login email. ``` client.users.changeLogin(userId: "33333", login: "updated.address@example.com") { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error updating user email") return } print("User \(user.name) (ID: \(user.id)) now has login \(user.login)") } ``` ## Delete User To delete a user, which removes their access to Box, call [`client.users.delete(userId:notify:force:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC6delete6userId6notify5force10completionySS_SbSgAIys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the user. By default, the user will not be deleted if they have any content remaining in their account. To delete the user and any content that is in their account, set the `force` parameter to `true`. ``` client.users.delete(userId: "33333") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error deleting user") return } print("User successfully deleted") } ``` ## Get Enterprise Users To retrieve the users in an enterprise, call [`client.users.listForEnterprise(filterTerm:fields:offset:limit:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC17listForEnterprise10filterTerm6fields9usemarker6marker6offset5limit10completionySSSg_SaySSGSgSbSgALSiSgAPys6ResultOyAA14PagingIteratorCyAA4UserCGAA0A8SDKErrorCGctF). The method returns an iterator object, which is used to get the users. ``` let iterator = client.users.listForEnterprise() iterator.next { result in switch results { case let .success(page): for user in page.entries { print("\(user.name) (ID: \(user.id))") } case let .failure(error): print(error) } } ``` ## Invite User to Enterprise To invite a user who already has a Box account to join an enterprise, call [`client.users.inviteToJoinEnterprise(login:enterpriseId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC22inviteToJoinEnterprise5login12enterpriseId6fields10completionySS_SSSaySSGSgys6ResultOyAA6InviteCAA0A8SDKErrorCGctF) with the login email of the user and the ID of the enterprise. ``` client.users.inviteToJoinEnterprise( login: "user@example.com", enterpriseId: "12345" ) { (result: Result<Invite, BoxSDKError>) in guard case let .success(invite) = result else { print("Error inviting user to enterprise") return } print("Invited user \(invite.actionableBy.name) to \(invite.invitedTo.name)") } ``` ## Move User Content Before deleting a user, it is recommended to move all content they own to another user. This can be done by calling [`client.users.moveItemsOwnedByUser(withID:toUserWithID:notify:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC20moveItemsOwnedByUser6withID02toi4WithK06notify6fields10completionySS_SSSbSgSaySSGSgys6ResultOyAA6FolderCAA0A8SDKErrorCGctF) with the ID of the source and destination users. The result of this method is a new folder created in the destination user's root folder, containing all content previously owned by the source user. ``` client.users.moveItemsOwnedByUser(withID: "33333", toUserWithID: "44444") { (result: Result<Folder, BoxSDKError>) in guard case let .success(folder) = result else { print("Error moving user content") return } print("Folder ID \(folder.id) created with migrated content") } ``` ## Get User Email Aliases To retrieve the list of email aliases associated with a user, call [`client.users.listEmailAliases(userId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC16listEmailAliases6userId10completionySS_ys6ResultOyAA14EntryContainerCyAA0F5AliasCGAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.listEmailAliases(userId: "33333") { (result: Result<EntryContainer<User>, BoxSDKError>) in guard case let .success(aliasCollection) = result else { print("Error retrieving email aliases") return } print("User has \(aliasCollection.totalCount) email aliases:") for alias in aliasCollection.entries { print("- \(alias.email) (\(alias.isConfirmed ? "Confirmed" : "Not Confirmed"))") } } ``` ## Add User Email Alias To associate a new email alias with a user, call [`client.users.createEmailAlias(userId:email:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC23createEmailAliasForUser6userId5email10completionySS_SSys6ResultOyAA0fG0CAA0A5ErrorOGctF) with the ID of the user and the email address to add as an alias. ``` client.users.createEmailAlias( userId: "33333", email: "user+alias@example.com" ) { (result: Result<EmailAlias, BoxSDKError>) in guard case let .success(alias) = result else { print("Error adding email alias") return } print("Added email alias \(alias.email) — user must confirm") } ``` ## Remove User Email Alias To remove a user's email alias, call [`client.users.deleteEmailAlias(userId:emailAliasId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC16deleteEmailAlias6userId05emailgI010completionySS_SSys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the user and the ID of the email alias to remove. ``` client.users.deleteEmailAlias(userId: "33333", emailAliasId: "99999") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing email alias") return } print("Successfully removed email alias") } ``` ## Roll User Out of Enterprise To roll a user out of an enterprise, converting them to a free user, call [`client.users.rollOutOfEnterprise(userId:notify:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/UsersModule.html#/s:6BoxSDK11UsersModuleC19rollOutOfEnterprise6userId6notify6fields10completionySS_SbSgSaySSGSgys6ResultOyAA4UserCAA0A8SDKErrorCGctF) with the ID of the user. ``` client.users.rollOutOfEnterprise(userId: "33333") { (result: Result<User, BoxSDKError>) in guard case let .success(user) = result else { print("Error removing user from enterprise") return } print("User \(user.name) successfully removed from enterprise") } ``` --- ## Untitled *Type: page* Storage Policies Get Storage Policy Info Get Storage Policies Get Storage Policy Assignment Info Get Storage Policy Assignments Create… # Storage Policies - [Get Storage Policy Info](#get-storage-policy-info) - [Get Storage Policies](#get-storage-policies) - [Get Storage Policy Assignment Info](#get-storage-policy-assignment-info) - [Get Storage Policy Assignments](#get-storage-policy-assignments) - [Create Storage Policy Assignment](#create-storage-policy-assignment) - [Assign Storage Policy](#assign-storage-policy) - [Update Storage Policy Assignment](#update-storage-policy-assignment) - [Delete Storage Policy Assignment](#delete-storage-policy-assignment) ## Get Storage Policy Info To retrieve information about a storage policy, call [`client.storagePolicies.get(storagePolicyId: String, fields: [String]?, completion: @escaping Callback<StoragePolicy>)`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC3get15storagePolicyId6fields10completionySS_SaySSGSgys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the storage policy. You can control which fields are returned in the resulting `Storage Policy` object by passing the `fields` parameter. ``` client.storagePolicies.get(storagePolicyId: "22222") { (result: Result<StoragePolicy, BoxSDKError>) in guard case let .success(policy) = result else { print("Error getting storage policy") return } print("Policy ID is \(policy.id)") } ``` ## Get Storage Policies To retrieve the storage policies in an enterprise, call [`client.storagePolicies.listForEnterprise(marker: String?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC17listForEnterprise6marker5limit6fields10completionySSSg_SiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA0C6PolicyCGAA0A8SDKErrorCGctF). This method will return an iterator, which is used to get the policies. ``` let iterator = client.storagePolicies.listForEnterprise() iterator.next { results in switch results { case let .success(page): for policy in page.entries { print("Storage policy \(policy.id)") } case let .failure(error): print(error) } } ``` ## Get Storage Policy Assignment Info To get storage policy assignment, call [`client.storagePolicies.getAssignment(storagePolicyAssignmentId: String, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC13getAssignment013storagePolicyG2Id6fields10completionySS_SaySSGSgys6ResultOyAA0ciG0CAA0A8SDKErrorCGctF) with the id of a storage policy assignment. ``` client.storagePolicy.getAssignment(storagePolicyAssignmentId: "1234") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error getting storage policy assignment") return } print("Storage policy assignment ID \(assignment.id)") } ``` ## Get Storage Policy Assignments To get storage policy assignments for a user or enterprise, call [`client.storagePolicies.listAssignments(resolvedForType: String, resolvedForId: String, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC15listAssignments15resolvedForType0hI2Id6fields10completionySS_SSSaySSGSgys6ResultOyAA0C16PolicyAssignmentCAA0A8SDKErrorCGctF). This always returns a single storage policy assignment. ``` client.storagePolicy.listAssignments(resolvedForType: "user", resolvedForId: "1234") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error getting storage policy assignment") return } print("Storage policy assignment for user \(assignment.assignedTo?.id) is \(assignment.id)") } ``` ## Assign Storage Policy To assign a storage policy, call [`client.storagePolicies.assign(storagePolicyId: String, assignedToType: String, assignedToId, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC6assign15storagePolicyId14assignedToType0jkI06fields10completionySS_S2SSaySSGSgys6ResultOyAA0cH10AssignmentCAA0A8SDKErrorCGctF). ``` client.storagePolicy.assign(storagePolicyId: "1234", assignedToType: "user", assignedToId: "123") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error assigning a storage policy") return } print("Created storage policy assignment ID is \(assignment.id). The ID of the user it is assigned to \(assignment.assignedTo?.id)") } ``` ## Force Assign Storage Policy To assign a storage policy, call [`client.storagePolicies.forceAssign(storagePolicyId: String, assignedToType: String, assignedToId, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC11forceAssign15storagePolicyId14assignedToType0klJ06fields10completionySS_S2SSaySSGSgys6ResultOyAA0cI10AssignmentCAA0A8SDKErrorCGctF). The difference between this call and the createPolicyAssignment() above is that this method will guarantee an update to the assignee's policy. If an assignee already has a policy assigned to it, the createPolicyAssignment() will return a 409 Conflict error. assignPolicy() will instead make an additional updatePolicyAssignment() call to replace the existing policy with the new policy for a policy assignment. ``` client.storagePolicy.forceAssign(storagePolicyId: "1234", assignedToType: "user", assignedToId: "123") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error assigning a storage policy") return } print("Created storage policy assignment ID is \(assignment.id). The ID of the user it is assigned to \(assignment.assignedTo?.id)") } ``` ## Update Storage Policy Assignment To update storage policy assignment, call [`client.storagePolicies.updateAssignment(storagePolicyId: String, assignedToType: String, assignedToId, fields: [String]?, completion: @escaping Callback<StoragePolicyAssignment>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC16updateAssignment013storagePolicyG2Id0hiJ06fields10completionySS_SSSgSaySSGSgys6ResultOyAA0ciG0CAA0A8SDKErrorCGctF). ``` client.storagePolicy.updateAssignment(storagePolicyAssignmentId: "1234", storagePolicyId: "123") { (result: Result<StoragePolicyAssignment, BoxSDKError>) in guard case let .success(assignment) = result else { print("Error updating a storage policy assignment") return } print("Updated storage policy assignment \(assignment.id)") } ``` ## Delete Storage Policy Assignment To delete a storage policy assignment, call [`client.folders.deleteAssignment(storagePolicyAssignmentId: String, completion: @escaping Callback<Void>`](https://opensource.box.com/box-ios-sdk/Classes/StoragePoliciesModule.html#/s:6BoxSDK21StoragePoliciesModuleC16deleteAssignment013storagePolicyG2Id10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the storage policy to delete. ``` client.storagePolicies.deleteAssignment(storagePolicyAssignmentId: "22222") { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting storage policy assignment") return } print("Storage policy assignment is successfully deleted.") } ``` --- ## Untitled *Type: page* Webhooks Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your… # Webhooks Webhooks enable you to attach event triggers to Box files and folders. Event triggers monitor events on Box objects and notify your application when they occur. A webhook notifies your application by sending HTTP requests to a URL of your choosing. A webhook object contains information about a webhook like the triggers, the URL, etc. - [Get Webhooks](#get-webhooks) - [Get Webhook Info](#get-webhook-info) - [Create Webhook](#create-webhook) - [Update Webhook](#update-webhook) - [Delete Webhook](#delete-webhook) ## Get Webhook Info To retrieve information about a webhook, call [`client.webhooks.get(webhookId: String, fields: [String]?, completion: @escaping Callback<Webhook>)`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC3get9webhookId6fields10completionySS_SaySSGSgys6ResultOyAA7WebhookCAA0A8SDKErrorCGctF) with the ID of the webhook. You can control which fields are returned in the resulting `Webhook` object by passing the `fields` parameter. ``` client.folders.get(webhookId: "22222", fields: ["id", "created_at"]) { (result: Result<Webhook, BoxSDKError>) in guard case let .success(webhook) = result else { print("Error getting webhook information") return } print("Webhook \(webhook.id) was created at \(webhook.createdAt)") } ``` ## List Webhooks To retrieve information about webhooks in an enterprise, call [`client.webhook.list(webhookId: String, marker: String?, limit: Int?, fields: [String]?)`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC4list6marker5limit6fields10completionySSSg_SiSgSaySSGSgys6ResultOyAA14PagingIteratorCyAA7WebhookCGAA0A8SDKErrorCGctF). This method will return an iterator object, which is used to get the webhooks. ``` let iterator = client.webhooks.list() iterator.next { results in switch results { case let .success(page): for webhook in page.entries { print("Webhook \(webhook.id) was created at \(webhook.createdAt)") } case let .failure(error): print(error) } } ``` ## Create Webhook To create a new webhook, call [`client.webhooks.create(targetType: String, targetId: String, triggers: [Webhook.EventTriggers], address: String, fields: [String]?, completion: @escaping Callback<Webhook>`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC6create10targetType0F2Id8triggers7address6fields10completionySS_SSSayAA7WebhookC13EventTriggersOGSSSaySSGSgys6ResultOyAlA0A8SDKErrorCGctF) ``` client.webhooks.create(targetType: "file", targetId: "1234", triggers: [.fileDownloaded], address: "www.testurl.com") { (result: Result<Webhook, BoxSDKError>) in guard case let .success(webhook) = result else { print("Error creating webhook") return } print("Created webhook \"\(webhook.id)\"") } ``` ## Update Webhook To update a webhook, call [`client.webhooks.update(webhookId: String, targetType: String?, targetId: String?, triggers: [Webhook.EventTriggers]?, address: String?, fields: [String]?, completion: @escaping Callback<Webhook>`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC6update9webhookId10targetType0hG08triggers7address6fields10completionySS_SSSgALSayAA7WebhookC13EventTriggersOGSgALSaySSGSgys6ResultOyAnA0A8SDKErrorCGctF) ``` client.webhooks.update(webhookId: "1234", targetType: "file", targetId: "1234", address: "www.testurl.com") { (result: Result<Webhook, BoxSDKError>) in guard case let .success(webhook) = result else { print("Error updating webhook") return } print("Updated webhook address to \"\(webhook.address)\"") } ``` ## Delete Webhook To delete a webhook, call [`client.webhooks.delete(webhookId: String, completion: @escaping Callback<Void>`](https://opensource.box.com/box-ios-sdk/Classes/WebhooksModule.html#/s:6BoxSDK14WebhooksModuleC6delete9webhookId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) ``` client.webhooks.delete(webhookId: "22222") { result: Result<Void, BoxSDKError>} in guard case .success = result else { print("Error deleting webhook") return } print("Webhook successfully deleted") } ``` --- ## Untitled *Type: page* Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link… # Web Links Web links are objects that point to URLs. These objects are also known as bookmarks within the Box web application. Web link objects are treated similarly to file objects. - [Create Web Link](#create-web-link) - [Get Web Link](#get-web-link) - [Update Web Link](#update-web-link) - [Delete Web Link](#delete-web-link) - [Set Shared Link](#set-shared-link) - [Remove Shared Link](#remove-shared-link) ## Create Web Link To create a web link with a specified name and description, call [`client.webLinks.create(url:parentId:name:description:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC6create3url8parentId4name11description6fields10completionySS_S2SSgAKSaySSGSgys6ResultOyAA0C4LinkCAA0A8SDKErrorCGctF). ``` client.webLinks.create( url: "https://www.example.com", parentId: "22222", name: "Link to Example", description: "This goes to an example page" ) { (result: Result<WebLink, BoxSDKError>) in guard case let .success(webLink) = result else { print("Error creating web link") return } print("WebLink \(webLink.name) was created at \(webLink.createdAt)") } ``` ## Get Web Link To retrieve information about a web link, call [`client.webLinks.get(webLinkId:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC3get9webLinkId6fields10completionySS_SaySSGSgys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of web link. You can control which fields are returned in the resulting `WebLink` object by passing the `fields` parameter. ``` client.webLinks.get(webLinkId: "11111", fields: ["name", "created_at"]) { (result: Result<WebLink, BoxSDKError>) in guard case let .success(webLink) = result else { print("Error retrieving web link information") return } print("WebLink \(webLink.name) was created at \(webLink.createdAt)") } ``` ## Update Web Link To update a web link record, call [`client.webLinks.update(webLinkId:url:parentId:name:description:sharedLink:fields:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC6update9webLinkId3url06parentI04name11description06sharedH06fields10completionySS_SSSgA3mA17NullableParameterOyAA06SharedH4DataVGSgSaySSGSgys6ResultOyAA0cH0CAA0A8SDKErrorCGctF) with the ID of the web link to update and the properties to update. ``` client.webLinks.update(webLinkId: "11111", name: "new name for weblink") { (result: Result<WebLink, BoxSDKError>) in guard case let .success(webLink) = result else { print("Error updating web link information") return } print("WebLink \(webLink.name) was updated successfully") } ``` ## Delete Web Link To delete a web link, call [`client.webLinks.delete(webLinkId:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC6delete9webLinkId10completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the web link to delete. ``` client.webLinks.delete(webLinkId: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing web link") return } print("WebLink removed") } ``` ## Set Shared Link To add or update the shared link for a web link, call [`client.webLinks.setSharedLink(forWebLink:access:unsharedAt:vanityName:password:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC13setSharedLink03forcH06access10unsharedAt10vanityName8password10completionySS_AA0gH6AccessOSgAA17NullableParameterOy10Foundation4DateVGSgAOySSGSgAVys6ResultOyAA0gH0CAA0A8SDKErrorCGctF) with the ID of the web link and the shared link properties to set. ``` client.webLinks.setSharedLink(forWebLink: "11111", access: .open) { (result: Result<SharedLink, BoxSDKError>) in guard case let .success(sharedLink) = result else { print("Error setting weblink shared link") return } print("WebLink shared link URL is \(sharedLink.url), with \(sharedLink.access) access") } ``` ## Remove Shared Link To remove a webLink's shared link, call [`client.webLinks.deleteSharedLink(forWebLink:completion:)`](https://opensource.box.com/box-ios-sdk/Classes/WebLinksModule.html#/s:6BoxSDK14WebLinksModuleC16deleteSharedLink03forcH010completionySS_ys6ResultOyytAA0A8SDKErrorCGctF) with the ID of the file. ``` client.webLinks.deleteSharedLink(forWebLink: "11111") { (result: Result<Void, BoxSDKError>) in guard case .success = result else { print("Error removing weblink shared link") return } print("WebLink shared link removed") } ``` --- ## Untitled *Type: page* Box cURL samples Authorize a user Authorize a user by sending them through the Box website and request their permission to act on their… # Box cURL samples ## Authorize a user Authorize a user by sending them through the [Box](https://box.com) website and request their permission to act on their behalf. This is the first step when authenticating a user using OAuth 2.0. To request a user's authorization to use the Box APIs on their behalf you will need to send a user to the URL with this format. ``` curl -i -X GET "https://account.box.com/api/oauth2/authorize?response_type=code&client_id=ly1nj6n11vionaie65emwzk575hnnmrk&redirect_uri=http://example.com/auth/callback" ``` ## Request an access token Request an Access Token using either a client-side obtained OAuth2 authorization code or a server-side JWT assertion. An Access Token is a string that enables Box to verify that a request belongs to an authorized session. In the normal order of operations you will begin by requesting authentication from the [authorize](#get-authorize) endpoint and Box will send you an authorization code. You will then send this code to this endpoint to exchange it for an Access Token. The returned Access Token can then be used to to make Box API calls. ``` curl -i -X POST "https://api.box.com/oauth2/token" \ -H "content-type: application/x-www-form-urlencoded" \ -d "client_id=[CLIENT_ID]" \ -d "client_secret=[CLIENT_SECRET]" \ -d "code=[CODE]" \ -d "grant_type=authorization_code" ``` ## Refresh an access token ``` curl -i -X POST "https://api.box.com/oauth2/token" \ -H "content-type: application/x-www-form-urlencoded" \ -d "client_id=[CLIENT_ID]" \ -d "client_secret=[CLIENT_SECRET]" \ -d "refresh_token=[REFRESH_TOKEN]" \ -d "grant_type=refresh_token" ``` ## Downscope a token ``` curl -i -X POST "https://api.box.com/oauth2/token" \ -H "content-type: application/x-www-form-urlencoded" \ -d "subject_token=[ACCESS_TOKEN]" \ -d "subject_token_type=urn:ietf:params:oauth:token-type:access_token" \ -d "scope=item_upload item_preview base_explorer" \ -d "resource=https://api.box.com/2.0/folders/123456" \ -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" ``` ## Revoke an access token Revoke an active Access Token, effectively logging a user out that has been previously authenticated. ``` curl -i -X POST "https://api.box.com/oauth2/revoke" \ -H "content-type: application/x-www-form-urlencoded" \ -d "client_id=[CLIENT_ID]" \ -d "client_secret=[CLIENT_SECRET]" \ -d "token=[ACCESS_TOKEN]" ``` ## Authentication with Client Credentials Creates a token using Client Credentials Grant, which allows you to log in as a Service Account. ``` curl -i -X POST "https://api.box.com/oauth2/token" \ -H "content-type: application/x-www-form-urlencoded" \ -d "client_id=[CLIENT_ID]" \ -d "client_secret=[CLIENT_SECRET]" \ -d "grant_type=client_credentials" \ -d "box_subject_type=enterprise" \ -d "box_subject_id=[ENTERPRISE_ID]" ``` ## Authentication with CCG as an admin or managed user Creates a token using Client Credentials Grant, which allows you to log in as an admin or a managed user. ``` curl -i -X POST "https://api.box.com/oauth2/token" \ -H "content-type: application/x-www-form-urlencoded" \ -d "client_id=[CLIENT_ID]" \ -d "client_secret=[CLIENT_SECRET]" \ -d "grant_type=client_credentials" \ -d "box_subject_type=user" \ -d "box_subject_id=[USER_ID]" ``` ## Authentication with CCG as app user Creates a token using Client Credentials Grant, which allows you to log in as any app user. ``` curl -i -X POST "https://api.box.com/oauth2/token" \ -H "content-type: application/x-www-form-urlencoded" \ -d "client_id=[CLIENT_ID]" \ -d "client_secret=[CLIENT_SECRET]" \ -d "grant_type=client_credentials" \ -d "box_subject_type=user" \ -d "box_subject_id=[APPUSER_ID]" ``` ## Send request to AI ``` curl -i -L POST "https://api.box.com/2.0/ai/ask" \ -H "content-type: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "mode": "single_item_qa", "prompt": "What is the value provided by public APIs based on this document?", "items": [ { "type": "file", "id": "9842787262" } ], "dialogue_history": [ { "prompt": "Make my email about public APIs sound more professional", "answer": "Here is the first draft of your professional email about public APIs", "created_at": "2013-12-12T10:53:43-08:00" } ], "include_citations": true, "ai_agent": { "type": "ai_agent_ask", "long_text": { "model": "azure__openai__gpt_4o_mini", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", }, "basic_text": { "model": "azure__openai__gpt_4o_mini", } } }' ``` ## Send request to AI (extended) ``` curl -i -L POST "https://api.box.com/2.0/ai/ask" \ -H "content-type: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "mode": "single_item_qa", "prompt": "What is the value provided by public APIs based on this document?", "items": [ { "type": "file", "id": "9842787262" } ], "dialogue_history": [ { "prompt": "Make my email about public APIs sound more professional", "answer": "Here is the first draft of your professional email about public APIs", "created_at": "2013-12-12T10:53:43-08:00" } ], "include_citations": true, "ai_agent": { "type": "ai_agent_ask", "long_text": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 0.0, "top_p": 1.0, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" }, "embeddings": { "model": "openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 8400 } } }, "basic_text": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 0.0, "top_p": 1.0, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" } }, "long_text_multi": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 0.0, "top_p": 1.0, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" }, "embeddings": { "model": "openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 8400 } } }, "basic_text_multi": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 0.0, "top_p": 1.0, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" } } }' ``` ## Send text generation request to AI ``` curl -i -L POST "https://api.box.com/2.0/ai/text_gen" \ -H "content-type: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "prompt": "Write a social media post about protein powder.", "items": [ { "id": "12345678", "type": "file", "content": "More information about protein powders" }, ], "dialogue_history": [ { "prompt": "Can you add some more information?", "answer": "Public API schemas provide necessary information to integrate with APIs...", "created_at": "2013-12-12T11:20:43-08:00" } ], "ai_agent": { "type": "ai_agent_text_gen", "basic_gen": { "model": "azure__openai__gpt_4o_mini" } } }' ``` ## Send text generation request to AI (extended) ``` curl -i -L POST "https://api.box.com/2.0/ai/text_gen" \ -H "content-type: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "prompt": "Write a social media post about protein powder.", "items": [ { "id": "12345678", "type": "file", "content": "More information about protein powders" }, ], "dialogue_history": [ { "prompt": "Make my email about public APIs sound more professional", "answer": "Here is the first draft of your professional email about public APIs", "created_at": "2013-12-12T10:53:43-08:00" }, { "prompt": "Can you add some more information?", "answer": "Public API schemas provide necessary information to integrate with APIs...", "created_at": "2013-12-12T11:20:43-08:00" } ], "ai_agent": { "type": "ai_agent_text_gen", "basic_gen": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 2.0, "top_p": 1.0, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" }, "embeddings": { "model": " openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } }, "content_template": "---{content}---" } } }' ``` ## Get default agent config ``` curl -L GET "https://api.box.com/2.0/ai_agent_default?mode=text_gen" \ -H 'Authorization: Bearer <ACCESS_TOKEN>' ``` ## Create agents Creates custom AI agents. ``` curl -L POST "https://api.box.com/2.0/ai-agents" \ -H 'Authorization: Bearer <ACCESS_TOKEN>' -d '{ type: type: string description: The type of agent used to handle queries. enum: - ai_agent example: ai_agent name: type: string description: The name of the AI Agent. example: 'My AI Agent' access_state: $ref: ../schemas/ai_agent_access_state.yml icon_reference: type: string minLength: 1 description: |- The icon reference of the AI Agent. It should have format of the URL https://cdn01.boxcdn.net/app-assets/aistudio/avatars/<file_name> where possible values of file_name are: `logo_boxAi.png`,`logo_stamp.png`,`logo_legal.png`,`logo_finance.png`,`logo_config.png`,`logo_handshake.png`,`logo_analytics.png`,`logo_classification.png example: 'https://cdn01.boxcdn.net/app-assets/aistudio/avatars/logo_analytics.svg' allowed_entities: type: array }, - d '{ items: $ref: '#/components/schemas/AiAgentAllowedEntity' description: List of allowed users or groups. ask: $ref: '#/components/schemas/AiStudioAgentAsk' text_gen: $ref: '#/components/schemas/AiStudioAgentTextGen' extract: $ref: '#/components/schemas/AiStudioAgentExtract' } ``` ## Delete AI agent ``` curl -L DELETE "https://api.box.com/2.0/ai_agents/12345" \ -H 'Authorization: Bearer <ACCESS_TOKEN>' ``` ## Get AI agent by ID ``` curl -i -X GET "https://api.box.com/2.0/ai_agents/1234567890" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get AI agents ``` curl -i -X GET "https://api.box.com/2.0/ai_agents" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update AI agents ``` curl -i -X PUT "https://api.box.com/2.0/ai_agents/1234567890" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Extract structured metadata ``` curl -i -L 'https://api.box.com/2.0/ai/extract_structured' \ -H 'content-type: application/json' \ -H 'authorization: Bearer <ACCESS_TOKEN>' \ -d '{ "items": [ { "id": "12345678", "type": "file", "content": "This is file content." } ], "metadata_template": { "template_key": "", "type": "metadata_template", "scope": "" }, "fields": [ { "key": "name", "description": "The name of the person.", "displayName": "Name", "prompt": "The name is the first and last name from the email address.", "type": "string", "options": [ { "key": "First Name" }, { "key": "Last Name" } ] } ], "ai_agent": { "type": "ai_agent_extract_structured", "long_text": { "model": "azure__openai__gpt_4o_mini" }, "basic_text": { "model": "azure__openai__gpt_4o_mini" } } }' ``` ## Extract structured metadata (extended) ``` curl -i -L 'https://api.box.com/2.0/ai/extract_structured' \ -H 'content-type: application/json' \ -H 'authorization: Bearer <ACCESS_TOKEN>' \ -d '{ "items": [ { "id": "12345678", "type": "file", "content": "This is file content." } ], "metadata_template": { "template_key": "", "type": "metadata_template", "scope": "" }, "fields": [ { "key": "name", "description": "The name of the person.", "displayName": "Name", "prompt": "The name is the first and last name from the email address.", "type": "string", "options": [ { "key": "First Name" }, { "key": "Last Name" } ] } ], "ai_agent": { "type": "ai_agent_extract_structured", "long_text": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 0, "top_p": 1, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" }, "embeddings": { "model": "openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } } }, "basic_text": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 0, "top_p": 1, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" } } } }' ``` ## Extract metadata ``` curl -i -L 'https://api.box.com/2.0/ai/extract' \ -H 'content-type: application/json' \ -H 'authorization: Bearer <ACCESS_TOKEN>' \ -d '{ "prompt": "Extract data related to contract conditions", "items": [ { "type": "file", "id": "1497741268097" } ], "ai_agent": { "type": "ai_agent_extract", "long_text": { "model": "azure__openai__gpt_4o_mini", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", }, "basic_text": { "model": "azure__openai__gpt_4o_mini", } } }' ``` ## Extract metadata (extended) ``` curl -i -L 'https://api.box.com/2.0/ai/extract' \ -H 'content-type: application/json' \ -H 'authorization: Bearer <ACCESS_TOKEN>' \ -d '{ "prompt": "Extract data related to contract conditions", "items": [ { "type": "file", "id": "1497741268097" } ], "ai_agent": { "type": "ai_agent_extract", "long_text": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 0, "top_p": 1, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" }, "embeddings": { "model": "openai__text_embedding_ada_002", "strategy": { "id": "basic", "num_tokens_per_chunk": 64 } } }, "basic_text": { "model": "azure__openai__gpt_4o_mini", "system_message": "You are a helpful travel assistant specialized in budget travel", "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?", "num_tokens_for_completion": 8400, "llm_endpoint_params": { "type": "openai_params", "temperature": 0, "top_p": 1, "frequency_penalty": 1.5, "presence_penalty": 1.5, "stop": "<|im_end|>" } } } }' ``` ## Add a Doc Gen template ``` curl -L 'https://api.box.com/2.0/docgen_templates' \ -H 'box-version: 2025.0' \ -H 'Authorization: Bearer <ACCESS_TOKEN>' \ -H 'Content-Type: application/json' \ -D '{ "file": { "id": "12345678", "type": "file" } }' ``` ## Delete association between Doc Gen template and file ``` curl -L -X DELETE 'https://api.box.com/2.0/docgen_templates/12345678' \ -H 'box-version: 2025.0' \ -H 'Authorization: Bearer <ACCESS_TOKEN>' ``` ## Get all Doc Gen templates ``` curl -L 'https://api.box.com/2.0/docgen_templates' \ -H 'box-version: 2025.0' \ -H 'Authorization: Bearer <ACCESS_TOKEN>' ``` ## Get Doc Gen template by ID ``` curl -L 'https://api.box.com/2.0/docgen_templates/12345678' \ -H 'box-version: 2025.0' \ -H 'Authorization: Bearer <ACCESS_TOKEN>' ``` ## Get Doc Gen jobs for a template ``` curl -L 'https://api.box.com/2.0/docgen_template_jobs/12345678' \ -H 'box-version: 2025.0' \ -H 'Authorization: Bearer <ACCESS_TOKEN>' ``` ## Get Doc Gen template tags for template ``` curl -L 'https://api.box.com/2.0/docgen_templates/12345678/tags' \ -H 'box-version: 2025.0' \ -H 'Authorization: Bearer <ACCESS_TOKEN>' ``` ## Generate a document with Doc Gen ``` curl -L 'https://api.box.com/2.0/docgen_batches' \ -H 'box-version: 2025.0' \ -H 'Authorization: Bearer <ACCESS_TOKEN>' \ -D '{ "file": { "id": "12345678", "type": "file" }, "input_source": "api", "destination_folder": { "id": "12345678", "type": "folder" }, "output_type": "docx", "document_generation_data": [ { "generated_file_name": "Image test", "user_input": { "order": { "id": "12305", "date": "18-08-2023", "country": "US", "expiryDate": "18-08-2024", "currency": "$", "amount": 5060.5, "taxRate": 10, "requester": "John", "approver": "Smith", "department": "Procurement", "paymentTerms": "30 days", "deliveryTerms": "30 days", "deliveryDate": "18-09-2023", "vendor": { "company": "Example company", "address": { "street": "Example street", "city": "Example city", "zip": "EX-456" } }, "products": [ { "id": 1, "name": "A4 Papers", "type": "non-fragile", "quantity": 100, "price": 29, "amount": 2900 }, { "id": 2, "name": "Ink Cartridge", "type": "non-fragile", "quantity": 40, "price": 39, "amount": 1560 }, { "id": 3, "name": "Adhesive tape", "type": "non-fragile", "quantity": 20, "price": 30, "amount": 600.5 } ] } } } ]` ``` ## Get all Doc Gen jobs ``` curl -i -X GET "https://api.box.com/2.0/docgen_jobs" \ -H 'box-version: 2025.0' \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get Doc Gen job by ID ``` curl -i -X GET "https://api.box.com/2.0/docgen_jobs/12345" \ -H 'box-version: 2025.0' \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get Doc Gen job for a specific batch ``` curl -i -X GET "https://api.box.com/2.0/docgen_batch_jobs/12345" \ -H 'box-version: 2025.0' \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get a file Retrieves the details about a file. ``` curl -i -X GET "https://api.box.com/2.0/files/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Restore file Restores an file that has been moved to the trash. ``` curl -i -X POST "https://api.box.com/2.0/files/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update a file Updates a file. This can be used to rename or move a file, create a shared link, or lock a file. ``` curl -i -X PUT "https://api.box.com/2.0/files/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "New name" }' ``` ## Delete a file Deletes a file, either permanently or by moving it to the trash. The the enterprise settings determine whether the item will be permanently deleted from Box or moved to the trash. ``` curl -i -X DELETE "https://api.box.com/2.0/files/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Download a file Returns the contents of a file in binary format. ``` curl -i -L -X GET "https://api.box.com/2.0/files/12345/content" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ ``` ## Download a file version ``` curl -i -L -X GET "https://api.box.com/2.0/files/12345/content?version=4" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ ``` ## Get download URL ``` curl -i -X GET "https://api.box.com/2.0/files/12345/content?version=4" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Download a shared link Returns the contents of a file in binary format. ``` curl -i -L -X GET "https://api.box.com/2.0/files/12345/content" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "boxapi: shared_link=https://cloud.box.com/shared/static/gjasdasjhasd&shared_link_password=letmein" \ ``` ## Upload a file version Update a file's content. For file sizes over 50MB we recommend using the Chunk Upload APIs. ``` curl -i -X POST "https://upload.box.com/api/2.0/files/12345/content" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: multipart/form-data" \ -F attributes='{"name":"Contract.pdf", "parent":{"id":"11446498"}}' \ -F file=@<FILE_NAME> ``` ## Preflight check Performs a check to verify that a file will be accepted by Box before you upload the entire file. ``` curl -i -X OPTIONS "https://api.box.com/2.0/files/content" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{"name":"Contract.pdf", "parent":{"id":"11446498"}}' ``` ``` curl -i -X OPTIONS "https://api.box.com/2.0/files/12345/content" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{"name":"Contract.pdf", "parent":{"id":"11446498"}}' ``` ## Upload a file Uploads a small file to Box. For file sizes over 50MB we recommend using the Chunk Upload APIs. ``` curl -i -X POST "https://upload.box.com/api/2.0/files/content" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: multipart/form-data" \ -F attributes='{"name":"Contract.pdf", "parent":{"id":"11446498"}}' \ -F file=@<FILE_NAME> ``` ## Create upload session Creates an upload session for a new file. ``` curl -i -X POST "https://upload.box.com/api/2.0/files/upload_sessions" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "folder_id": "0", "file_size": 104857600, "file_name": "Contract.pdf" }' ``` ## Create upload session for existing file Creates an upload session for an existing file. ``` curl -i -X POST "https://upload.box.com/api/2.0/files/12345/upload_sessions" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "file_size": 104857600 }' ``` ## Get upload session Return information about an upload session. ``` curl -i -X GET "https://upload.box.com/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Upload a part Updates a chunk of an upload session for a file. ``` curl -i -X PUT "https://upload.box.com/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "digest: sha=fpRyg5eVQletdZqEKaFlqwBXJzM=" \ -H "content-range: bytes 8388608-16777215/445856194" \ -H "content-type: application/octet-stream" \ --data-binary @<FILE_NAME> ``` ## Abort upload session Abort an upload session and discard all data uploaded. This cannot be reversed. ``` curl -i -X DELETE "https://upload.box.com/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List parts Return a list of the chunks uploaded to the upload session so far. ``` curl -i -X GET "https://upload.box.com/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/parts" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Commit upload session Close an upload session and create a file from the uploaded chunks. ``` curl -i -X POST "https://upload.box.com/2.0/files/upload_sessions/F971964745A5CD0C001BBE4E58196BFD/commit" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "digest: sha=fpRyg5eVQletdZqEKaFlqwBXJzM=" \ -H "content-type: application/json" \ -d '{ "parts": [ { "part_id": "BFDF5379", "offset": 0, "size": 8388608, "sha1": "134b65991ed521fcfe4724b7d814ab8ded5185dc" }, { "part_id": "E8A3ED8E", "offset": 8388608, "size": 1611392, "sha1": "234b65934ed521fcfe3424b7d814ab8ded5185dc" } ], "attributes": { "content_modified_at": "2017-04-08T00:58:08Z" } }' ``` ## Copy a file Creates a copy of a file. ``` curl -i -X POST "https://api.box.com/2.0/files/12345/copy" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "parent": { "id": "123" } }' ``` ## Get a file thumbnail Retrieves a thumbnail, or smaller image representation, of a file. Sizes of `32x32`,`64x64`, `128x128`, and `256x256` can be returned in the `.png` format and sizes of `32x32`, `94x94`, `160x160`, and `320x320` can be returned in the `.jpg` format. Thumbnails can be generated for the image and video file formats listed [found on our community site]([http://community.box.com/t5/Managing-](http://community.box.com/t5/Managing-) Your-Content/What-file-types-are-supported-by-Box-s-Content-Preview/ ta-p/327). ``` curl -i -X GET "https://api.box.com/2.0/files/12345/thumbnail.png" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get file collaborations Retrieves a list of collaborations for a file. This returns all the users that have access to the file. ``` curl -i -X GET "https://api.box.com/2.0/files/12345/collaborations" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List a file's comments Retrieves a list of comments for a file. ``` curl -i -X GET "https://api.box.com/2.0/files/12345/comments" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get file tasks Retrieves a list of all the tasks for a file. This endpoint does not support paging. ``` curl -i -X GET "https://api.box.com/2.0/files/12345/tasks" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get trashed file Retrieves a file that has been moved to the trash. ``` curl -i -X GET "https://api.box.com/2.0/files/12345/trash" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Permanently delete file Permanently deletes a file that is in the trash. This action cannot be undone. ``` curl -i -X DELETE "https://api.box.com/2.0/files/12345/trash" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List all file versions Retrieve information on all version of a file. This endpoint can be used to retrieve information about older versions of a file. Versions are only tracked for Box users with premium accounts. ``` curl -i -X GET "https://api.box.com/2.0/files/12345/versions" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get a file version Retrieve a specific older version of a file. Versions are only tracked for Box users with premium accounts. ``` curl -i -X GET "https://api.box.com/2.0/files/12345/versions/456456" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Delete file version Move a file version to the trash. Versions are only tracked for Box users with premium accounts. ``` curl -i -X DELETE "https://api.box.com/2.0/files/12345/versions/456456" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Promote file version Promote a specific version of a file. If previous versions exist, this method can be used to promote one of the older versions to the top of the version history. This actually creates a new copy of the old version and puts it at the top of the versions history. The file will have the exact same contents as the older version, with the the same SHA1/etag, and the same name as the original. Other properties such as comments do not get updated to their former values. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. ``` curl -i -X POST "https://api.box.com/2.0/files/12345/versions/current" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "type": "file_version", "id": "456456" }' ``` ## Restore file version Restores a specific version of a file after it was deleted. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. ``` curl -i -X POST "https://api.box.com/2.0/files/12345/versions/456456" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "trashed_at": null }' ``` ## List file's metadata Retrieves all metadata for a given file. ``` curl -i -X GET "https://api.box.com/2.0/files/12345/metadata" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get specific file metadata Retrieve a specific metadata template instance for a file ``` curl -i -X GET "https://api.box.com/2.0/files/12345/metadata/enterprise_27335/blueprintTemplate" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create metadata on file Creates a piece of metadata on a file based on the specified template. Only values that are present in the metadata template will be accepted. ``` curl -i -X POST "https://api.box.com/2.0/files/12345/metadata/enterprise_27335/blueprintTemplate" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "audience": "internal", "documentType": "Q1 plans", "competitiveDocument": "no", "status": "active", "author": "Jones", "currentState": "proposal" }' ``` ## Update file metadata Updates a piece of metadata on a file. The metadata instance can only be updated if the instance already exists. When editing metadata, only values that adhere to the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance remains unchanged. ``` curl -i -X PUT "https://api.box.com/2.0/files/12345/metadata/enterprise_27335/blueprintTemplate" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[ { "op": "test", "path": "/competitiveDocument", "value": "no" }, { "op": "remove", "path": "/competitiveDocument" }, { "op": "test", "path": "/status", "value": "active" }, { "op": "replace", "path": "/status", "value": "inactive" }, { "op": "test", "path": "/author", "value": "Jones" }, { "op": "copy", "from": "/author", "path": "/editor" }, { "op": "test", "path": "/currentState", "value": "proposal" }, { "op": "move", "from": "/currentState", "path": "/previousState" }, { "op": "add", "path": "/currentState", "value": "reviewed" } ]' ``` ## Delete file metadata Deletes a piece of file metadata. ``` curl -i -X DELETE "https://api.box.com/2.0/files/12345/metadata/enterprise_27335/blueprintTemplate" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get file watermark Retrieve the watermark for a file. ``` curl -i -X GET "https://api.box.com/2.0/files/12345/watermark" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Apply watermark to file Applies or update a watermark on a file. ``` curl -i -X PUT "https://api.box.com/2.0/files/12345/watermark" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "watermark": { "imprint": "default" } }' ``` ## Remove file watermark Removes the watermark from a file. ``` curl -i -X DELETE "https://api.box.com/2.0/files/12345/watermark" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get a folder Retrieves details for a folder, including the first 100 entries in the folder. To fetch more items within the folder, please use the [Get items in a folder](#get-folders-id-items) endpoint. ``` curl -i -X GET "https://api.box.com/2.0/folders/4353455" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Restore folder Restores a folder that has been moved to the trash. ``` curl -i -X POST "https://api.box.com/2.0/folders/4353455" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update a folder Updates a folder. This can be also be used to move the folder, create shared links, update collaborations, and more. ``` curl -i -X PUT "https://api.box.com/2.0/folders/4353455" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "New folder name" }' ``` ## Move a folder ``` curl -i -X PUT "https://api.box.com/2.0/folders/4353455" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "New folder name", "parent": { "id": "123" } }' ``` ## Move a subfolder to a private folder ``` curl -i -X PUT "https://api.box.com/2.0/folders/4353455" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "New folder name", "parent": { "id": "123" } "owned_by": { "id": "123456" } }' ``` ## Rename a folder ``` curl -i -X PUT "https://api.box.com/2.0/folders/4353455" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "New folder name" }' ``` ## Change folder owner ``` curl -i -X PUT "https://api.box.com/2.0/folders/4353455" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "owned_by": { "id": "123" } }' ``` ## Delete a folder Deletes a folder, either permanently or by moving it to the trash. ``` curl -i -X DELETE "https://api.box.com/2.0/folders/4353455" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get items in folder Retrieves a page of items in a folder. These items can be files, folders, and web links. To request more information about the folder itself, like its size, please use the [Get a folder](#get-folders-id) endpoint instead. ``` curl -i -X GET "https://api.box.com/2.0/folders/0/items" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create a folder Creates a new empty folder within the specified parent folder. ``` curl -i -X POST "https://api.box.com/2.0/folders" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "New Folder", "parent": { "id": "0" } }' ``` ## Copy a folder Creates a copy of a folder within a destination folder. The original folder will not be changed. ``` curl -i -X POST "https://api.box.com/2.0/folders/4353455/copy" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "parent": { "id": "345345" } }' ``` ## Get folder collaborations Retrieves a list of collaborations for a folder. This returns all the users that have access to the folder. ``` curl -i -X GET "https://api.box.com/2.0/folders/4353455/collaborations" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get trashed folder Retrieves a folder that has been moved to the trash. ``` curl -i -X GET "https://api.box.com/2.0/folders/4353455/trash" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Permanently delete folder Permanently deletes a folder that is in the trash. This action cannot be undone. ``` curl -i -X DELETE "https://api.box.com/2.0/folders/4353455/trash" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List folder's metadata Retrieves all metadata for a given folder. ``` curl -i -X GET "https://api.box.com/2.0/folders/4353455/metadata" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get specific folder metadata Retrieve a specific metadata template instance for a folder ``` curl -i -X GET "https://api.box.com/2.0/folders/4353455/metadata/enterprise_27335/blueprintTemplate" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create metadata on folder Creates a piece of metadata on a folder based on the specified template. Only values that are present in the metadata template will be accepted. ``` curl -i -X POST "https://api.box.com/2.0/folders/4353455/metadata/enterprise_27335/blueprintTemplate" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "audience": "internal", "documentType": "Q1 plans", "competitiveDocument": "no", "status": "active", "author": "Jones", "currentState": "proposal" }' ``` ## Update folder metadata Updates a piece of metadata on a folder based. The metadata instance can only be updated if the instance already exists. When editing metadata, only values that adhere to the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance remains unchanged. ``` curl -i -X PUT "https://api.box.com/2.0/folders/4353455/metadata/enterprise_27335/blueprintTemplate" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[ { "op": "test", "path": "/competitiveDocument", "value": "no" }, { "op": "remove", "path": "/competitiveDocument" }, { "op": "test", "path": "/status", "value": "active" }, { "op": "replace", "path": "/status", "value": "inactive" }, { "op": "test", "path": "/author", "value": "Jones" }, { "op": "copy", "from": "/author", "path": "/editor" }, { "op": "test", "path": "/currentState", "value": "proposal" }, { "op": "move", "from": "/currentState", "path": "/previousState" }, { "op": "add", "path": "/currentState", "value": "reviewed" } ]' ``` ## Delete folder metadata Deletes a piece of folder metadata. ``` curl -i -X DELETE "https://api.box.com/2.0/folders/4353455/metadata/enterprise_27335/blueprintTemplate" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute in the full files or folders objects can be passed in with the `fields` parameter to retrieve those specific attributes that are not returned by default. ``` curl -i -X GET "https://api.box.com/2.0/folders/trash/items" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get folder watermark Retrieve the watermark for a folder. ``` curl -i -X GET "https://api.box.com/2.0/folders/4353455/watermark" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Apply watermark to folder Applies or update a watermark on a folder. ``` curl -i -X PUT "https://api.box.com/2.0/folders/4353455/watermark" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "watermark": { "imprint": "default" } }' ``` ## Remove folder watermark Removes the watermark from a folder. ``` curl -i -X DELETE "https://api.box.com/2.0/folders/4353455/watermark" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get folder lock Retrieve locks applied to a folder. ``` curl -i -X GET "https://api.box.com/2.0/folder_locks?folder_id=33552487093" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create folder lock Creates a lock on a folder to prevent move and / or delete operations. ``` curl -i -X POST "https://api.box.com/2.0/folder_locks" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "folder": { "type": "folder", "id": "33552487093" }, "locked_operations": { "move": true, "delete": true } }' ``` ## Delete folder lock Deletes a lock on a folder. ``` curl -i -X DELETE "https://api.box.com/2.0/folder_locks/93134" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get template by name Retrieves a metadata template by its scope and template name. ``` curl -i -X GET "https://api.box.com/2.0/metadata_templates/enterprise/blueprintTemplate/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update metadata template Updates a metadata template. The metadata template can only be updated if the template already exists. The update is applied atomically. If any errors occur during the application of the operations, the metadata template remains unchanged. ``` curl -i -X PUT "https://api.box.com/2.0/metadata_templates/enterprise/blueprintTemplate/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[ { "op": "editField", "fieldKey": "category", "data": { "displayName": "Customer Group" } } ]' ``` ## Delete metadata template Delete a metadata template and its instances. This deletion is permanent and can not be reversed. ``` curl -i -X DELETE "https://api.box.com/2.0/metadata_templates/enterprise/blueprintTemplate/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get a template by ID Retrieves a metadata template by its ID. ``` curl -i -X GET "https://api.box.com/2.0/metadata_templates/d9671692-3df6-11ea-b77f-2e728ce88125" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List enterprise templates Used to retrieve all metadata templates within a user's enterprise ``` curl -i -X GET "https://api.box.com/2.0/metadata_templates/enterprise" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List global templates Used to retrieve all globally available metadata templates. ``` curl -i -X GET "https://api.box.com/2.0/metadata_templates/global" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create metadata template Creates a new metadata template that can be applied to files and folders. ``` curl -i -X POST "https://api.box.com/2.0/metadata_templates/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "scope": "enterprise", "displayName": "Customer", "fields": [ { "type": "string", "key": "name", "displayName": "Name", "description": "The customer name", "hidden": false }, { "type": "date", "key": "last_contacted_at", "displayName": "Last Contacted At", "description": "When this customer was last contacted at", "hidden": false }, { "type": "enum", "key": "industry", "displayName": "Industry", "options": [ {"key": "Technology"}, {"key": "Healthcare"}, {"key": "Legal"} ] }, { "type": "multiSelect", "key": "role", "displayName": "Contact Role", "options": [ {"key": "Developer"}, {"key": "Business Owner"}, {"key": "Marketing"}, {"key": "Legal"}, {"key": "Sales"} ] } ] }' ``` ## List cascade policies Retrieve a collection of metadata cascade policies within a given folder for the current enterprise. ``` curl -i -X GET "https://api.box.com/2.0/metadata_cascade_policies?folder_id=31232" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create cascade policy Creates a new metadata cascade policy that applies a given metadata template to a given folder and automatically cascades it down to its children. In order for the policy to work, a metadata instance must first be applied to the folder. ``` curl -i -X POST "https://api.box.com/2.0/metadata_cascade_policies" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "folder_id": "12321", "scope": "enterprise_27335", "templateKey": "productInfo" }' ``` ## Get cascade policy Retrieve a metadata cascade policy. ``` curl -i -X GET "https://api.box.com/2.0/metadata_cascade_policies/324324" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Delete cascade policy Deletes a metadata cascade policy. ``` curl -i -X DELETE "https://api.box.com/2.0/metadata_cascade_policies/324324" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Force apply cascade policy If a policy already exists on a folder, this will apply that policy to all existing files and sub-folders within the target folder. ``` curl -i -X POST "https://api.box.com/2.0/metadata_cascade_policies/21312/apply" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "conflict_resolution": "overwrite" }' ``` ## Create a metadata query ``` curl -i -X POST "https://api.box.com/2.0/files/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "from": "enterprise_123456.contractTemplate", "query": "amount >= :value", "query_params": { "value": 100 }, "fields": [ "created_at", "metadata.enterprise_123456.contractTemplate.amount", "metadata.enterprise_123456.contractTemplate.customerName" ], "ancestor_folder_id": "5555", "order_by": [ { "field_key": "amount", "direction": "asc" } ], "limit": 100 }' ``` ## Get metadata query indices ``` curl -i -X GET "https://api.box.com/2.0/metadata_query_indices?scope=enterprise&template_key=properties" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get comment Retrieves the message and metadata for a specific comment, as well as information on the user who created the comment. ``` curl -i -X GET "https://api.box.com/2.0/comments/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update comment Update the message of a comment. ``` curl -i -X PUT "https://api.box.com/2.0/comments/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "message": "My New Message" }' ``` ## Delete comment Permanently deletes a comment. ``` curl -i -X DELETE "https://api.box.com/2.0/comments/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create comment Adds a comment comment by the user to a specific file, or as a reply to an other comment. ``` curl -i -X POST "https://api.box.com/2.0/comments" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "message": "Review completed!", "item": { "type": "file", "id": 426436 } }' ``` ## Create reply ``` curl -i -X POST "https://api.box.com/2.0/comments" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "message": "I agree with this.", "item": { "type": "comment", "id": 345344 } } ``` ## Tag User in Comment ``` curl -i -X POST "https://api.box.com/2.0/comments" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "tagged_message": "What do you think @[1234:John]?", "item": { "type": "file", "id": 123 } } ``` ## Tag User in Reply ``` curl -i -X POST "https://api.box.com/2.0/comments" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "message": " @[1234:John], I agree with this.", "item": { "type": "comment", "id": 345344 } } ``` ## Get collaboration Retrieves a single collaboration. ``` curl -i -X GET "https://api.box.com/2.0/collaborations/1234" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update collaboration Updates a collaboration. Can be used to change the owner of an item, or to accept collaboration invites. ``` curl -i -X PUT "https://api.box.com/2.0/collaborations/1234" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "role": "viewer" }' ``` ## Delete collaboration Deletes a single collaboration. ``` curl -i -X DELETE "https://api.box.com/2.0/collaborations/1234" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List pending collaborations Retrieves all pending collaboration invites for this user. ``` curl -i -X GET "https://api.box.com/2.0/collaborations?status=pending" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create collaboration Adds a collaboration for a single user or a single group to a file or folder. Collaborations can be created using email address, user IDs, or a group IDs. If a collaboration is being created with a group, access to this endpoint is dependent on the group's ability to be invited. ``` curl -i -X POST "https://api.box.com/2.0/collaborations" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "item": { "type": "file", "id": "11446498" }, "accessible_by": { "type": "user", "login": "user@example.com" }, "role": "editor" }' ``` ``` curl -i -X POST "https://api.box.com/2.0/collaborations" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "item": { "type": "file", "id": "11446498" }, "accessible_by": { "type": "group", "id": "845344" }, "role": "editor" }' ``` ## Search for content Searches for items that are available to the user or an entire enterprise. ``` curl -i -X GET "https://api.box.com/2.0/search?query=sales" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create task Creates a single task on a file. ``` curl -i -X POST "https://api.box.com/2.0/tasks" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "item": { "id": "11446498", "type": "file" }, "action": "review" }' ``` ## Get task Fetches a specific task. ``` curl -i -X GET "https://api.box.com/2.0/tasks/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update task Updates a specific task. ``` curl -i -X PUT "https://api.box.com/2.0/tasks/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "action": "review" }' ``` ## Delete task Deletes a specific task. ``` curl -i -X DELETE "https://api.box.com/2.0/tasks/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List task's assignments Retrieves all of the assignments for a given task. ``` curl -i -X GET "https://api.box.com/2.0/tasks/12345/assignments" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Assign task Assigns a task to a user. Multiple assignments to different users are allowed per task. ``` curl -i -X POST "https://api.box.com/2.0/task_assignments" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "task": { "id": "11446498", "type": "task" }, "assign_to": { "id": "4823213" } }' ``` ## Get task assignment Fetches a specific task assignment. ``` curl -i -X GET "https://api.box.com/2.0/task_assignments/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update task assignment Updates a task assignment. This endpoint can be used to update the state of a task. ``` curl -i -X PUT "https://api.box.com/2.0/task_assignments/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "message": "New message", "resolution_state": "completed" }' ``` ## Unassign task Deletes a specific task assignment. ``` curl -i -X DELETE "https://api.box.com/2.0/task_assignments/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Find item for shared link Return the file or folder represented by a shared link. Shared items are any files or folders that are represented by a shared link, which can originate within the current enterprise or within another one. This endpoint allows an application to retrieve information about a shared item when only given a shared link. ``` curl -i -X GET "https://api.box.com/2.0/shared_items" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "boxapi: shared_link=https://app.box.com/s/gjasdasjhasd&shared_link_password=letmein" ``` The syntax is the same regardless of wether the shared link is a file or a folder. ``` curl -i -X GET "https://api.box.com/2.0/shared_items" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "boxapi: shared_link=https://app.box.com/s/jsasdsd8sad24&shared_link_password=letmein" ``` ## Create web link Creates a web link object within a folder. ``` curl -i -X POST "https://api.box.com/2.0/web_links" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "Cloud Content Management", "url": "https://box.com", "parent": { "id": "0" } }' ``` ## Get web link Retrieve information about a web link. ``` curl -i -X GET "https://api.box.com/2.0/web_links/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Restore web link Restores an web link that has been moved to the trash. ``` curl -i -X POST "https://api.box.com/2.0/web_links/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update web link Updates a web link object. ``` curl -i -X PUT "https://api.box.com/2.0/web_links/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "Cloud Content Management" }' ``` ## Delete web link Deletes a web link. ``` curl -i -X DELETE "https://api.box.com/2.0/web_links/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get trashed web link Retrieves a web link that has been moved to the trash. ``` curl -i -X GET "https://api.box.com/2.0/web_links/12345/trash" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Permanently delete web link Permanently deletes a web link that is in the trash. This action cannot be undone. ``` curl -i -X DELETE "https://api.box.com/2.0/web_links/12345/trash" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List enterprise users Returns a list of all users for the Enterprise along with their user_id, public_name, and login. The application and the authenticated user need to have the permission to look up users in the entire enterprise. ``` curl -i -X GET "https://api.box.com/2.0/users" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create user Creates a new managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. ``` curl -i -X POST "https://api.box.com/2.0/users" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "login": "ceo@example.com", "name": "Aaron Levie" }' ``` ## Get authenticated user Retrieves information about the user who is currently authenticated. In the case of a 3-legged OAuth2, client-side authenticated application this will be the user who authorized the app. In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default. Use the `As-User` header to change who this API call is made on behalf of. ``` curl -i -X GET "https://api.box.com/2.0/users/me" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get user Retrieves information about a user in the enterprise. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This endpoint also returns a limited set of information for external users who are collaborated on content owned by the enterprise for authenticated users with the right scopes. In this case, disallowed fields will return null instead. ``` curl -i -X GET "https://api.box.com/2.0/users/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update user Updates a managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. ``` curl -i -X PUT "https://api.box.com/2.0/users/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "Aaron Levie" }' ``` ## Delete user Deletes a user. By default this will fail if the user still owns any content. Move their owned content first before proceeding, or use the `force` field to delete the user and their files. ``` curl -i -X DELETE "https://api.box.com/2.0/users/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get user avatar Retrieves an image of a the user's avatar. ``` curl -i -X GET "https://api.box.com/2.0/users/12345/avatar" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add or update user avatar Uploads or updates a user avatar. ``` curl -i -X -L POST "https://api.box.net/2.0/users/12345/avatar" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ --form 'pic=@"path/to/file/file.jpeg"' ``` ## Delete user avatar Deletes a user avatar. ``` curl -i -X DELETE -L "https://api.box.net/2.0/users/12345/avatar" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Transfer owned folders Move all of the items owned by a user into a new folder in another user’s account. Only the root folder (`0`) can be transferred. Folders can only be moved across users by users with administrative permissions. This call will be performed synchronously which might lead to a slow response when the source user has a large number of items in all of its folders. If the destination path has a metadata cascade policy attached to any of the parent folders, a metadata cascade operation will be kicked off asynchronously. There is currently no way to check for when this operation is finished. ``` curl -i -X PUT "https://api.box.com/2.0/users/12345/folders/0" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "owned_by": { "id": "1232234" } }' ``` ## List user's email aliases Retrieves all email aliases for a user. The collection does not include the primary login for the user. ``` curl -i -X GET "https://api.box.com/2.0/users/12345/email_aliases" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create email alias Adds a new email alias to a user account. ``` curl -i -X POST "https://api.box.com/2.0/users/12345/email_aliases" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "email": "alias@example.com" }' ``` ## Remove email alias Removes an email alias from a user. ``` curl -i -X DELETE "https://api.box.com/2.0/users/12345/email_aliases/23432" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List user's groups Retrieves all the groups for a user. The user making an API call must have admin permissions to inspect the enterprise's groups. ``` curl -i -X GET "https://api.box.com/2.0/users/12345/memberships" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Invite user Invites an existing external user to join an enterprise. The existing user can not be part of another enterprise and must already have a Box account. Once invited, the user will receive an email and are prompted to accept the invitation within the Box web application. This method requires the "Manage An Enterprise" scope enabled for the application, which can be enabled within the developer console. ``` curl -i -X POST "https://api.box.com/2.0/invites" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "enterprise": { "id": "1232234" }, "actionable_by": { "login" : "freeuser@box.com" } }' ``` ## Get user invite status Returns the status of a user invite. ``` curl -i -X GET "https://api.box.com/2.0/invites/213723" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List enterprise groups Retrieves all of the groups for a given enterprise. The user must have admin permissions to inspect enterprise's groups. ``` curl -i -X GET "https://api.box.com/2.0/groups" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create group Creates a new group of users in an enterprise. Only users with admin permissions can create new groups. ``` curl -i -X POST "https://api.box.com/2.0/groups" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "Customer Support" }' ``` ## Get group Retrieves information about a group. ``` curl -i -X GET "https://api.box.com/2.0/groups/57645" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update group Updates a specific group. ``` curl -i -X PUT "https://api.box.com/2.0/groups/57645" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "Customer Support" }' ``` ## Delete group Permanently deletes a group. ``` curl -i -X DELETE "https://api.box.com/2.0/groups/57645" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List group's members Retrieves all the members for a group. The user must have admin permissions to inspect enterprise's groups. ``` curl -i -X GET "https://api.box.com/2.0/groups/57645/memberships" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List group's collaborations Retrieves all the collaborations for a group. The user must have admin permissions to inspect enterprise's groups. Each collaboration object has details on which files or folders the group has access to and with what role. ``` curl -i -X GET "https://api.box.com/2.0/groups/57645/collaborations" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add user to group Creates a group membership ``` curl -i -X POST "https://api.box.com/2.0/group_memberships" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "user": { "id": "1434325" }, "group": { "id": "4545523" } }' ``` ## Get group membership Retrieves a specific group membership. ``` curl -i -X GET "https://api.box.com/2.0/group_memberships/434534" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update user's membership Updates a user's group membership. ``` curl -i -X PUT "https://api.box.com/2.0/group_memberships/434534" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "role": "admin" }' ``` ## Remove user from group Deletes a specific group membership. ``` curl -i -X DELETE "https://api.box.com/2.0/group_memberships/434534" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List all webhooks Returns all defined webhooks for the requesting application. ``` curl -i -X GET "https://api.box.com/2.0/webhooks" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create webhook Creates a webhook. ``` curl -i -X POST "https://api.box.com/2.0/webhooks" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "target": { "id": "21322", "type": "file" }, "address": "https://example.com/webhooks", "triggers": [ "FILE.PREVIEWED" ] }' ``` ``` curl -i -X POST "https://api.box.com/2.0/webhooks" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "target": { "id": "234234", "type": "folder" }, "address": "https://example.com/webhooks", "triggers": [ "FILE.UPLOADED" ] }' ``` ## Get webhook Retrieves a specific webhook ``` curl -i -X GET "https://api.box.com/2.0/webhooks/3321123" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update webhook Updates a webhook. ``` curl -i -X PUT "https://api.box.com/2.0/webhooks/3321123" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "triggers": [ "FILE.DOWNLOADED" ] }' ``` ## Delete webhook Deletes a webhook. ``` curl -i -X DELETE "https://api.box.com/2.0/webhooks/3321123" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update skill invocation Updates the status, usage and response metadata of a skill invocation. ``` curl -i -X PUT "https://api.box.com/2.0/skill_invocations/33243242" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "status": "success", "metadata": { "cards": [{ "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } },{ "type": "skill_card", "skill_card_type": "transcript", "skill_card_title": { "code": "video-transcription", "message": "Video Transcription" }, "skill": { "type": "service" "id": "video-transcription-service" }, "invocation": { "type": "skill_invocation" "id": "video-transcription-service-123" }, "duration": 1000, "entries": { { "text": "Hi John, have I told you about Box recently?", "appears": [{ "start": 0 }] }, { "text": "No Aaron, you have not. Tell me more!", "appears": [{ "start": 5 }] } } },{ "type": "skill_card", "skill_card_type": "timeline", "skill_card_title": { "code": "face-detection", "message": "Faces" }, "skill": { "type": "service" "id": "face-detection-service" }, "invocation": { "type": "skill_invocation" "id": "face-detection-service-123" }, "duration": 1000, "entries": { { "text": "John", "appears": [{ "start": 0, "end": 5 }, { "start": 10, "end": 15 }], "image_url": "https://example.com/john.png" }, { "text": "Aaron", "appears": [{ "start": 5, "end": 10 }], "image_url": "https://example.com/aaron.png" } } },{ "type": "skill_card", "skill_card_type": "status", "skill_card_title": { "code": "hold", "message": "Please hold..." }, "skill": { "type": "service" "id": "face-detection-service" }, "invocation": { "type": "skill_invocation" "id": "face-detection-service-123" }, "status": { "code": "processing", "message": "We are processing this file right now." } }], }, "file": { "id": "12345" }, "usage": { "unit": "file", "value": 1 } }' ``` ## List Skill cards on file ``` curl -i -X PUT "https://api.box.com/2.0/files/12345/metadata/global/boxSkillsCards" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create Skill cards on file ``` curl -i -X POST "https://api.box.com/2.0/files/12345/metadata/global/boxSkillsCards" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "cards": [{ "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } },{ "type": "skill_card", "skill_card_type": "transcript", "skill_card_title": { "code": "video-transcription", "message": "Video Transcription" }, "skill": { "type": "service" "id": "video-transcription-service" }, "invocation": { "type": "skill_invocation" "id": "video-transcription-service-123" }, "duration": 1000, "entries": { { "text": "Hi John, have I told you about Box recently?", "appears": [{ "start": 0 }] }, { "text": "No Aaron, you have not. Tell me more!", "appears": [{ "start": 5 }] } } },{ "type": "skill_card", "skill_card_type": "timeline", "skill_card_title": { "code": "face-detection", "message": "Faces" }, "skill": { "type": "service" "id": "face-detection-service" }, "invocation": { "type": "skill_invocation" "id": "face-detection-service-123" }, "duration": 1000, "entries": { { "text": "John", "appears": [{ "start": 0, "end": 5 }, { "start": 10, "end": 15 }], "image_url": "https://example.com/john.png" }, { "text": "Aaron", "appears": [{ "start": 5, "end": 10 }], "image_url": "https://example.com/aaron.png" } } },{ "type": "skill_card", "skill_card_type": "status", "skill_card_title": { "code": "hold", "message": "Please hold..." }, "skill": { "type": "service" "id": "face-detection-service" }, "invocation": { "type": "skill_invocation" "id": "face-detection-service-123" }, "status": { "code": "processing", "message": "We are processing this file right now." } }], }' ``` ## Update Skill cards on file ``` curl -i -X PUT "https://api.box.com/2.0/files/12345/metadata/global/boxSkillsCards" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[ "op": "replace", "path": "/cards/0", "value": { "type": "skill_card", "skill_card_type": "keyword", "skill_card_title": { "code": "license-plates", "message": "Licence Plates" }, "skill": { "type": "service" "id": "license-plates-service" }, "invocation": { "type": "skill_invocation" "id": "license-plates-service-123" }, "entries": { { "text": "DD-26-YT" }, { "text": "DN86 BOX" } } } ]' ``` ## Delete Skill cards from file ``` curl -i -X DELETE "https://api.box.com/2.0/files/12345/metadata/global/boxSkillsCards" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get a long poll endpoint Returns a list of real-time servers that can be used for long-polling updates to the [event stream](#get-events). Long polling is the concept where a HTTP request is kept open until the server sends a response, then repeating the process over and over to receive updated responses. Long polling the event stream can only be used for user events, not for enterprise events. To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next, make a long poll request to any of the provided URLs. When an event occurs in monitored account a response with the value `new_change` will be sent. The response contains no other details as it simply serves as a prompt to take further action such as sending a request to the [events endpoint](#get-events) with the last known `stream_position`. After the server sends this response it closes the connection. You must now repeat the long poll process to begin listening for events again. If no events occur for a while and the connection times out you will receive a response with the value `reconnect`. When you receive this response you’ll make another call to this endpoint to restart the process. If you receive no events in `retry_timeout` seconds then you will need to make another request to the real-time server (one of the URLs in the response for this endpoint). This might be necessary due to network errors. Finally, if you receive a `max_retries` error when making a request to the real-time server, you should start over by making a call to this endpoint first. ``` curl -i -X OPTIONS "https://api.box.com/2.0/events" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get user and enterprise events Returns up to a year of past events for a given user or for the entire enterprise. By default this returns events for the authenticated user. To retrieve events for the entire enterprise, set the `stream_type` to `admin_logs` (historical - 1 year) or `admin_logs_streaming` (live - two weeks). The user making the API call will need to have admin privileges, and the application will need to have the permission to access the event feed to get the enterprise event feed. ``` curl -i -X GET "https://api.box.com/2.0/events" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ``` curl -i -X GET "https://api.box.com/2.0/events?stream_type=admin_logs" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ``` curl -i -X GET "https://api.box.com/2.0/events?stream_type=admin_logs&event_type=LOGIN,FAILED_LOGIN" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ``` curl -i -X GET "https://api.box.com/2.0/events?stream_type=admin_logs_streaming" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ``` curl -i -X GET "https://api.box.com/2.0/events?stream_type=admin_logs_streaming&event_type=LOGIN,FAILED_LOGIN" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List all collections Retrieves all collections for a given user. Currently, only the `favorites` collection is supported. ``` curl -i -X GET "https://api.box.com/2.0/collections" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List collection items Retrieves the files and/or folders contained within this collection. ``` curl -i -X GET "https://api.box.com/2.0/collections/926489/items" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add file to collection ``` curl -i -X PUT "https://api.box.com/2.0/files/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "collections": [ { "id": "123" } ] }' ``` ## Add folder to collection ``` curl -i -X PUT "https://api.box.com/2.0/folders/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "collections": [ { "id": "123" } ] }' ``` ## Add web link to collection ``` curl -i -X PUT "https://api.box.com/2.0/web_links/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "collections": [ { "id": "123" } ] }' ``` ## Remove file from collection ``` curl -i -X PUT "https://api.box.com/2.0/files/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "collections": [] }' ``` ## Remove folder from collection ``` curl -i -X PUT "https://api.box.com/2.0/folders/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "collections": [] }' ``` ## Remove web link from collection ``` curl -i -X PUT "https://api.box.com/2.0/web_links/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "collections": [] }' ``` ## List recent items Returns information about the recent items accessed by a user, either in the last 90 days or up to the last 1000 items accessed. ``` curl -i -X GET "https://api.box.com/2.0/recent_items" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List retention policies Retrieves all of the retention policies for an enterprise. ``` curl -i -X GET "https://api.box.com/2.0/retention_policies" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create retention policy Creates a retention policy. ``` curl -i -X POST "https://api.box.com/2.0/retention_policies" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "policy_name": "Some Policy Name", "policy_type": "finite", "retention_length": 365, "disposition_action": "permanently_delete" }' ``` ## Get retention policy Retrieves a retention policy. ``` curl -i -X GET "https://api.box.com/2.0/retention_policies/982312" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update retention policy Updates a retention policy. ``` curl -i -X PUT "https://api.box.com/2.0/retention_policies/982312" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "disposition_action": "permanently_delete" }' ``` ## List policy's assignments Returns a list of all retention policy assignments associated with a specified retention policy. ``` curl -i -X GET "https://api.box.com/2.0/retention_policies/982312/assignments" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Assign retention policy Assigns a retention policy to an item. ``` curl -i -X POST "https://api.box.com/2.0/retention_policy_assignments" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "policy_id": "173463", "assign_to": { "type": "folder", "id": "6564564" } }' ``` ## Get policy assignment Retrieves a retention policy assignment ``` curl -i -X GET "https://api.box.com/2.0/retention_policy_assignments/1233123" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List all legal hold policies Retrieves a list of legal hold policies that belong to an enterprise. ``` curl -i -X GET "https://api.box.com/2.0/legal_hold_policies" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create legal hold policy Create a new legal hold policy. ``` curl -i -X POST "https://api.box.com/2.0/legal_hold_policies" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "policy_name": "Policy 3", "description": "Automatic created policy" }' ``` ## Get legal hold policy Retrieve a legal hold policy. ``` curl -i -X GET "https://api.box.com/2.0/legal_hold_policies/324432" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update legal hold policy Update legal hold policy. ``` curl -i -X PUT "https://api.box.com/2.0/legal_hold_policies/324432" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "policy_name": "Policy 4" }' ``` ## Delete legal hold policy Delete an existing legal hold policy. This is an asynchronous process. The policy will not be fully deleted yet when the response returns. ``` curl -i -X DELETE "https://api.box.com/2.0/legal_hold_policies/324432" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List policy's assignments Retrieves a list of items a legal hold policy has been assigned to. ``` curl -i -X GET "https://api.box.com/2.0/legal_hold_policy_assignments?policy_id=324432" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Assign legal hold policy Assign a legal hold to a file, file version, folder, or user. ``` curl -i -X POST "https://api.box.com/2.0/legal_hold_policy_assignments" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "policy_id": "123244", "assign_to": { "type": "folder", "id": "6564564" } }' ``` ## Get policy assignment Retrieve a legal hold policy assignment. ``` curl -i -X GET "https://api.box.com/2.0/legal_hold_policy_assignments/753465" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Unassign legal hold policy Remove a legal hold from an item. This is an asynchronous process. The policy will not be fully removed yet when the response returns. ``` curl -i -X DELETE "https://api.box.com/2.0/legal_hold_policy_assignments/753465" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get retention for file Returns information about a file version retention. ``` curl -i -X GET "https://api.box.com/2.0/file_version_retentions/3424234" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List retentions on files Retrieves all file version retentions for the given enterprise. ``` curl -i -X GET "https://api.box.com/2.0/file_version_retentions" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List files under retention for a retention policy Retrieves all files for the given retention policy id. ``` curl -i -X GET "https://app.box.com/api/2.0/retention_policy_assignments/3424234/files_under_retention" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List file versions under retention for a retention policy Retrieves all file versions for the given retention policy id. ``` curl -i -X GET "https://app.box.com/api/2.0/retention_policy_assignments/3424234/file_versions_under_retention" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Inspect legal hold on file Retrieves information about the legal hold policies assigned to a file version. ``` curl -i -X GET "https://api.box.com/2.0/file_version_legal_holds/2348213" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List legal holds for policy Get list of non-deleted legal holds for a single legal hold policy. ``` curl -i -X GET "https://api.box.com/2.0/file_version_legal_holds?policy_id=133870" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get device pin Retrieves information about an individual device pin. ``` curl -i -X GET "https://api.box.com/2.0/device_pinners/2324234" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Delete device pin Deletes an individual device pin. ``` curl -i -X DELETE "https://api.box.com/2.0/device_pinners/2324234" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List enterprise device pins Retrieves all the device pins within an enterprise. The user must have admin privileges, and the application needs the "manage enterprise" scope to make this call. ``` curl -i -X GET "https://api.box.com/2.0/enterprises/3442311/device_pinners" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List terms of services Returns the current terms of service text and settings for the enterprise. ``` curl -i -X GET "https://api.box.com/2.0/terms_of_services" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create terms of service Creates a terms of service for a given enterprise and type of user. ``` curl -i -X POST "https://api.box.com/2.0/terms_of_services" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "status": "enabled", "text": "By collaborating on this file you are accepting..." }' ``` ## Get terms of service Fetches a specific terms of service. ``` curl -i -X GET "https://api.box.com/2.0/terms_of_services/324234" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update terms of service Updates a specific terms of service. ``` curl -i -X PUT "https://api.box.com/2.0/terms_of_services/324234" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "status": "enabled", "text": "By collaborating on this file you are accepting..." }' ``` ## List ToS user statuses Retrieves an overview of users and their status for a terms of service, including Whether they have accepted the terms and when. ``` curl -i -X GET "https://api.box.com/2.0/terms_of_service_user_statuses?tos_id=324234" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Set status for new user Sets the status for a terms of service for a user. ``` curl -i -X POST "https://api.box.com/2.0/terms_of_service_user_statuses" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "tos": { "type": "terms_of_service", "id": "1232132" }, "user": { "type": "user", "id": "3423423" }, "is_accepted": true }' ``` ## Set status for existing user Updates the status for a terms of service for a user. ``` curl -i -X PUT "https://api.box.com/2.0/terms_of_service_user_statuses/324234" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "is_accepted": true }' ``` ## List whitelist entries Returns the list of whitelist entries which specify what domains can collaborate with the current enterprise. ``` curl -i -X GET "https://api.box.com/2.0/collaboration_whitelist_entries" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create whitelist entry Creates a collaboration whitelist entry, specifying a domain and direction to allow collaboration for. ``` curl -i -X POST "https://api.box.com/2.0/collaboration_whitelist_entries" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "domain": "example.com", "direction": "inboud" }' ``` ## Get whitelist entry Returns a specific collaboration whitelist entry. ``` curl -i -X GET "https://api.box.com/2.0/collaboration_whitelist_entries/213123" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Delete whitelist entry Deletes a specific collaboration whitelist entry. ``` curl -i -X DELETE "https://api.box.com/2.0/collaboration_whitelist_entries/213123" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List whitelist exemptions Returns a list of users who have been exempt from the collaboration whitelist. ``` curl -i -X GET "https://api.box.com/2.0/collaboration_whitelist_exempt_targets" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Create whitelist exemption Creates a collaboration whitelist entry exemption, specifying a user that is exempted from the whitelist. ``` curl -i -X POST "https://api.box.com/2.0/collaboration_whitelist_exempt_targets" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "user": { "id": "23522323" } }' ``` ## Get whitelist exemption Returns a users who has been exempt from the collaboration whitelist. ``` curl -i -X GET "https://api.box.com/2.0/collaboration_whitelist_exempt_targets/984923" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Remove whitelist exemption Deletes a specific collaboration whitelist exemption. ``` curl -i -X DELETE "https://api.box.com/2.0/collaboration_whitelist_exempt_targets/984923" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List storage policies Fetches all the storage policies in the enterprise. ``` curl -i -X GET "https://api.box.com/2.0/storage_policies" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get storage policy Fetches a specific storage policy. ``` curl -i -X GET "https://api.box.com/2.0/storage_policies/34342" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## List policy assignments Fetches all the storage policy assignment for an enterprise or user. ``` curl -i -X GET "https://api.box.com/2.0/storage_policy_assignments?resolved_for_type=userresolved_for_id=984322" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Assign storage policy Creates a storage policy assignment for an enterprise or user. ``` curl -i -X POST "https://api.box.com/2.0/storage_policy_assignments" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "storage_policy": { "type": "storage_policy", "id": "1434325" }, "assigned_to": { "type": "user", "id": "9987987" } }' ``` ## Get policy assignment Fetches a specific storage policy assignment. ``` curl -i -X GET "https://api.box.com/2.0/storage_policy_assignments/932483" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Update policy assignment Updates a specific storage policy assignment. ``` curl -i -X PUT "https://api.box.com/2.0/storage_policy_assignments/932483" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "storage_policy": { "type": "storage_policy", "id": "1434325" } }' ``` ## Unassign storage policy Delete a storage policy assignment. Deleting a storage policy assignment on a user will have the user inherit the enterprise's default storage policy. There is a rate limit for calling this endpoint of only twice per user in a 24 hour period. ``` curl -i -X DELETE "https://api.box.com/2.0/storage_policy_assignments/932483" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "items": { "type": "storage_policy", "id": "1434325" } }' ``` ## Create zip download ``` curl -i -X POST "https://api.box.com/2.0/zip_downloads" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "download_file_name": "January Financials", "items": [ { "type": "file", "id": "12345" }, { "type": "file", "id": "34325" }, { "type": "folder", "id": "45678" } ] }' ``` ## Get zip download status ``` curl -i -X GET "https://api.box.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Download zip archive ``` curl -L GET "https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -o sample_curl.zip ``` ## List all classifications ``` curl -i -X GET "https://api.box.com/2.0/metadata_templates/enterprise/securityClassification-6VMVochwUWo/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add initial classifications ``` curl -i -X POST "https://api.box.com/2.0/metadata_templates/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "templateKey": "securityClassification-6VMVochwUWo", "scope": "enterprise", "displayName": "Classification", "hidden": false, "copyInstanceOnItemCopy": true, "fields": [ { "type": "enum", "key": "Box__Security__Classification__Key", "displayName": "Classification", "hidden": false, "options": [ { "key": "Classified", "staticConfig": { "classification": { "colorID": 7, "classificationDefinition": "Top Seret" } } } ] } ] }' ``` ## Add another classification ``` curl -i -X PUT "https://api.box.com/2.0/metadata_templates/enterprise/securityClassification-6VMVochwUWo/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[{ "op": "addEnumOption", "fieldKey": "Box__Security__Classification__Key", "data": { "key": "Sensitive", "staticConfig":{ "classification": { "classificationDefinition": "Sensitive information that must not be shared.", "colorID": 4 } } } }]' ``` ## Update classification ``` curl -i -X PUT "https://api.box.com/2.0/metadata_templates/enterprise/securityClassification-6VMVochwUWo/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[{ "op": "editEnumOption", "fieldKey": "Box__Security__Classification__Key", "enumOptionKey": "Sensitive", "data": { "key": "Very Sensitive", "staticConfig": { "classification": { "classificationDefinition": "Sensitive information that must not be shared.", "colorID": 4 } } } }]' ``` ## Delete classification ``` curl -i -X PUT "https://api.box.com/2.0/metadata_templates/enterprise/securityClassification-6VMVochwUWo/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[{ "op": "removeEnumOption", "fieldKey": "Box__Security__Classification__Key", "enumOptionKey": "Sensitive" }]' ``` ## Delete all classifications ``` curl -i -X DELETE "https://api.box.com/2.0/metadata_templates/enterprise/securityClassification-6VMVochwUWo/schema" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get classification on file ``` curl -i -X GET "https://api.box.com/2.0/files/12345/metadata/enterprise/securityClassification-6VMVochwUWo" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add classification to file ``` curl -i -X POST "https://api.box.com/2.0/files/12345/metadata/enterprise/securityClassification-6VMVochwUWo" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "Box__Security__Classification__Key": "Sensitive" }' ``` ## Update classification on file ``` curl -i -X PUT "https://api.box.com/2.0/files/12345/metadata/enterprise/securityClassification-6VMVochwUWo" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[{ "op": "replace", "path": "/Box__Security__Classification__Key", "value": "Internal" }]' ``` ## Remove classification from file ``` curl -i -X DELETE "https://api.box.com/2.0/files/12345/metadata/enterprise/securityClassification-6VMVochwUWo" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get classification on folder ``` curl -i -X GET "https://api.box.com/2.0/folders/12345/metadata/enterprise/securityClassification-6VMVochwUWo" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add classification to folder ``` curl -i -X POST "https://api.box.com/2.0/folders/12345/metadata/enterprise/securityClassification-6VMVochwUWo" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "Box__Security__Classification__Key": "Sensitive" }' ``` ## Update classification on folder ``` curl -i -X PUT "https://api.box.com/2.0/folders/12345/metadata/enterprise/securityClassification-6VMVochwUWo" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json-patch+json" \ -d '[{ "op": "replace", "path": "/Box__Security__Classification__Key", "value": "Internal" }]' ``` ## Remove classification from folder ``` curl -i -X DELETE "https://api.box.com/2.0/folders/12345/metadata/enterprise/securityClassification-6VMVochwUWo" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Copy a file request ``` curl -i -X POST "https://api.box.com/2.0/file_requests/42037322/copy" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "title": "Please upload required documents", "description": "Please upload required documents", "status": "active", "is_email_required": true, "is_description_required": false, "folder": { "id": "2233212", "type": "folder" } }' ``` ## Update a file request ``` curl -i -X PUT "https://api.box.com/2.0/file_requests/42037322" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "title": "Please upload required documents", "description": "Please upload required documents", "status": "active", "is_email_required": true, "is_description_required": false }' ``` ## Get a file request ``` curl -i -X GET "https://api.box.com/2.0/file_requests/42037322" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Delete a file request ``` curl -i -X DELETE "https://api.box.com/2.0/file_requests/42037322" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get shared link on a file ``` curl -i -X GET "https://api.box.com/2.0/files/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add shared link to a file ``` curl -i -X PUT "https://api.box.com/2.0/files/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": { "access": "open", "password": "mypassword", "unshared_at": "2012-12-12T10:53:43-08:00", "permissions": { "can_download": false } } }' ``` ## Update shared link on a file ``` curl -i -X PUT "https://api.box.com/2.0/files/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": { "access": "open", "password": "mypassword", "unshared_at": "2012-12-12T10:53:43-08:00", "permissions": { "can_download": false } } }' ``` ## Remove shared link from a file ``` curl -i -X PUT "https://api.box.com/2.0/files/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": null }' ``` ## Get shared link on a folder ``` curl -i -X GET "https://api.box.com/2.0/folders/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add shared link to a folder ``` curl -i -X PUT "https://api.box.com/2.0/folders/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": { "access": "open", "password": "mypassword", "unshared_at": "2012-12-12T10:53:43-08:00", "permissions": { "can_download": false } } }' ``` ## Update shared link on a folder ``` curl -i -X PUT "https://api.box.com/2.0/folders/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": { "access": "open", "password": "mypassword", "unshared_at": "2012-12-12T10:53:43-08:00", "permissions": { "can_download": false } } }' ``` ## Remove shared link from a folder ``` curl -i -X PUT "https://api.box.com/2.0/folders/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": null }' ``` ## Get shared link on a web link ``` curl -i -X GET "https://api.box.com/2.0/web_links/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Add shared link to a web link ``` curl -i -X PUT "https://api.box.com/2.0/web_links/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": { "access": "open", "password": "mypassword", "unshared_at": "2012-12-12T10:53:43-08:00", "permissions": { "can_download": false } } }' ``` ## Update shared link on a web link ``` curl -i -X PUT "https://api.box.com/2.0/web_links/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": { "access": "open", "password": "mypassword", "unshared_at": "2012-12-12T10:53:43-08:00", "permissions": { "can_download": false } } }' ``` ## Remove shared link from a web link ``` curl -i -X PUT "https://api.box.com/2.0/web_links/32423234?fields=shared_link" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "shared_link": null }' ``` ## Gets a relay workflow with flows that are of type WORKFLOW_MANUAL_START ``` curl -i -X GET "https://api.box.com/2.0/workflows?folder_id=324234" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Start a flow in a relay workflow of type WORKFLOW_MANUAL_START ``` curl -i -X POST "https://api.box.com/2.0/workflows/42037322/start" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "type": "workflow_parameters", "flow": { "id": "8937625", "type": "flow" }, "files": [{ "type": "file", "id": "389047572" }, { "type": "file", "id": "389047578" }], "folder": { "id": "2233212", "type": "folder" }, "outcomes": [ { "id": "34895783", "type": "outcome", "task_collaborators": { "type": "variable", "variable_type": "user_list", "variable_value": [{ "type": "user", "id": "890273642" }] }, "completion_rule": { "type": "variable", "variable_type": "task_completion_rule", "variable_value": "all_assignees" }, "file_collaborator_role": { "type": "variable", "variable_type": "collaborator_role", "variable_value": "viewer" } } ] }' ``` ## Create Box Sign request ``` curl -i -X POST "https://api.box.com/2.0/sign_requests" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '{ "signers": [ { "role": "signer", "email": "example_email@box.com" } ], "source_files": [ { "type": "file", "id": "123456789" } ], "parent_folder": { "type": "folder", "id": "0987654321" } }' ``` ## Get Box Sign requests ``` curl -i -X GET "https://api.box.com/2.0/sign_requests" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Get Box Sign request by ID ``` curl -i -X GET "https://api.box.com/2.0/sign_requests/<SIGN_REQUEST_ID>" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Cancel Box Sign request ``` curl -i -X POST "https://api.box.com/2.0/sign_requests/<SIGN_REQUEST_ID>/cancel" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Resend Box Sign request ``` curl -i -X POST "https://api.box.com/2.0/sign_requests/<SIGN_REQUEST_ID>/resend" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Terminate user sessions ``` curl -i -X POST "https://api.box.com/2.0/users/terminate_sessions" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -H "accept: application/json" \ -d { user_ids: ["6178859178", "4824866571"] user_logins: ["user@example.com", "user2@example.com",] } ``` ## Terminate groups sessions ``` curl -i -X POST "https://api.box.com/2.0/groups/terminate_sessions" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -H "accept: application/json" \ -d {   "group_ids": ["6178859178", "4824866571"], } ``` ## List integration mappings Slack ``` curl -X -L GET "https://api.box.com/2.0/integration_mappings/slack?partner_item_id=C987654321&box_item_id=123456789" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ ``` ## Create integration mapping Slack ``` curl -X -L POST "https://api.box.com/2.0/integration_mappings/slack" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H 'content-type: application/json' \ -d '{ "partner_item": { "id": "C987654321", "type": "channel", "slack_workspace_id": "T5555555" }, "box_item": { "id": "123456789", "type": "folder" } }' ``` ## Update integration mapping Slack ``` curl -X -L PUT "https://api.box.com/2.0/integration_mappings/slack/512521" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H 'content-type: application/json' \ -d'{ "options": { "is_access_management_disabled": true } }' ``` ## Delete integration mapping Slack ``` curl -X -L DELETE "https://api.box.com/2.0/integration_mappings/slack/512521" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '' ``` ## Get Box Sign template by ID ``` curl -L -X GET "https://api.box.com/2.0/sign_templates/12345678" \ -H "accept: application/json" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ ``` ## Get Box Sign templates ``` curl -L -X GET "https://api.box.com/2.0/sign_templates?marker=JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii&limit=1000" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ ``` ## List integration mappings Teams ``` curl -X -L GET "https://api.box.com/2.0/integration_mappings/teams" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ ``` ## Create integration mapping Teams ``` curl -X -L POST "https://api.box.com/2.0/integration_mappings/teams" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H 'content-type: application/json' \ -d '{ "partner_item": { "id": "19%3ABCD-Avgfggkggyftdtfgghjhkhkhh%40thread:tacv2", "type": "channel", "team_id": "hjgjgjg-bhhj-564a-b643-hghgj685u", "tenant_id": "E1234567" }, "box_item": { "id": "42037322", "type": "folder" } }' ``` ## Update integration mapping Teams ``` curl -X -L PUT "https://api.box.com/2.0/integration_mappings/teams/12345" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H 'content-type: application/json' \ ``` ## Delete integration mapping Teams ``` curl -X -L DELETE "https://api.box.com/2.0/integration_mappings/teams/342423" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -d '' ``` ## Create archive ``` curl -i -X POST "https://api.box.com/2.0/archives" \ -H "box-version: 2025.0" \ -H "authorization: Bearer <ACCESS_TOKEN>" \ -H "content-type: application/json" \ -d '{ "name": "Some Archive Name" }' ``` ## List archives ``` curl -i -X GET "https://api.box.com/2.0/archives" \ -H "box-version: 2025.0" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` ## Delete archive ``` curl -i -X DELETE "https://api.box.com/2.0/archives/12345" \ -H "box-version: 2025.0" \ -H "authorization: Bearer <ACCESS_TOKEN>" ``` --- ## Untitled *Type: page* Documentation High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available… # Documentation ## High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available by topic: - [Ai](https://developer.box.com/fc42e321d2401ca0f6fe6f7e5ec20811/ai.md) - [Ai studio](https://developer.box.com/8822997d67c91efdef77e9832080d4e1/aiStudio.md) - [App item associations](https://developer.box.com/4034943d9e64ff39152dc3139f382930/appItemAssociations.md) - [Archives](https://developer.box.com/03c7bbda6842fb29e607240095f13bfd/archives.md) - [Authorization](https://developer.box.com/54db4bdfd48f3a6ec39ff167cf37866f/authorization.md) - [Avatars](https://developer.box.com/7c3b30e7558d2a2b891bff3612cf9c5a/avatars.md) - [Chunked uploads](https://developer.box.com/1bf542cbafed560ad041597c2e669b10/chunkedUploads.md) - [Classifications](https://developer.box.com/7cd4dee4c8a39f7c49339926c04a1727/classifications.md) - [Collaboration allowlist entries](https://developer.box.com/fefd69a7143c658da785ee8faf12e287/collaborationAllowlistEntries.md) - [Collaboration allowlist exempt targets](https://developer.box.com/786501d756036bb7e91c363f879c6bbf/collaborationAllowlistExemptTargets.md) - [Collections](https://developer.box.com/387abdb9c87dbbca0a7976c7e646f0bc/collections.md) - [Comments](https://developer.box.com/5d89e1ff5d912ce9d6080560dbadbc14/comments.md) - [Device pinners](https://developer.box.com/4ca72e5d948fc5485c6323931210c54d/devicePinners.md) - [Docgen](https://developer.box.com/2714459337fc73828d66b04638378a84/docgen.md) - [Docgen template](https://developer.box.com/ff7ab59ba903f6dc3bf5bd0548a55be3/docgenTemplate.md) - [Downloads](https://developer.box.com/80f4868fdb960ff18c3bba8461ccefbb/downloads.md) - [Email aliases](https://developer.box.com/ceaf283ee1976470bad67502d0c28b2d/emailAliases.md) - [Events](https://developer.box.com/f1850d50f91fe5198f93afe29989c943/events.md) - [File classifications](https://developer.box.com/167f08e301ea6c001265fba1e76c2c96/fileClassifications.md) - [File metadata](https://developer.box.com/94ee1bf2763b45f6153f538236dc1612/fileMetadata.md) - [File requests](https://developer.box.com/575355bac34130141841d217f6a657b0/fileRequests.md) - [File version legal holds](https://developer.box.com/4ef97fec6c26bafa9ce8404356a5149c/fileVersionLegalHolds.md) - [File version retentions](https://developer.box.com/b01b11eec48e9c775d002a333a1aa7c0/fileVersionRetentions.md) - [File versions](https://developer.box.com/7b8b55e23fff06d0b6bcad2d313caeea/fileVersions.md) - [File watermarks](https://developer.box.com/57cf27e58b81c4f89366758c08ba5447/fileWatermarks.md) - [Files](https://developer.box.com/aa3d852da4ce11a548a6d62adfdaa3b7/files.md) - [Folder classifications](https://developer.box.com/381e7a37b9c5e10f49114be777a6298c/folderClassifications.md) - [Folder locks](https://developer.box.com/8a8fc37fc424948206c922024d88b576/folderLocks.md) - [Folder metadata](https://developer.box.com/90c6a5cae9698e12462d169cd99fa132/folderMetadata.md) - [Folder watermarks](https://developer.box.com/89888806b209dd3b28963340156b9605/folderWatermarks.md) - [Folders](https://developer.box.com/8605da97a3a372ed9e2cad4a4ae42b15/folders.md) - [Groups](https://developer.box.com/9852d820fbf91c6823cd938abf5ff29b/groups.md) - [Hub collaborations](https://developer.box.com/58b33abec097635b202dc68d24c6c6aa/hubCollaborations.md) - [Hub items](https://developer.box.com/089a7a2d714ef7dac8f630856ba131c8/hubItems.md) - [Hubs](https://developer.box.com/06670926823945d5279e5d4cf62b91d1/hubs.md) - [Integration mappings](https://developer.box.com/ea609e4da1a3e8be97f5cd3d8bfc8ec7/integrationMappings.md) - [Invites](https://developer.box.com/570713a7f115e71ef94d2a31f91799d1/invites.md) - [Legal hold policies](https://developer.box.com/f3c35a6cf28e239368a70c608a3b5eeb/legalHoldPolicies.md) - [Legal hold policy assignments](https://developer.box.com/766e57e7ae862c1295aa97ebec2108e3/legalHoldPolicyAssignments.md) - [List collaborations](https://developer.box.com/460f4df77c97e7a9dfe2771e42552f41/listCollaborations.md) - [Memberships](https://developer.box.com/f9c0cc93abbed99477cb81bc2cee32f7/memberships.md) - [Metadata cascade policies](https://developer.box.com/9de5dfde89750a42b5bef529b8d2b473/metadataCascadePolicies.md) - [Metadata templates](https://developer.box.com/4b660eca31fb1d104018b476be30fc93/metadataTemplates.md) - [Recent items](https://developer.box.com/e8464b93cdec65c4240e9a81184537dd/recentItems.md) - [Retention policies](https://developer.box.com/4e5d789921f45688d198727e3c819442/retentionPolicies.md) - [Retention policy assignments](https://developer.box.com/2a31d25ec24ac3f250d27f7747c03e1b/retentionPolicyAssignments.md) - [Search](https://developer.box.com/c1f609590852cf05b33789df60c5a2a0/search.md) - [Session termination](https://developer.box.com/008b747050b6524e6f57d8171f0ee468/sessionTermination.md) - [Shared links app items](https://developer.box.com/b309bf564a6ff77fb7febda29f0450ae/sharedLinksAppItems.md) - [Shared links files](https://developer.box.com/63dbc250e82521bacec64f9131840628/sharedLinksFiles.md) - [Shared links folders](https://developer.box.com/f41a61a94c970f9780a93ebf59659dde/sharedLinksFolders.md) - [Shared links web links](https://developer.box.com/273993f9ac7054ef527aa10d984fcdf2/sharedLinksWebLinks.md) - [Shield information barrier reports](https://developer.box.com/3bc57ac1d4eaf4eca2d5d769ee84fdf1/shieldInformationBarrierReports.md) - [Shield information barrier segment members](https://developer.box.com/7519790d3212be1e03e5ea77974af8e6/shieldInformationBarrierSegmentMembers.md) - [Shield information barrier segment restrictions](https://developer.box.com/f0ec9d47cec408877261f55b58fc45e1/shieldInformationBarrierSegmentRestrictions.md) - [Shield information barrier segments](https://developer.box.com/41b908f45bb5085e90cd70d1ba67a542/shieldInformationBarrierSegments.md) - [Shield information barriers](https://developer.box.com/e3c23e60a043f54945a1dd9a63eb3852/shieldInformationBarriers.md) - [Shield lists](https://developer.box.com/4d261bc4440e84e5b99f721eeb2956cc/shieldLists.md) - [Sign requests](https://developer.box.com/07171b3c0c1cf0495a9aa54fa1c12c89/signRequests.md) - [Sign templates](https://developer.box.com/6e4e135ed584d32f8c8fcd3dfcf258fe/signTemplates.md) - [Skills](https://developer.box.com/2069b036c3e063717f1ba5c295b69369/skills.md) - [Storage policies](https://developer.box.com/9d06b1b430c4a84e5e11b5f3b8c3d472/storagePolicies.md) - [Storage policy assignments](https://developer.box.com/77a6621be0c09237fa869d5366ce04a1/storagePolicyAssignments.md) - [Task assignments](https://developer.box.com/fd631f75e820875193cccb1cb27e5617/taskAssignments.md) - [Tasks](https://developer.box.com/116e16a33227b329ae30ac6a68f9b316/tasks.md) - [Terms of service user statuses](https://developer.box.com/86f8d1fe48e9b4bc997a4dfdd1c5b578/termsOfServiceUserStatuses.md) - [Terms of services](https://developer.box.com/3f9018652046f755ba2c4f482bcec9c3/termsOfServices.md) - [Transfer](https://developer.box.com/127d549d1ccfa1875e86ee3d271060de/transfer.md) - [Trashed files](https://developer.box.com/f71fe80a773ee514f5867da629ca5d78/trashedFiles.md) - [Trashed folders](https://developer.box.com/c5e78e27035cfb6433141e273b307358/trashedFolders.md) - [Trashed items](https://developer.box.com/48aa1a5148c0149fffb3a64456a822f0/trashedItems.md) - [Trashed web links](https://developer.box.com/348ae3e1fa3897632a53b9ee47955033/trashedWebLinks.md) - [Uploads](https://developer.box.com/05b776ce26018b8d33b958a8ee419e8b/uploads.md) - [User collaborations](https://developer.box.com/250b562d65a6727f865a1395773d8104/userCollaborations.md) - [Users](https://developer.box.com/b2654a7dce5bf1ad888991ccd8496ab7/users.md) - [Web links](https://developer.box.com/eeb85371c138f2c0492fc01a22eb5424/webLinks.md) - [Webhooks](https://developer.box.com/b7cfc413355f7af7206ec4e1f9d71828/webhooks.md) - [Workflows](https://developer.box.com/d10e200014d42126c441e15bff385374/workflows.md) - [Zip downloads](https://developer.box.com/721efe8523b9cfa123495a1225868953/zipDownloads.md) --- ## Untitled *Type: page* AiStudioManager List AI agents Create AI agent Update AI agent Get AI agent by agent ID Delete AI agent List AI agents Lists AI agents based… # AiStudioManager - [List AI agents](#list-ai-agents) - [Create AI agent](#create-ai-agent) - [Update AI agent](#update-ai-agent) - [Get AI agent by agent ID](#get-ai-agent-by-agent-id) - [Delete AI agent](#delete-ai-agent) ## List AI agents Lists AI agents based on the provided parameters. This operation is performed by calling function `getAiAgents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents/). ``` await client.aiStudio.getAiAgents(); ``` ### Arguments queryParams `GetAiAgentsQueryParams` - Query parameters of getAiAgents method headersInput `GetAiAgentsHeadersInput` - Headers of getAiAgents method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `AiMultipleAgentResponse`. A successful response including the agents list. ## Create AI agent Creates an AI agent. At least one of the following capabilities must be provided: `ask`, `text_gen`, `extract`. This operation is performed by calling function `createAiAgent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-agents/). ``` await client.aiStudio.createAiAgent({ name: agentName, accessState: 'enabled', ask: new AiStudioAgentAsk({ accessState: 'enabled', description: 'desc1' }), } satisfies CreateAiAgentInput); ``` ### Arguments requestBodyInput `CreateAiAgentInput` - Request body of createAiAgent method optionalsInput `CreateAiAgentOptionalsInput` ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Update AI agent Updates an AI agent. This operation is performed by calling function `updateAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-ai-agents-id/). ``` await client.aiStudio.updateAiAgentById(createdAgent.id, { name: agentName, accessState: 'enabled', ask: new AiStudioAgentAsk({ accessState: 'disabled', description: 'desc2' }), } satisfies CreateAiAgentInput); ``` ### Arguments agentId `string` - The ID of the agent to update. Example: "1234" requestBodyInput `CreateAiAgentInput` - Request body of updateAiAgentById method optionalsInput `UpdateAiAgentByIdOptionalsInput` ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Get AI agent by agent ID Gets an AI Agent using the `agent_id` parameter. This operation is performed by calling function `getAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents-id/). ``` await client.aiStudio.getAiAgentById(createdAgent.id, { queryParams: { fields: ['ask'] } satisfies GetAiAgentByIdQueryParams, } satisfies GetAiAgentByIdOptionalsInput); ``` ### Arguments agentId `string` - The agent id to get. Example: "1234" optionalsInput `GetAiAgentByIdOptionalsInput` ### Returns This function returns a value of type `AiSingleAgentResponseFull`. A successful response including the agent. ## Delete AI agent Deletes an AI agent using the provided parameters. This operation is performed by calling function `deleteAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-ai-agents-id/). ``` await client.aiStudio.deleteAiAgentById(createdAgent.id); ``` ### Arguments agentId `string` - The ID of the agent to delete. Example: "1234" optionalsInput `DeleteAiAgentByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A successful response with no content. --- ## Untitled *Type: page* AiManager Ask question Generate text Get AI agent default configuration Extract metadata (freeform) Extract metadata (structured) Ask… # AiManager - [Ask question](#ask-question) - [Generate text](#generate-text) - [Get AI agent default configuration](#get-ai-agent-default-configuration) - [Extract metadata (freeform)](#extract-metadata-freeform) - [Extract metadata (structured)](#extract-metadata-structured) ## Ask question Sends an AI request to supported LLMs and returns an answer specifically focused on the user's question given the provided context. This operation is performed by calling function `createAiAsk`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-ask/). ``` await client.ai.createAiAsk({ mode: 'single_item_qa' as AiAskModeField, prompt: 'which direction sun rises', items: [ { id: fileToAsk.id, type: 'file' as AiItemAskTypeField, content: 'Sun rises in the East', } satisfies AiItemAsk, ], aiAgent: aiAskAgentConfig, } satisfies AiAsk); ``` ### Arguments requestBody `AiAsk` - Request body of createAiAsk method optionalsInput `CreateAiAskOptionalsInput` ### Returns This function returns a value of type `undefined | AiResponseFull`. A successful response including the answer from the LLM.No content is available to answer the question. This is returned when the request item is a hub, but content in the hubs is not indexed. To ensure content in the hub is indexed, make sure Box AI for Hubs in the Admin Console was enabled before hub creation. ## Generate text Sends an AI request to supported Large Language Models (LLMs) and returns generated text based on the provided prompt. This operation is performed by calling function `createAiTextGen`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-text-gen/). ``` await client.ai.createAiTextGen({ prompt: 'Parapharse the document.s', items: [ new AiTextGenItemsField({ id: fileToAsk.id, type: 'file' as AiTextGenItemsTypeField, content: 'The Earth goes around the sun. Sun rises in the East in the morning.', }), ], dialogueHistory: [ { prompt: 'What does the earth go around?', answer: 'The sun', createdAt: dateTimeFromString('2021-01-01T00:00:00Z'), } satisfies AiDialogueHistory, { prompt: 'On Earth, where does the sun rise?', answer: 'East', createdAt: dateTimeFromString('2021-01-01T00:00:00Z'), } satisfies AiDialogueHistory, ], aiAgent: aiTextGenAgentConfig, } satisfies AiTextGen); ``` ### Arguments requestBody `AiTextGen` - Request body of createAiTextGen method optionalsInput `CreateAiTextGenOptionalsInput` ### Returns This function returns a value of type `AiResponse`. A successful response including the answer from the LLM. ## Get AI agent default configuration Get the AI agent default config. This operation is performed by calling function `getAiAgentDefaultConfig`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agent-default/). ``` await client.ai.getAiAgentDefaultConfig({ mode: 'ask' as GetAiAgentDefaultConfigQueryParamsModeField, language: 'en-US', } satisfies GetAiAgentDefaultConfigQueryParams); ``` ### Arguments queryParams `GetAiAgentDefaultConfigQueryParams` - Query parameters of getAiAgentDefaultConfig method optionalsInput `GetAiAgentDefaultConfigOptionalsInput` ### Returns This function returns a value of type `AiAgentAskOrAiAgentExtractOrAiAgentExtractStructuredOrAiAgentTextGen`. A successful response including the default agent configuration. This response can be one of the following four objects: - AI agent for questions - AI agent for text generation - AI agent for freeform metadata extraction AI agent for structured metadata extraction. The response depends on the agent configuration requested in this endpoint. ## Extract metadata (freeform) Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of key-value pairs. In this request, both the prompt and the output can be freeform. Metadata template setup before sending the request is not required. This operation is performed by calling function `createAiExtract`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract/). ``` await client.ai.createAiExtract({ prompt: 'firstName, lastName, location, yearOfBirth, company', items: [new AiItemBase({ id: file.id })], aiAgent: agentIgnoringOverridingEmbeddingsModel, } satisfies AiExtract); ``` ### Arguments requestBody `AiExtract` - Request body of createAiExtract method optionalsInput `CreateAiExtractOptionalsInput` ### Returns This function returns a value of type `AiResponse`. A response including the answer from the LLM. ## Extract metadata (structured) Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. For this request, you either need a metadata template or a list of fields you want to extract. Input is **either** a metadata template or a list of fields to ensure the structure. To learn more about creating templates, see [Creating metadata templates in the Admin Console](https://support.box.com/hc/en-us/articles/360044194033-Customizing-Metadata-Templates) or use the [metadata template API](g://metadata/templates/create). This operation is performed by calling function `createAiExtractStructured`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract-structured/). ``` await client.ai.createAiExtractStructured({ fields: [ { key: 'firstName', displayName: 'First name', description: 'Person first name', prompt: 'What is the your first name?', type: 'string', } satisfies AiExtractStructuredFieldsField, { key: 'lastName', displayName: 'Last name', description: 'Person last name', prompt: 'What is the your last name?', type: 'string', } satisfies AiExtractStructuredFieldsField, { key: 'dateOfBirth', displayName: 'Birth date', description: 'Person date of birth', prompt: 'What is the date of your birth?', type: 'date', } satisfies AiExtractStructuredFieldsField, { key: 'age', displayName: 'Age', description: 'Person age', prompt: 'How old are you?', type: 'float', } satisfies AiExtractStructuredFieldsField, { key: 'hobby', displayName: 'Hobby', description: 'Person hobby', prompt: 'What is your hobby?', type: 'multiSelect', options: [ { key: 'guitar' } satisfies AiExtractStructuredFieldsOptionsField, { key: 'books' } satisfies AiExtractStructuredFieldsOptionsField, ], } satisfies AiExtractStructuredFieldsField, ], items: [new AiItemBase({ id: file.id })], aiAgent: agentIgnoringOverridingEmbeddingsModel, } satisfies AiExtractStructured); ``` ### Arguments requestBody `AiExtractStructured` - Request body of createAiExtractStructured method optionalsInput `CreateAiExtractStructuredOptionalsInput` ### Returns This function returns a value of type `AiExtractStructuredResponse`. A successful response including the answer from the LLM. --- ## Untitled *Type: page* ArchivesManager List archives Create archive Delete archive List archives Retrieves archives for an enterprise. This operation is performed… # ArchivesManager - [List archives](#list-archives) - [Create archive](#create-archive) - [Delete archive](#delete-archive) ## List archives Retrieves archives for an enterprise. This operation is performed by calling function `getArchivesV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-archives/). ``` await client.archives.getArchivesV2025R0({ limit: 100, } satisfies GetArchivesV2025R0QueryParams); ``` ### Arguments queryParams `GetArchivesV2025R0QueryParams` - Query parameters of getArchivesV2025R0 method headersInput `GetArchivesV2025R0HeadersInput` - Headers of getArchivesV2025R0 method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `ArchivesV2025R0`. Returns a list of archives in the enterprise. ## Create archive Creates an archive. This operation is performed by calling function `createArchiveV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-archives/). ``` await client.archives.createArchiveV2025R0({ name: archiveName, } satisfies CreateArchiveV2025R0RequestBody); ``` ### Arguments requestBody `CreateArchiveV2025R0RequestBody` - Request body of createArchiveV2025R0 method optionalsInput `CreateArchiveV2025R0OptionalsInput` ### Returns This function returns a value of type `ArchiveV2025R0`. Returns a new archive object. ## Delete archive Permanently deletes an archive. This operation is performed by calling function `deleteArchiveByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-archives-id/). ``` await client.archives.deleteArchiveByIdV2025R0(archive.id); ``` ### Arguments archiveId `string` - The ID of the archive. Example: "982312" optionalsInput `DeleteArchiveByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the archive has been deleted. --- ## Untitled *Type: page* AppItemAssociationsManager List file app item associations List folder app item associations List file app item associations This is a beta… # AppItemAssociationsManager - [List file app item associations](#list-file-app-item-associations) - [List folder app item associations](#list-folder-app-item-associations) ## List file app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the file is associated with. This includes app items associated with ancestors of the file. Assuming the context user has access to the file, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `getFileAppItemAssociations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-app-item-associations/). ``` await client.appItemAssociations.getFileAppItemAssociations(fileId); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetFileAppItemAssociationsOptionalsInput` ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this file, an empty collection will be returned. This list includes app items on ancestors of this File. ## List folder app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the folder is associated with. This includes app items associated with ancestors of the folder. Assuming the context user has access to the folder, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `getFolderAppItemAssociations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-app-item-associations/). ``` await client.appItemAssociations.getFolderAppItemAssociations(folderId); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `GetFolderAppItemAssociationsOptionalsInput` ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this folder an empty collection will be returned. This list includes app items on ancestors of this folder. --- ## Untitled *Type: page* AuthorizationManager Authorize user Request access token Refresh access token Revoke access token Authorize user Authorize a user by sending… # AuthorizationManager - [Authorize user](#authorize-user) - [Request access token](#request-access-token) - [Refresh access token](#refresh-access-token) - [Revoke access token](#revoke-access-token) ## Authorize user Authorize a user by sending them through the [Box](https://box.com) website and request their permission to act on their behalf. This is the first step when authenticating a user using OAuth 2.0. To request a user's authorization to use the Box APIs on their behalf you will need to send a user to the URL with this format. This operation is performed by calling function `authorizeUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-authorize/). *Currently we don't have an example for calling `authorizeUser` in integration tests* ### Arguments queryParams `AuthorizeUserQueryParams` - Query parameters of authorizeUser method optionalsInput `AuthorizeUserOptionalsInput` ### Returns This function returns a value of type `undefined`. Does not return any data, but rather should be used in the browser. ## Request access token Request an Access Token using either a client-side obtained OAuth 2.0 authorization code or a server-side JWT assertion. An Access Token is a string that enables Box to verify that a request belongs to an authorized session. In the normal order of operations you will begin by requesting authentication from the [authorize](#get-authorize) endpoint and Box will send you an authorization code. You will then send this code to this endpoint to exchange it for an Access Token. The returned Access Token can then be used to to make Box API calls. This operation is performed by calling function `requestAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token/). *Currently we don't have an example for calling `requestAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2Token` - Request body of requestAccessToken method optionalsInput `RequestAccessTokenOptionalsInput` ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Refresh access token Refresh an Access Token using its client ID, secret, and refresh token. This operation is performed by calling function `refreshAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token--refresh/). *Currently we don't have an example for calling `refreshAccessToken` in integration tests* ### Arguments requestBodyInput `PostOAuth2TokenRefreshAccessTokenInput` - Request body of refreshAccessToken method optionalsInput `RefreshAccessTokenOptionalsInput` ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Revoke access token Revoke an active Access Token, effectively logging a user out that has been previously authenticated. This operation is performed by calling function `revokeAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-revoke/). *Currently we don't have an example for calling `revokeAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2Revoke` - Request body of revokeAccessToken method optionalsInput `RevokeAccessTokenOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the token was successfully revoked. --- ## Untitled *Type: page* AvatarsManager Get user avatar Add or update user avatar Delete user avatar Get user avatar Retrieves an image of a the user's avatar. This… # AvatarsManager - [Get user avatar](#get-user-avatar) - [Add or update user avatar](#add-or-update-user-avatar) - [Delete user avatar](#delete-user-avatar) ## Get user avatar Retrieves an image of a the user's avatar. This operation is performed by calling function `getUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-avatar/). ``` await client.avatars.getUserAvatar(user.id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" optionalsInput `GetUserAvatarOptionalsInput` ### Returns This function returns a value of type `ByteStream`. When an avatar can be found for the user the image data will be returned in the body of the response. ## Add or update user avatar Adds or updates a user avatar. This operation is performed by calling function `createUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-avatar/). ``` await client.avatars.createUserAvatar(user.id, { pic: decodeBase64ByteStream( 'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg==', ), picContentType: 'image/png', picFileName: 'avatar.png', } satisfies CreateUserAvatarRequestBody); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" requestBody `CreateUserAvatarRequestBody` - Request body of createUserAvatar method optionalsInput `CreateUserAvatarOptionalsInput` ### Returns This function returns a value of type `UserAvatar`. `ok`: Returns the `pic_urls` object with URLs to existing user avatars that were updated.`created`: Returns the `pic_urls` object with URLS to user avatars uploaded to Box with the request. ## Delete user avatar Removes an existing user avatar. You cannot reverse this operation. This operation is performed by calling function `deleteUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-avatar/). ``` await client.avatars.deleteUserAvatar(user.id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" optionalsInput `DeleteUserAvatarOptionalsInput` ### Returns This function returns a value of type `undefined`. `no_content`: Removes the avatar and returns an empty response. --- ## Untitled *Type: page* Authentication Authentication Authentication methods Developer Token JWT Auth Authenticate Enterprise Authenticate user Client Credentials… # Authentication - [Authentication](#authentication) [Authentication methods](#authentication-methods) - [Developer Token](#developer-token) [JWT Auth](#jwt-auth) - [Authenticate Enterprise](#authenticate-enterprise) - [Authenticate user](#authenticate-user) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) - [Switching between Service Account and User](#switching-between-service-account-and-user) [OAuth 2.0 Auth](#oauth-20-auth) - [Authentication with OAuth2](#authentication-with-oauth2) - [Injecting existing token into BoxOAuth](#injecting-existing-token-into-boxoauth) [Retrieve current access token](#retrieve-current-access-token) [Refresh access token](#refresh-access-token) [Revoke token](#revoke-token) [Downscope token](#downscope-token) [Token storage](#token-storage) - [In-memory token storage](#in-memory-token-storage) - [Custom storage](#custom-storage) # Authentication methods ## Developer Token The fastest way to get started using the API is with developer token. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. To create a `BoxClient` with a developer token, construct an `BoxDeveloperTokenAuth` object with the `token` set to the developer token and construct the client with that. ``` import { BoxClient } from 'box-typescript-sdk-gen/client.generated'; import { BoxDeveloperTokenAuth } from 'box-typescript-sdk-gen/box/developerTokenAuth.generated'; const auth = new BoxDeveloperTokenAuth({ token: 'DEVELOPER_TOKEN_GOES_HERE' }); const client = new BoxClient({ auth }); const me = await client.users.getUserMe(); console.log(`My user ID is ${me.id}`); ``` ## JWT Auth Before using JWT Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with JWT](https://developer.box.com/guides/authentication/jwt/jwt-setup/) ### Authenticate Enterprise JWT auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. If you generated your public and private keys automatically through the [Box Developer Console](https://app.box.com/developers/console), you can use the JSON file created there to configure your SDK instance and create a client to make calls as the Service Account. Call one of static `BoxJwtAuth` method: `JwtConfig.fromConfigFile(configFilePath)` and pass JSON file local path or `JwtConfig.fromConfigJsonString(configJsonString)` and pass JSON config file content as string. ``` import { BoxClient } from 'box-typescript-sdk-gen/client.generated'; import { BoxJwtAuth, JwtConfig, } from 'box-typescript-sdk-gen/box/jwtAuth.generated'; const jwtConfig = JwtConfig.fromConfigFile('/path/to/settings.json'); const jwtAuth = new BoxJwtAuth({ config: jwtConfig }); const client = new BoxClient({ auth: jwtAuth }); const me = await client.users.getUserMe(); console.log(`My user ID is ${me.id}`); ``` Otherwise, you'll need to provide the necessary configuration fields directly to the `JwtConfig` constructor: ``` import { BoxClient } from 'box-typescript-sdk-gen/client.generated'; import { BoxJwtAuth, JwtConfig, } from 'box-typescript-sdk-gen/box/jwtAuth.generated'; const jwtConfig = new JwtConfig({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', jwtKeyId: 'YOUR_JWT_KEY_ID', privateKey: 'YOUR_PRIVATE_KEY', privateKeyPassphrase: 'PASSPHRASE', enterpriseId: 'YOUR_ENTERPRISE_ID', }); const jwtAuth = new BoxJwtAuth({ config: jwtConfig }); const serviceAccountClient = new BoxClient({ auth: jwtAuth }); ``` ### Authenticate user App auth applications also often have associated [App Users](https://developer.box.com/guides/getting-started/user-types/app-users/), which are created and managed directly by the application — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user to make calls as that user. See the [API documentation](https://developer.box.com/) for detailed instructions on how to use app auth. Clients for making calls as an App User can be created with the same JSON JWT config file generated through the [Box Developer Console](https://app.box.com/developers/console). Calling `jwtAuth.withUserSubject('USER_ID')` method will return a new auth object, which is authenticated as the user with provided id, leaving the original object unchanged. ``` import { BoxClient } from 'box-typescript-sdk-gen/client.generated'; import { BoxJwtAuth, JwtConfig, } from 'box-typescript-sdk-gen/box/jwtAuth.generated'; const jwtConfig = JwtConfig.fromConfigFile('/path/to/settings.json'); const jwtAuth = new BoxJwtAuth({ config: jwtConfig }); const userAuth = jwtAuth.withUserSubject('USER_ID'); const userClient = new BoxClient({ auth: userAuth }); ``` Alternatively, clients for making calls as an App User can be created with the same `JwtConfig` constructor as in the above examples, similarly to creating a Service Account client. Simply pass the `userId` instead of `enterpriseId` when constructing the auth config instance: ``` import { BoxClient } from 'box-typescript-sdk-gen/client.generated'; import { BoxJwtAuth, JwtConfig, } from 'box-typescript-sdk-gen/box/jwtAuth.generated'; const jwtConfig = new JwtConfig({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', jwtKeyId: 'YOUR_JWT_KEY_ID', privateKey: 'YOUR_PRIVATE_KEY', privateKeyPassphrase: 'PASSPHRASE', userId: 'USER_ID', }); const jwtAuth = new BoxJwtAuth({ config: jwtConfig }); const userClient = new BoxClient({ auth: jwtAuth }); ``` ## Client Credentials Grant Before using Client Credentials Grant Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with Client Credentials Grant](https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/) Client Credentials Grant Auth method allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account. You can use `CCGAuth` to initialize a client object the same way as for other authentication types: ``` import { BoxClient } from 'box-typescript-sdk-gen/client.generated'; import { BoxCcgAuth, CcgConfig, } from 'box-typescript-sdk-gen/box/ccgAuth.generated'; const ccgConfig = new CcgConfig({ userId: 'YOUR_USER_ID', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }); const ccgAuth = new BoxCcgAuth({ config: ccgConfig }); const client = new BoxClient({ auth: ccgAuth }); const me = await client.users.getUserMe(); console.log(`My user ID is ${me.id}`); ``` Obtained token is valid for specified amount of time, it will be refreshed automatically by default. ### Obtaining Service Account token The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID with client id and secret: ``` import { BoxClient } from 'box-typescript-sdk-gen/client.generated'; import { BoxCcgAuth, CcgConfig, } from 'box-typescript-sdk-gen/box/ccgAuth.generated'; const ccgConfig = new CcgConfig({ enterpriseId: 'YOUR_ENTERPRISE_ID', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }); const ccgAuth = new BoxCcgAuth({ config: ccgConfig }); const client = new BoxClient({ auth: ccgAuth }); ``` ### Obtaining User token In order to enable obtaining user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/console). In `Configuration` tab, in section `Advanced Features` select `Generate user access tokens`. Do not forget to re-authorize application if it was already authorized. To obtain user account you will have to provide user ID with client id and secret. ``` import { BoxClient } from 'box-typescript-sdk-gen/client.generated'; import { BoxCcgAuth, CcgConfig, } from 'box-typescript-sdk-gen/box/ccgAuth.generated'; const ccgConfig = new CcgConfig({ userId: 'YOUR_USER_ID', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }); const ccgAuth = new BoxCcgAuth({ config: ccgConfig }); const client = new BoxClient({ auth: ccgAuth }); ``` ### Switching between Service Account and User You can easily switch to be authenticated as a Service Account or as a User. To create a new auth object authenticated as Service Account you can call: ``` const enterpriseAuth = ccgAuth.withEnterpriseSubject('YOUR_ENTERPRISE_ID'); const enterpriseClient = new BoxClient({ auth: enterpriseAuth }); ``` To authenticate with user subject call: ``` const userAuth = ccgAuth.withUserSubject('YOUR_USER_ID'); const userClient = new BoxClient({ auth: userAuth }); ``` The new token will be automatically fetched with a next API call. ## OAuth 2.0 Auth ### Authentication with OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/en/guides/authentication/oauth2/). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code. ``` import { BoxOAuth, OAuthConfig, } from 'box-typescript-sdk-gen/box/oauth.generated'; const config = new OAuthConfig({ clientId: 'OAUTH_CLIENT_ID', clientSecret: 'OAUTH_CLIENT_SECRET', }); const oauth = new BoxOAuth({ config: config }); // the URL to redirect the user to var authorize_url = oauth.getAuthorizeUrl(); ``` After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirect_uri` which will contain an auth code. This auth code can then be used along with your client ID and client secret to establish an API connection. You need to provide the auth code to the SDK to obtain an access token. Calling `oauth.getTokensAuthorizationCodeGrant('code')` will exchange the auth code for an access token and save it in the `BoxOAuth` token storage. The SDK will automatically refresh the token when needed. All you need to do is create a client object with the `BoxOAuth` object and start making API calls. ``` await auth.retrieveToken(); ``` # Refresh access token Access tokens are short-lived and need to be refreshed periodically. The SDK will automatically refresh the token when needed. If you want to manually refresh the token, you can use the following code: ``` await auth.refreshToken(); ``` # Revoke token Access tokens for a client can be revoked when needed. This call invalidates old token. For BoxCcgAuth and BoxJwtAuth you can still reuse the `auth` object to retrieve a new token. If you make any new call after revoking the token, a new token will be automatically retrieved. For BoxOAuth it would be necessary to manually go through the authentication process again. For BoxDeveloperTokenAuth, it is necessary to provide a DeveloperTokenConfig during initialization, containing the client ID and client secret. To revoke current client's tokens in the storage use the following code: ``` await auth.revokeTokens(); // client's tokens have been revoked ``` # Downscope token You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). A downscoped token does not include a refresh token. In such a scenario, to obtain a new downscoped token, refresh the original token and utilize the newly acquired token to obtain the downscoped token. More information about downscoping tokens can be found [here](https://developer.box.com/guides/authentication/tokens/downscope/). If you want to learn more about available scopes please go [here](https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/#scopes-for-downscoping). For example to get a new token with only `item_preview` scope, restricted to a single file, suitable for the [Content Preview UI Element](https://developer.box.com/en/guides/embed/ui-elements/preview/) you can use the following code. You can also initialize `BoxDeveloperTokenAuth` with the retrieved access token and use it to create a new Client. ``` let resource = 'https://api.box.com/2.0/files/123456789'; let token = await oauth.downscopeToken(['item_preview'], resource); const auth = new BoxDeveloperTokenAuth({ token: token.accessToken }); const client = new BoxClient({ auth }); ``` # Token storage ## In-memory token storage By default, the SDK stores the access token in volatile memory. When rerunning your application, the access token won't be reused from the previous run; a new token has to be obtained again. To use in-memory token storage, you don't need to do anything more than create an Auth class using AuthConfig, for example, for OAuth: ``` const config = new OAuthConfig({ clientId: 'OAUTH_CLIENT_ID', clientSecret: 'OAUTH_CLIENT_SECRET', }); const oauth = new BoxOAuth({ config: config }); ``` ## Custom storage You can also provide a custom token storage class. All you need to do is create a class that implements `TokenStorage` interface and pass an instance of your class to the AuthConfig constructor. ``` class MyCustomTokenStorage implements TokenStorage { async store(token: AccessToken): Promise<undefined> { // store token in your custom storage } async get(): Promise<undefined | AccessToken> { // retrieve token from your custom storage } async clear(): Promise<undefined> { // clear token from your custom storage } } const config = new OAuthConfig({ clientId: 'OAUTH_CLIENT_ID', clientSecret: 'OAUTH_CLIENT_SECRET', tokenStorage: new MyCustomTokenStorage(), }); const oauth = new BoxOAuth({ config: config }); ``` --- ## Untitled *Type: page* ClassificationsManager List all classifications Add classification Update classification Add initial classifications List all… # ClassificationsManager - [List all classifications](#list-all-classifications) - [Add classification](#add-classification) - [Update classification](#update-classification) - [Add initial classifications](#add-initial-classifications) ## List all classifications Retrieves the classification metadata template and lists all the classifications available to this enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `getClassificationTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema/). ``` await client.classifications.getClassificationTemplate(); ``` ### Arguments headersInput `GetClassificationTemplateHeadersInput` - Headers of getClassificationTemplate method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `ClassificationTemplate`. Returns the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification Adds one or more new classifications to the list of classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `addClassification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--add/). ``` await client.classifications.addClassification([ new AddClassificationRequestBody({ data: { key: getUuid(), staticConfig: { classification: { colorId: 4, classificationDefinition: 'Other description', } satisfies AddClassificationRequestBodyDataStaticConfigClassificationField, } satisfies AddClassificationRequestBodyDataStaticConfigField, } satisfies AddClassificationRequestBodyDataField, }), ]); ``` ### Arguments requestBody `readonly AddClassificationRequestBody[]` - Request body of addClassification method optionalsInput `AddClassificationOptionalsInput` ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Update classification Updates the labels and descriptions of one or more classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `updateClassification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--update/). ``` await client.classifications.updateClassification([ new UpdateClassificationRequestBody({ enumOptionKey: classification.key, data: { key: updatedClassificationName, staticConfig: { classification: { colorId: 2, classificationDefinition: updatedClassificationDescription, } satisfies UpdateClassificationRequestBodyDataStaticConfigClassificationField, } satisfies UpdateClassificationRequestBodyDataStaticConfigField, } satisfies UpdateClassificationRequestBodyDataField, }), ]); ``` ### Arguments requestBody `readonly UpdateClassificationRequestBody[]` - Request body of updateClassification method optionalsInput `UpdateClassificationOptionalsInput` ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add initial classifications When an enterprise does not yet have any classifications, this API call initializes the classification template with an initial set of classifications. If an enterprise already has a classification, the template will already exist and instead an API call should be made to add additional classifications. This operation is performed by calling function `createClassificationTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema--classifications/). *Currently we don't have an example for calling `createClassificationTemplate` in integration tests* ### Arguments requestBodyInput `CreateClassificationTemplateRequestBodyInput` - Request body of createClassificationTemplate method optionalsInput `CreateClassificationTemplateOptionalsInput` ### Returns This function returns a value of type `ClassificationTemplate`. Returns a new `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. --- ## Untitled *Type: page* CollaborationAllowlistEntriesManager List allowed collaboration domains Add domain to list of allowed collaboration domains Get allowed… # CollaborationAllowlistEntriesManager - [List allowed collaboration domains](#list-allowed-collaboration-domains) - [Add domain to list of allowed collaboration domains](#add-domain-to-list-of-allowed-collaboration-domains) - [Get allowed collaboration domain](#get-allowed-collaboration-domain) - [Remove domain from list of allowed collaboration domains](#remove-domain-from-list-of-allowed-collaboration-domains) ## List allowed collaboration domains Returns the list domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `getCollaborationWhitelistEntries`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries/). ``` await client.collaborationAllowlistEntries.getCollaborationWhitelistEntries(); ``` ### Arguments queryParams `GetCollaborationWhitelistEntriesQueryParams` - Query parameters of getCollaborationWhitelistEntries method headersInput `GetCollaborationWhitelistEntriesHeadersInput` - Headers of getCollaborationWhitelistEntries method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationAllowlistEntries`. Returns a collection of domains that are allowed for collaboration. ## Add domain to list of allowed collaboration domains Creates a new entry in the list of allowed domains to allow collaboration for. This operation is performed by calling function `createCollaborationWhitelistEntry`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-entries/). ``` await client.collaborationAllowlistEntries.createCollaborationWhitelistEntry({ direction: 'inbound' as CreateCollaborationWhitelistEntryRequestBodyDirectionField, domain: domain, } satisfies CreateCollaborationWhitelistEntryRequestBody); ``` ### Arguments requestBody `CreateCollaborationWhitelistEntryRequestBody` - Request body of createCollaborationWhitelistEntry method optionalsInput `CreateCollaborationWhitelistEntryOptionalsInput` ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns a new entry on the list of allowed domains. ## Get allowed collaboration domain Returns a domain that has been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `getCollaborationWhitelistEntryById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries-id/). ``` await client.collaborationAllowlistEntries.getCollaborationWhitelistEntryById( newEntry.id!, ); ``` ### Arguments collaborationWhitelistEntryId `string` - The ID of the entry in the list. Example: "213123" optionalsInput `GetCollaborationWhitelistEntryByIdOptionalsInput` ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns an entry on the list of allowed domains. ## Remove domain from list of allowed collaboration domains Removes a domain from the list of domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `deleteCollaborationWhitelistEntryById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-entries-id/). ``` await client.collaborationAllowlistEntries.deleteCollaborationWhitelistEntryById( entry.id!, ); ``` ### Arguments collaborationWhitelistEntryId `string` - The ID of the entry in the list. Example: "213123" optionalsInput `DeleteCollaborationWhitelistEntryByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the entry was successfully deleted. --- ## Untitled *Type: page* CollectionsManager List all collections List collection items Get collection by ID List all collections Retrieves all collections for a… # CollectionsManager - [List all collections](#list-all-collections) - [List collection items](#list-collection-items) - [Get collection by ID](#get-collection-by-id) ## List all collections Retrieves all collections for a given user. Currently, only the `favorites` collection is supported. This operation is performed by calling function `getCollections`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections/). ``` await client.collections.getCollections(); ``` ### Arguments queryParams `GetCollectionsQueryParams` - Query parameters of getCollections method headersInput `GetCollectionsHeadersInput` - Headers of getCollections method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `Collections`. Returns all collections for the given user. ## List collection items Retrieves the files and/or folders contained within this collection. This operation is performed by calling function `getCollectionItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id-items/). ``` await client.collections.getCollectionItems(favouriteCollection.id!); ``` ### Arguments collectionId `string` - The ID of the collection. Example: "926489" optionalsInput `GetCollectionItemsOptionalsInput` ### Returns This function returns a value of type `ItemsOffsetPaginated`. Returns an array of items in the collection. ## Get collection by ID Retrieves a collection by its ID. This operation is performed by calling function `getCollectionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id/). ``` await client.collections.getCollectionById(collections.entries![0].id!); ``` ### Arguments collectionId `string` - The ID of the collection. Example: "926489" optionalsInput `GetCollectionByIdOptionalsInput` ### Returns This function returns a value of type `Collection`. Returns an array of items in the collection. --- ## Untitled *Type: page* ChunkedUploadsManager This is a manager for chunked uploads (allowed for files at least 20MB). Create upload session Create upload session… # ChunkedUploadsManager This is a manager for chunked uploads (allowed for files at least 20MB). - [Create upload session](#create-upload-session) - [Create upload session for existing file](#create-upload-session-for-existing-file) - [Get upload session by URL](#get-upload-session-by-url) - [Get upload session](#get-upload-session) - [Upload part of file by URL](#upload-part-of-file-by-url) - [Upload part of file](#upload-part-of-file) - [Remove upload session by URL](#remove-upload-session-by-url) - [Remove upload session](#remove-upload-session) - [List parts by URL](#list-parts-by-url) - [List parts](#list-parts) - [Commit upload session by URL](#commit-upload-session-by-url) - [Commit upload session](#commit-upload-session) - [Upload big file](#upload-big-file) ## Create upload session Creates an upload session for a new file. This operation is performed by calling function `createFileUploadSession`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions/). ``` await client.chunkedUploads.createFileUploadSession({ fileName: fileName, fileSize: fileSize, folderId: parentFolderId, } satisfies CreateFileUploadSessionRequestBody); ``` ### Arguments requestBody `CreateFileUploadSessionRequestBody` - Request body of createFileUploadSession method optionalsInput `CreateFileUploadSessionOptionalsInput` ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Create upload session for existing file Creates an upload session for an existing file. This operation is performed by calling function `createFileUploadSessionForExistingFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-upload-sessions/). *Currently we don't have an example for calling `createFileUploadSessionForExistingFile` in integration tests* ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CreateFileUploadSessionForExistingFileRequestBody` - Request body of createFileUploadSessionForExistingFile method optionalsInput `CreateFileUploadSessionForExistingFileOptionalsInput` ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Get upload session by URL Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `getFileUploadSessionByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` await client.chunkedUploads.getFileUploadSessionByUrl(statusUrl); ``` ### Arguments url `string` - URL of getFileUploadSessionById method optionalsInput `GetFileUploadSessionByUrlOptionalsInput` ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Get upload session Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `getFileUploadSessionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` await client.chunkedUploads.getFileUploadSessionById(uploadSessionId); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" optionalsInput `GetFileUploadSessionByIdOptionalsInput` ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Upload part of file by URL Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `uploadFilePartByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` await client.chunkedUploads.uploadFilePartByUrl( acc.uploadPartUrl, generateByteStreamFromBuffer(chunkBuffer), { digest: digest, contentRange: contentRange, } satisfies UploadFilePartByUrlHeadersInput, ); ``` ### Arguments url `string` - URL of uploadFilePart method requestBody `ByteStream` - Request body of uploadFilePart method headersInput `UploadFilePartByUrlHeadersInput` - Headers of uploadFilePart method optionalsInput `UploadFilePartByUrlOptionalsInput` ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Upload part of file Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `uploadFilePart`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` await client.chunkedUploads.uploadFilePart( acc.uploadSessionId, generateByteStreamFromBuffer(chunkBuffer), { digest: digest, contentRange: contentRange, } satisfies UploadFilePartHeadersInput, ); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" requestBody `ByteStream` - Request body of uploadFilePart method headersInput `UploadFilePartHeadersInput` - Headers of uploadFilePart method optionalsInput `UploadFilePartOptionalsInput` ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Remove upload session by URL Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `deleteFileUploadSessionByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` await client.chunkedUploads.deleteFileUploadSessionByUrl(abortUrl); ``` ### Arguments url `string` - URL of deleteFileUploadSessionById method optionalsInput `DeleteFileUploadSessionByUrlOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the session was successfully aborted. ## Remove upload session Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `deleteFileUploadSessionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` await client.chunkedUploads.deleteFileUploadSessionById(uploadSessionId); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" optionalsInput `DeleteFileUploadSessionByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the session was successfully aborted. ## List parts by URL Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `getFileUploadSessionPartsByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` await client.chunkedUploads.getFileUploadSessionPartsByUrl(listPartsUrl); ``` ### Arguments url `string` - URL of getFileUploadSessionParts method optionalsInput `GetFileUploadSessionPartsByUrlOptionalsInput` ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## List parts Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `getFileUploadSessionParts`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` await client.chunkedUploads.getFileUploadSessionParts(uploadSessionId); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" optionalsInput `GetFileUploadSessionPartsOptionalsInput` ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## Commit upload session by URL Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `createFileUploadSessionCommitByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` await client.chunkedUploads.createFileUploadSessionCommitByUrl( commitUrl, { parts: parts } satisfies CreateFileUploadSessionCommitByUrlRequestBody, { digest: digest } satisfies CreateFileUploadSessionCommitByUrlHeadersInput, ); ``` ### Arguments url `string` - URL of createFileUploadSessionCommit method requestBody `CreateFileUploadSessionCommitByUrlRequestBody` - Request body of createFileUploadSessionCommit method headersInput `CreateFileUploadSessionCommitByUrlHeadersInput` - Headers of createFileUploadSessionCommit method optionalsInput `CreateFileUploadSessionCommitByUrlOptionalsInput` ### Returns This function returns a value of type `undefined | Files`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Commit upload session Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `createFileUploadSessionCommit`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` await client.chunkedUploads.createFileUploadSessionCommit( uploadSessionId, { parts: parts } satisfies CreateFileUploadSessionCommitRequestBody, { digest: digest } satisfies CreateFileUploadSessionCommitHeadersInput, ); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" requestBody `CreateFileUploadSessionCommitRequestBody` - Request body of createFileUploadSessionCommit method headersInput `CreateFileUploadSessionCommitHeadersInput` - Headers of createFileUploadSessionCommit method optionalsInput `CreateFileUploadSessionCommitOptionalsInput` ### Returns This function returns a value of type `undefined | Files`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Upload big file Starts the process of chunk uploading a big file. Should return a File object representing uploaded file. This operation is performed by calling function `uploadBigFile`. ``` await client.chunkedUploads.uploadBigFile( fileByteStream, fileName, fileSize, parentFolderId, ); ``` ### Arguments file `ByteStream` - The stream of the file to upload. fileName `string` - The name of the file, which will be used for storage in Box. fileSize `number` - The total size of the file for the chunked upload in bytes. parentFolderId `string` - The ID of the folder where the file should be uploaded. cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. --- ## Untitled *Type: page* CollaborationAllowlistExemptTargetsManager List users exempt from collaboration domain restrictions Create user exemption from collaboration… # CollaborationAllowlistExemptTargetsManager - [List users exempt from collaboration domain restrictions](#list-users-exempt-from-collaboration-domain-restrictions) - [Create user exemption from collaboration domain restrictions](#create-user-exemption-from-collaboration-domain-restrictions) - [Get user exempt from collaboration domain restrictions](#get-user-exempt-from-collaboration-domain-restrictions) - [Remove user from list of users exempt from domain restrictions](#remove-user-from-list-of-users-exempt-from-domain-restrictions) ## List users exempt from collaboration domain restrictions Returns a list of users who have been exempt from the collaboration domain restrictions. This operation is performed by calling function `getCollaborationWhitelistExemptTargets`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets/). ``` await client.collaborationAllowlistExemptTargets.getCollaborationWhitelistExemptTargets(); ``` ### Arguments queryParams `GetCollaborationWhitelistExemptTargetsQueryParams` - Query parameters of getCollaborationWhitelistExemptTargets method headersInput `GetCollaborationWhitelistExemptTargetsHeadersInput` - Headers of getCollaborationWhitelistExemptTargets method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationAllowlistExemptTargets`. Returns a collection of user exemptions. ## Create user exemption from collaboration domain restrictions Exempts a user from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `createCollaborationWhitelistExemptTarget`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-exempt-targets/). ``` await client.collaborationAllowlistExemptTargets.createCollaborationWhitelistExemptTarget( { user: { id: user.id, } satisfies CreateCollaborationWhitelistExemptTargetRequestBodyUserField, } satisfies CreateCollaborationWhitelistExemptTargetRequestBody, ); ``` ### Arguments requestBody `CreateCollaborationWhitelistExemptTargetRequestBody` - Request body of createCollaborationWhitelistExemptTarget method optionalsInput `CreateCollaborationWhitelistExemptTargetOptionalsInput` ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns a new exemption entry. ## Get user exempt from collaboration domain restrictions Returns a users who has been exempt from the collaboration domain restrictions. This operation is performed by calling function `getCollaborationWhitelistExemptTargetById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets-id/). ``` await client.collaborationAllowlistExemptTargets.getCollaborationWhitelistExemptTargetById( newExemptTarget.id!, ); ``` ### Arguments collaborationWhitelistExemptTargetId `string` - The ID of the exemption to the list. Example: "984923" optionalsInput `GetCollaborationWhitelistExemptTargetByIdOptionalsInput` ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns the user's exempted from the list of collaboration domains. ## Remove user from list of users exempt from domain restrictions Removes a user's exemption from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `deleteCollaborationWhitelistExemptTargetById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-exempt-targets-id/). ``` await client.collaborationAllowlistExemptTargets.deleteCollaborationWhitelistExemptTargetById( exemptTarget.id!, ); ``` ### Arguments collaborationWhitelistExemptTargetId `string` - The ID of the exemption to the list. Example: "984923" optionalsInput `DeleteCollaborationWhitelistExemptTargetByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the exemption was successfully deleted. --- ## Untitled *Type: page* CommentsManager List file comments Get comment Update comment Remove comment Create comment List file comments Retrieves a list of comments… # CommentsManager - [List file comments](#list-file-comments) - [Get comment](#get-comment) - [Update comment](#update-comment) - [Remove comment](#remove-comment) - [Create comment](#create-comment) ## List file comments Retrieves a list of comments for a file. This operation is performed by calling function `getFileComments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-comments/). ``` await client.comments.getFileComments(fileId); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetFileCommentsOptionalsInput` ### Returns This function returns a value of type `Comments`. Returns a collection of comment objects. If there are no comments on this file an empty collection will be returned. ## Get comment Retrieves the message and metadata for a specific comment, as well as information on the user who created the comment. This operation is performed by calling function `getCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-comments-id/). ``` await client.comments.getCommentById(newComment.id!); ``` ### Arguments commentId `string` - The ID of the comment. Example: "12345" optionalsInput `GetCommentByIdOptionalsInput` ### Returns This function returns a value of type `CommentFull`. Returns a full comment object. ## Update comment Update the message of a comment. This operation is performed by calling function `updateCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-comments-id/). ``` await client.comments.updateCommentById(newReplyComment.id!, { requestBody: { message: newMessage } satisfies UpdateCommentByIdRequestBody, } satisfies UpdateCommentByIdOptionalsInput); ``` ### Arguments commentId `string` - The ID of the comment. Example: "12345" optionalsInput `UpdateCommentByIdOptionalsInput` ### Returns This function returns a value of type `CommentFull`. Returns the updated comment object. ## Remove comment Permanently deletes a comment. This operation is performed by calling function `deleteCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-comments-id/). ``` await client.comments.deleteCommentById(newComment.id!); ``` ### Arguments commentId `string` - The ID of the comment. Example: "12345" optionalsInput `DeleteCommentByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the comment has been deleted. ## Create comment Adds a comment by the user to a specific file, or as a reply to an other comment. This operation is performed by calling function `createComment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-comments/). ``` await client.comments.createComment({ message: message, item: { id: fileId, type: 'file' as CreateCommentRequestBodyItemTypeField, } satisfies CreateCommentRequestBodyItemField, } satisfies CreateCommentRequestBody); ``` ### Arguments requestBody `CreateCommentRequestBody` - Request body of createComment method optionalsInput `CreateCommentOptionalsInput` ### Returns This function returns a value of type `CommentFull`. Returns the newly created comment object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* Configuration Max retry attempts Custom retry strategy Max retry attempts The default maximum number of retries in case of failed API call… # Configuration - [Max retry attempts](#max-retry-attempts) - [Custom retry strategy](#custom-retry-strategy) ## Max retry attempts The default maximum number of retries in case of failed API call is 5. To change this number you should initialize `BoxRetryStrategy` with the new value and pass it to `NetworkSession`. ``` const auth = new BoxDeveloperTokenAuth({ token: 'DEVELOPER_TOKEN_GOES_HERE' }); const networkSession = new NetworkSession({ retryStrategy: new BoxRetryStrategy({ maxAttempts: 6 }), }); const client = new BoxClient({ auth, networkSession }); ``` ## Custom retry strategy You can also implement your own retry strategy by subclassing `RetryStrategy` and overriding `shouldRetry` and `retryAfter` methods. This example shows how to set custom strategy that retries on 5xx status codes and waits 1 second between retries. ``` export class CustomRetryStrategy implements RetryStrategy { async shouldRetry( fetchOptions: FetchOptions, fetchResponse: FetchResponse, attemptNumber: number, ): Promise<boolean> { return false; } retryAfter( fetchOptions: FetchOptions, fetchResponse: FetchResponse, attemptNumber: number, ): number { return 1.0; } } const auth = new BoxDeveloperTokenAuth({ token: 'DEVELOPER_TOKEN_GOES_HERE' }); const networkSession = new NetworkSession({ retryStrategy: new CustomRetryStrategy(), }); const client = new BoxClient({ auth, networkSession }); ``` --- ## Untitled *Type: page* DevicePinnersManager Get device pin Remove device pin List enterprise device pins Get device pin Retrieves information about an individual… # DevicePinnersManager - [Get device pin](#get-device-pin) - [Remove device pin](#remove-device-pin) - [List enterprise device pins](#list-enterprise-device-pins) ## Get device pin Retrieves information about an individual device pin. This operation is performed by calling function `getDevicePinnerById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-device-pinners-id/). ``` await client.devicePinners.getDevicePinnerById(devicePinnerId); ``` ### Arguments devicePinnerId `string` - The ID of the device pin. Example: "2324234" optionalsInput `GetDevicePinnerByIdOptionalsInput` ### Returns This function returns a value of type `DevicePinner`. Returns information about a single device pin. ## Remove device pin Deletes an individual device pin. This operation is performed by calling function `deleteDevicePinnerById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-device-pinners-id/). ``` await client.devicePinners.deleteDevicePinnerById(devicePinnerId); ``` ### Arguments devicePinnerId `string` - The ID of the device pin. Example: "2324234" optionalsInput `DeleteDevicePinnerByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the pin has been deleted. ## List enterprise device pins Retrieves all the device pins within an enterprise. The user must have admin privileges, and the application needs the "manage enterprise" scope to make this call. This operation is performed by calling function `getEnterpriseDevicePinners`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-enterprises-id-device-pinners/). ``` await client.devicePinners.getEnterpriseDevicePinners(enterpriseId); ``` ### Arguments enterpriseId `string` - The ID of the enterprise. Example: "3442311" optionalsInput `GetEnterpriseDevicePinnersOptionalsInput` ### Returns This function returns a value of type `DevicePinners`. Returns a list of device pins for a given enterprise. --- ## Untitled *Type: page* Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers… # Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers. [Make custom HTTP request](#make-custom-http-request) - [JSON request](#json-request) - [Multi-part request](#multi-part-request) - [Binary response](#binary-response) [Additional headers](#additional-headers) - [As-User header](#as-user-header) - [Suppress notifications](#suppress-notifications) - [Custom headers](#custom-headers) [Custom Base URLs](#custom-base-urls) [Custom Agent Options](#custom-agent-options) [Interceptors](#interceptors) [Use Proxy for API calls](#use-proxy-for-api-calls) # Make custom HTTP request You can make custom HTTP requests using the `client.makeRequest()` method. This method allows you to make any HTTP request to the Box API. It will automatically use authentication and network configuration settings from the client. The method accepts a `FetchOptions` object as an argument and returns a `FetchResponse` object. ## JSON request The following example demonstrates how to make a custom POST request to create a new folder in the root folder. ``` const response: FetchResponse = await client.makeRequest( { method: "POST", url: "https://api.box.com/2.0/folders", data: {name: newFolderName, parent: {id: "0"}} } satisfies FetchOptionsInput ); console.log('Received status code: ', response.status) console.log('Created folder name: ', getSdValueByKey(response.content, "name")) ``` ## Multi-part request The following example demonstrates how to make a custom multipart request that uploads a file to a folder. ``` const multipartAttributes = {name: "newFileName", parent: { id: "0" }}; const uploadFileResponse: FetchResponse = await client.makeRequest({ method: "POST", url: "https://upload.box.com/api/2.0/files/content", contentType: "multipart/form-data", multipartData: [{ partName: "attributes", data: multipartAttributes } satisfies MultipartItem, { partName: "file", fileStream: fileContentStream } satisfies MultipartItem] } satisfies FetchOptionsInput); console.log('Received status code: ', response.status) ``` ## Binary response The following example demonstrates how to make a custom request that expects a binary response. It is required to specify the `responseFormat` parameter in the `FetchOptions` object to "binary". ``` const response: FetchResponse = await client.makeRequest({ method: "GET", url: "".concat("https://api.box.com/2.0/files/", uploadedFile.id, "/content") as string, responseFormat: "binary" as ResponseFormat } satisfies FetchOptionsInput); console.log('Received status code: ', response.status) const fileWriteStream = fs.createWriteStream('file.pdf'); response.content.pipe(fileWriteStream); ``` # Additional headers BoxClient provides a convenient methods, which allow passing additional headers, which will be included in every API call made by the client. ## As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an As-User: USER-ID header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). The following example assume that the client has been instantiated with an access token belonging to an admin-level user or Service Account with appropriate privileges to make As-User calls. Calling the `client.withAsUserHeader()` method creates a new client to impersonate user with the provided ID. All calls made with the new client will be made in context of the impersonated user, leaving the original client unmodified. ``` const userClient = client.withAsUserHeader('1234567'); ``` ## Suppress notifications If you are making administrative API calls (that is, your application has “Manage an Enterprise” scope, and the user signing in is a co-admin with the correct "Edit settings for your company" permission) then you can suppress both email and webhook notifications. This can be used, for example, for a virus-scanning tool to download copies of everyone’s files in an enterprise, without every collaborator on the file getting an email. All actions will still appear in users' updates feed and audit logs. **Note:** This functionality is only available for approved applications. Calling the `client.withSuppressedNotifications()` method creates a new client. For all calls made with the new client the notifications will be suppressed. ``` const newClient = client.withSuppressedNotifications(); ``` ## Custom headers You can also specify the custom set of headers, which will be included in every API call made by client. Calling the `client.withExtraHeaders()` method creates a new client, leaving the original client unmodified. ``` const newClient = client.withExtraHeaders({ ['customHeader']: 'customValue' }); ``` # Custom Base URLs You can also specify the custom base URLs, which will be used for API calls made by client. Calling the `client.withCustomBaseUrls()` method creates a new client, leaving the original client unmodified. ``` const newClient = client.withCustomBaseUrls({ baseUrl: 'https://api.box.com', uploadUrl: 'https://upload.box.com/api', oauth2Url: 'https://account.box.com/api/oauth2', }); ``` # Custom Agent Options You can also specify the custom agent options, which will be used for API calls made by client. Calling the `client.withCustomAgentOptions()` method creates a new client, leaving the original client unmodified. ``` const options: AgentOptions = {}; const newClient = client.withCustomAgentOptions(options); ``` # Interceptors You can specify custom interceptors - methods that will be called just before making a request and right after receiving a response from the server. Using these function allows you to modify the request payload and response. Interceptor interface accepts two methods with the following signatures: ``` beforeRequest(options: FetchOptions): FetchOptions; afterRequest(response: FetchResponse): FetchResponse; ``` You can apply more than one interceptor to the client by passing a list of interceptors to apply. Calling the `client.withInterceptors()` method creates a new client, leaving the original client unmodified. ``` function beforeRequest(options: FetchOptions): FetchOptions { return { method: options.method, headers: options.headers, params: { ...options.params, ...{ ['fields']: 'role' } }, data: options.data, fileStream: options.fileStream, multipartData: options.multipartData, contentType: options.contentType, responseFormat: options.responseFormat, auth: options.auth, networkSession: options.networkSession, cancellationToken: options.cancellationToken, }; } function emptyAfterRequest(response: FetchResponse): FetchResponse { return response; } const clientWithInterceptor: BoxClient = client.withInterceptors([ { beforeRequest: beforeRequest, afterRequest: emptyAfterRequest, }, ]); ``` # Use Proxy for API calls In order to use a proxy for API calls, calling the `client.withProxy(proxyConfig)` method creates a new client, leaving the original client unmodified, with the username and password being optional. If both custom agent options and proxy are provided, the proxy will take precedence. **Note:** We are only supporting http/s proxies with basic authentication. NTLM and other authentication methods are not supported. ``` newClient = client.withProxy({ url: 'http://127.0.0.1:1234/', username: 'user', password: 'password', }); ``` --- ## Untitled *Type: page* DocgenTemplateManager Create Box Doc Gen template List Box Doc Gen templates Delete Box Doc Gen template Get Box Doc Gen template by ID List… # DocgenTemplateManager - [Create Box Doc Gen template](#create-box-doc-gen-template) - [List Box Doc Gen templates](#list-box-doc-gen-templates) - [Delete Box Doc Gen template](#delete-box-doc-gen-template) - [Get Box Doc Gen template by ID](#get-box-doc-gen-template-by-id) - [List all Box Doc Gen template tags in template](#list-all-box-doc-gen-template-tags-in-template) - [Get list of all Box Doc Gen jobs for template](#get-list-of-all-box-doc-gen-jobs-for-template) ## Create Box Doc Gen template Marks a file as a Box Doc Gen template. This operation is performed by calling function `createDocgenTemplateV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-templates/). ``` await client.docgenTemplate.createDocgenTemplateV2025R0({ file: new FileReferenceV2025R0({ id: file.id }), } satisfies DocGenTemplateCreateRequestV2025R0); ``` ### Arguments requestBody `DocGenTemplateCreateRequestV2025R0` - Request body of createDocgenTemplateV2025R0 method optionalsInput `CreateDocgenTemplateV2025R0OptionalsInput` ### Returns This function returns a value of type `DocGenTemplateBaseV2025R0`. The file which has now been marked as a Box Doc Gen template. ## List Box Doc Gen templates Lists Box Doc Gen templates on which the user is a collaborator. This operation is performed by calling function `getDocgenTemplatesV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates/). ``` await client.docgenTemplate.getDocgenTemplatesV2025R0(); ``` ### Arguments queryParams `GetDocgenTemplatesV2025R0QueryParams` - Query parameters of getDocgenTemplatesV2025R0 method headersInput `GetDocgenTemplatesV2025R0HeadersInput` - Headers of getDocgenTemplatesV2025R0 method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenTemplatesV2025R0`. Returns a collection of templates. ## Delete Box Doc Gen template Unmarks file as Box Doc Gen template. This operation is performed by calling function `deleteDocgenTemplateByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-docgen-templates-id/). ``` await client.docgenTemplate.deleteDocgenTemplateByIdV2025R0( createdDocgenTemplate.file!.id, ); ``` ### Arguments templateId `string` - ID of the file which will no longer be marked as a Box Doc Gen template. Example: "123" optionalsInput `DeleteDocgenTemplateByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when a file is no longer marked as a Box Doc Gen template. ## Get Box Doc Gen template by ID Lists details of a specific Box Doc Gen template. This operation is performed by calling function `getDocgenTemplateByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id/). ``` await client.docgenTemplate.getDocgenTemplateByIdV2025R0( createdDocgenTemplate.file!.id, ); ``` ### Arguments templateId `string` - The ID of a Box Doc Gen template. Example: 123 optionalsInput `GetDocgenTemplateByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `DocGenTemplateV2025R0`. Returns a template. ## List all Box Doc Gen template tags in template Lists all tags in a Box Doc Gen template. This operation is performed by calling function `getDocgenTemplateTagsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id-tags/). ``` await client.docgenTemplate.getDocgenTemplateTagsV2025R0( fetchedDocgenTemplate.file!.id, ); ``` ### Arguments templateId `string` - ID of template. Example: 123 optionalsInput `GetDocgenTemplateTagsV2025R0OptionalsInput` ### Returns This function returns a value of type `DocGenTagsV2025R0`. A list of document generation template tags.Processing tags for the file. ## Get list of all Box Doc Gen jobs for template Lists the users jobs which use this template. This operation is performed by calling function `getDocgenTemplateJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-template-jobs-id/). ``` await client.docgenTemplate.getDocgenTemplateJobByIdV2025R0( fetchedDocgenTemplate.file!.id, ); ``` ### Arguments templateId `string` - Id of template to fetch jobs for. Example: 123 optionalsInput `GetDocgenTemplateJobByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `DocGenJobsV2025R0`. A single Box Doc Gen template. --- ## Untitled *Type: page* DocgenManager Get Box Doc Gen job by ID List all Box Doc Gen jobs Get Box Doc Gen jobs by batch ID Generate document using Box Doc Gen… # DocgenManager - [Get Box Doc Gen job by ID](#get-box-doc-gen-job-by-id) - [List all Box Doc Gen jobs](#list-all-box-doc-gen-jobs) - [Get Box Doc Gen jobs by batch ID](#get-box-doc-gen-jobs-by-batch-id) - [Generate document using Box Doc Gen template](#generate-document-using-box-doc-gen-template) ## Get Box Doc Gen job by ID Get details of the Box Doc Gen job. This operation is performed by calling function `getDocgenJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs-id/). ``` await client.docgen.getDocgenJobByIdV2025R0(docgenJobItemFromList.id); ``` ### Arguments jobId `string` - Box Doc Gen job ID. Example: 123 optionalsInput `GetDocgenJobByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `DocGenJobV2025R0`. Details of the Box Doc Gen job. ## List all Box Doc Gen jobs Lists all Box Doc Gen jobs for a user. This operation is performed by calling function `getDocgenJobsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs/). ``` await client.docgen.getDocgenJobsV2025R0({ limit: 500, } satisfies GetDocgenJobsV2025R0QueryParams); ``` ### Arguments queryParams `GetDocgenJobsV2025R0QueryParams` - Query parameters of getDocgenJobsV2025R0 method headersInput `GetDocgenJobsV2025R0HeadersInput` - Headers of getDocgenJobsV2025R0 method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenJobsFullV2025R0`. A list of Box Doc Gen jobs. ## Get Box Doc Gen jobs by batch ID Lists Box Doc Gen jobs in a batch. This operation is performed by calling function `getDocgenBatchJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-batch-jobs-id/). ``` await client.docgen.getDocgenBatchJobByIdV2025R0(docgenBatch.id); ``` ### Arguments batchId `string` - Box Doc Gen batch ID. Example: 123 optionalsInput `GetDocgenBatchJobByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `DocGenJobsV2025R0`. Returns a list of Box Doc Gen jobs in a Box Doc Gen batch. ## Generate document using Box Doc Gen template Generates a document using a Box Doc Gen template. This operation is performed by calling function `createDocgenBatchV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-batches/). ``` await client.docgen.createDocgenBatchV2025R0({ file: new FileReferenceV2025R0({ id: uploadedFile.id }), inputSource: 'api', destinationFolder: new DocGenBatchCreateRequestV2025R0DestinationFolderField({ id: folder.id, }), outputType: 'pdf', documentGenerationData: [ { generatedFileName: 'test', userInput: { ['abc']: 'xyz' }, } satisfies DocGenDocumentGenerationDataV2025R0, ], } satisfies DocGenBatchCreateRequestV2025R0); ``` ### Arguments requestBody `DocGenBatchCreateRequestV2025R0` - Request body of createDocgenBatchV2025R0 method optionalsInput `CreateDocgenBatchV2025R0OptionalsInput` ### Returns This function returns a value of type `DocGenBatchBaseV2025R0`. The created Batch ID. --- ## Untitled *Type: page* EmailAliasesManager List user's email aliases Create email alias Remove email alias List user's email aliases Retrieves all email aliases… # EmailAliasesManager - [List user's email aliases](#list-users-email-aliases) - [Create email alias](#create-email-alias) - [Remove email alias](#remove-email-alias) ## List user's email aliases Retrieves all email aliases for a user. The collection does not include the primary login for the user. This operation is performed by calling function `getUserEmailAliases`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-email-aliases/). ``` await client.emailAliases.getUserEmailAliases(newUser.id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" optionalsInput `GetUserEmailAliasesOptionalsInput` ### Returns This function returns a value of type `EmailAliases`. Returns a collection of email aliases. ## Create email alias Adds a new email alias to a user account.. This operation is performed by calling function `createUserEmailAlias`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-email-aliases/). ``` await client.emailAliases.createUserEmailAlias(newUser.id, { email: newAliasEmail, } satisfies CreateUserEmailAliasRequestBody); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" requestBody `CreateUserEmailAliasRequestBody` - Request body of createUserEmailAlias method optionalsInput `CreateUserEmailAliasOptionalsInput` ### Returns This function returns a value of type `EmailAlias`. Returns the newly created email alias object. ## Remove email alias Removes an email alias from a user. This operation is performed by calling function `deleteUserEmailAliasById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-email-aliases-id/). ``` await client.emailAliases.deleteUserEmailAliasById(newUser.id, newAlias.id!); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" emailAliasId `string` - The ID of the email alias. Example: "23432" optionalsInput `DeleteUserEmailAliasByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Removes the alias and returns an empty response. --- ## Untitled *Type: page* EventsManager Get events long poll endpoint List user and enterprise events Get events long poll endpoint Returns a list of real-time… # EventsManager - [Get events long poll endpoint](#get-events-long-poll-endpoint) - [List user and enterprise events](#list-user-and-enterprise-events) ## Get events long poll endpoint Returns a list of real-time servers that can be used for long-polling updates to the [event stream](#get-events). Long polling is the concept where a HTTP request is kept open until the server sends a response, then repeating the process over and over to receive updated responses. Long polling the event stream can only be used for user events, not for enterprise events. To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next, make a long poll request to any of the provided URLs. When an event occurs in monitored account a response with the value `new_change` will be sent. The response contains no other details as it only serves as a prompt to take further action such as sending a request to the [events endpoint](#get-events) with the last known `stream_position`. After the server sends this response it closes the connection. You must now repeat the long poll process to begin listening for events again. If no events occur for a while and the connection times out you will receive a response with the value `reconnect`. When you receive this response you’ll make another call to this endpoint to restart the process. If you receive no events in `retry_timeout` seconds then you will need to make another request to the real-time server (one of the URLs in the response for this endpoint). This might be necessary due to network errors. Finally, if you receive a `max_retries` error when making a request to the real-time server, you should start over by making a call to this endpoint first. This operation is performed by calling function `getEventsWithLongPolling`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-events/). ``` await client.events.getEventsWithLongPolling(); ``` ### Arguments headersInput `GetEventsWithLongPollingHeadersInput` - Headers of getEventsWithLongPolling method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `RealtimeServers`. Returns a paginated array of servers that can be used instead of the regular endpoints for long-polling events. ## List user and enterprise events Returns up to a year of past events for a given user or for the entire enterprise. By default this returns events for the authenticated user. To retrieve events for the entire enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events, or `admin_logs` for querying across historical events. The user making the API call will need to have admin privileges, and the application will need to have the scope `manage enterprise properties` checked. This operation is performed by calling function `getEvents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-events/). ``` await client.events.getEvents(); ``` ### Arguments queryParams `GetEventsQueryParams` - Query parameters of getEvents method headersInput `GetEventsHeadersInput` - Headers of getEvents method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `Events`. Returns a list of event objects. Events objects are returned in pages, with each page (chunk) including a list of event objects. The response includes a `chunk_size` parameter indicating how many events were returned in this chunk, as well as the next `stream_position` that can be queried. --- ## Untitled *Type: page* Downloads Downloads module is used to download files from Box. Downloads Download a File Get download URL Arguments Returns Download a File… # Downloads Downloads module is used to download files from Box. [Downloads](#downloads) - [Download a File](#download-a-file) [Get download URL](#get-download-url) - [Arguments](#arguments) - [Returns](#returns) ## Download a File To get the entire contents of the file as `ArrayBuffer`, call `downloadFile` method. This method returns a `ArrayBuffer` object which contains the file content. ``` const fs = require('fs'); const fileContent = await client.downloads.downloadFile('123456789'); const fileWriteStream = fs.createWriteStream('file.pdf'); fileContent.pipe(fileWriteStream); ``` ## Get download URL Get a URL to download a file This operation is performed by calling function `getDownloadFileUrl`. ``` await client.downloads.getDownloadFileUrl(uploadedFile.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" ## optionalsInput GetDownloadFileUrlOptionalsInput ### Returns This function returns a value of type `string`. --- ## Untitled *Type: page* FileClassificationsManager Get classification on file Add classification to file Update classification on file Remove classification from… # FileClassificationsManager - [Get classification on file](#get-classification-on-file) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Remove classification from file](#remove-classification-from-file) ## Get classification on file Retrieves the classification metadata instance that has been applied to a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `getClassificationOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.fileClassifications.getClassificationOnFile(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetClassificationOnFileOptionalsInput` ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to file Adds a classification to a file by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `addClassificationToFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.fileClassifications.addClassificationToFile(file.id, { requestBody: { boxSecurityClassificationKey: classification.key, } satisfies AddClassificationToFileRequestBody, } satisfies AddClassificationToFileOptionalsInput); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `AddClassificationToFileOptionalsInput` ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the file. ## Update classification on file Updates a classification on a file. The classification can only be updated if a classification has already been applied to the file before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `updateClassificationOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.fileClassifications.updateClassificationOnFile(file.id, [ new UpdateClassificationOnFileRequestBody({ value: secondClassification.key, }), ]); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `readonly UpdateClassificationOnFileRequestBody[]` - Request body of updateClassificationOnFile method optionalsInput `UpdateClassificationOnFileOptionalsInput` ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from file Removes any classifications from a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `deleteClassificationFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.fileClassifications.deleteClassificationFromFile(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `DeleteClassificationFromFileOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* FileMetadataManager List metadata instances on file Get metadata instance on file Create metadata instance on file Update metadata instance… # FileMetadataManager - [List metadata instances on file](#list-metadata-instances-on-file) - [Get metadata instance on file](#get-metadata-instance-on-file) - [Create metadata instance on file](#create-metadata-instance-on-file) - [Update metadata instance on file](#update-metadata-instance-on-file) - [Remove metadata instance from file](#remove-metadata-instance-from-file) ## List metadata instances on file Retrieves all metadata for a given file. This operation is performed by calling function `getFileMetadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata/). ``` await client.fileMetadata.getFileMetadata(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetFileMetadataOptionalsInput` ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Get metadata instance on file Retrieves the instance of a metadata template that has been applied to a file. This operation is performed by calling function `getFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-id-id/). ``` await client.fileMetadata.getFileMetadataById( file.id, 'global' as GetFileMetadataByIdScope, 'properties', ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `GetFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" optionalsInput `GetFileMetadataByIdOptionalsInput` ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on file Applies an instance of a metadata template to a file. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. This operation is performed by calling function `createFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-id-id/). ``` await client.fileMetadata.createFileMetadataById( file.id, 'enterprise' as CreateFileMetadataByIdScope, templateKey, { ['name']: 'John', ['age']: 23, ['birthDate']: '2001-01-03T02:20:50.520Z', ['countryCode']: 'US', ['sports']: ['basketball', 'tennis'], }, ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `CreateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `CreateFileMetadataByIdRequestBody` - Request body of createFileMetadataById method optionalsInput `CreateFileMetadataByIdOptionalsInput` ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update metadata instance on file Updates a piece of metadata on a file. The metadata instance can only be updated if the template has already been applied to the file before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `updateFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-id-id/). ``` await client.fileMetadata.updateFileMetadataById( file.id, 'enterprise' as UpdateFileMetadataByIdScope, templateKey, [ { op: 'replace' as UpdateFileMetadataByIdRequestBodyOpField, path: '/name', value: 'Jack', } satisfies UpdateFileMetadataByIdRequestBody, { op: 'replace' as UpdateFileMetadataByIdRequestBodyOpField, path: '/age', value: 24, } satisfies UpdateFileMetadataByIdRequestBody, { op: 'replace' as UpdateFileMetadataByIdRequestBodyOpField, path: '/birthDate', value: '2000-01-03T02:20:50.520Z', } satisfies UpdateFileMetadataByIdRequestBody, { op: 'replace' as UpdateFileMetadataByIdRequestBodyOpField, path: '/countryCode', value: 'CA', } satisfies UpdateFileMetadataByIdRequestBody, { op: 'replace' as UpdateFileMetadataByIdRequestBodyOpField, path: '/sports', value: ['football'], } satisfies UpdateFileMetadataByIdRequestBody, ], ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `UpdateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `readonly UpdateFileMetadataByIdRequestBody[]` - Request body of updateFileMetadataById method optionalsInput `UpdateFileMetadataByIdOptionalsInput` ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from file Deletes a piece of file metadata. This operation is performed by calling function `deleteFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-id-id/). ``` await client.fileMetadata.deleteFileMetadataById( file.id, 'enterprise' as DeleteFileMetadataByIdScope, templateKey, ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `DeleteFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" optionalsInput `DeleteFileMetadataByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* FileRequestsManager Get file request Update file request Delete file request Copy file request Get file request Retrieves the information… # FileRequestsManager - [Get file request](#get-file-request) - [Update file request](#update-file-request) - [Delete file request](#delete-file-request) - [Copy file request](#copy-file-request) ## Get file request Retrieves the information about a file request. This operation is performed by calling function `getFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-requests-id/). ``` await client.fileRequests.getFileRequestById(fileRequestId); ``` ### Arguments fileRequestId `string` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" optionalsInput `GetFileRequestByIdOptionalsInput` ### Returns This function returns a value of type `FileRequest`. Returns a file request object. ## Update file request Updates a file request. This can be used to activate or deactivate a file request. This operation is performed by calling function `updateFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-file-requests-id/). ``` await client.fileRequests.updateFileRequestById(copiedFileRequest.id, { title: 'updated title', description: 'updated description', } satisfies FileRequestUpdateRequest); ``` ### Arguments fileRequestId `string` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" requestBody `FileRequestUpdateRequest` - Request body of updateFileRequestById method optionalsInput `UpdateFileRequestByIdOptionalsInput` ### Returns This function returns a value of type `FileRequest`. Returns the updated file request object. ## Delete file request Deletes a file request permanently. This operation is performed by calling function `deleteFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-file-requests-id/). ``` await client.fileRequests.deleteFileRequestById(updatedFileRequest.id); ``` ### Arguments fileRequestId `string` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" optionalsInput `DeleteFileRequestByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the file request has been successfully deleted. ## Copy file request Copies an existing file request that is already present on one folder, and applies it to another folder. This operation is performed by calling function `createFileRequestCopy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-file-requests-id-copy/). ``` await client.fileRequests.createFileRequestCopy(fileRequestId, { folder: { id: fileRequest.folder.id, type: 'folder' as FileRequestCopyRequestFolderTypeField, } satisfies FileRequestCopyRequestFolderField, } satisfies FileRequestCopyRequest); ``` ### Arguments fileRequestId `string` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" requestBody `FileRequestCopyRequest` - Request body of createFileRequestCopy method optionalsInput `CreateFileRequestCopyOptionalsInput` ### Returns This function returns a value of type `FileRequest`. Returns updated file request object. --- ## Untitled *Type: page* FileVersionLegalHoldsManager Get file version legal hold List file version legal holds Get file version legal hold Retrieves information… # FileVersionLegalHoldsManager - [Get file version legal hold](#get-file-version-legal-hold) - [List file version legal holds](#list-file-version-legal-holds) ## Get file version legal hold Retrieves information about the legal hold policies assigned to a file version. This operation is performed by calling function `getFileVersionLegalHoldById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds-id/). ``` await client.fileVersionLegalHolds.getFileVersionLegalHoldById( fileVersionLegalHoldId, ); ``` ### Arguments fileVersionLegalHoldId `string` - The ID of the file version legal hold. Example: "2348213" optionalsInput `GetFileVersionLegalHoldByIdOptionalsInput` ### Returns This function returns a value of type `FileVersionLegalHold`. Returns the legal hold policy assignments for the file version. ## List file version legal holds Get a list of file versions on legal hold for a legal hold assignment. Due to ongoing re-architecture efforts this API might not return all file versions for this policy ID. Instead, this API will only return file versions held in the legacy architecture. Two new endpoints will available to request any file versions held in the new architecture. For file versions held in the new architecture, the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API can be used to return all past file versions available for this policy assignment, and the `GET /legal_hold_policy_assignments/:id/files_on_hold` API can be used to return any current (latest) versions of a file under legal hold. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. Once the re-architecture is completed this API will be deprecated. This operation is performed by calling function `getFileVersionLegalHolds`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds/). ``` await client.fileVersionLegalHolds.getFileVersionLegalHolds({ policyId: policyId, } satisfies GetFileVersionLegalHoldsQueryParams); ``` ### Arguments queryParams `GetFileVersionLegalHoldsQueryParams` - Query parameters of getFileVersionLegalHolds method optionalsInput `GetFileVersionLegalHoldsOptionalsInput` ### Returns This function returns a value of type `FileVersionLegalHolds`. Returns the list of file version legal holds for a specific legal hold policy. --- ## Untitled *Type: page* FileVersionRetentionsManager List file version retentions Get retention on file List file version retentions Retrieves all file version… # FileVersionRetentionsManager - [List file version retentions](#list-file-version-retentions) - [Get retention on file](#get-retention-on-file) ## List file version retentions Retrieves all file version retentions for the given enterprise. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `getFileVersionRetentions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions/). ``` await client.fileVersionRetentions.getFileVersionRetentions(); ``` ### Arguments queryParams `GetFileVersionRetentionsQueryParams` - Query parameters of getFileVersionRetentions method headersInput `GetFileVersionRetentionsHeadersInput` - Headers of getFileVersionRetentions method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersionRetentions`. Returns a list of all file version retentions for the enterprise. ## Get retention on file Returns information about a file version retention. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `getFileVersionRetentionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions-id/). ``` await client.fileVersionRetentions.getFileVersionRetentionById( fileVersionRetention.id!, ); ``` ### Arguments fileVersionRetentionId `string` - The ID of the file version retention. Example: "3424234" optionalsInput `GetFileVersionRetentionByIdOptionalsInput` ### Returns This function returns a value of type `FileVersionRetention`. Returns a file version retention object. --- ## Untitled *Type: page* FileVersionsManager List all file versions Get file version Remove file version Restore file version Promote file version List all file… # FileVersionsManager - [List all file versions](#list-all-file-versions) - [Get file version](#get-file-version) - [Remove file version](#remove-file-version) - [Restore file version](#restore-file-version) - [Promote file version](#promote-file-version) ## List all file versions Retrieve a list of the past versions for a file. Versions are only tracked by Box users with premium accounts. To fetch the ID of the current version of a file, use the `GET /file/:id` API. This operation is performed by calling function `getFileVersions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions/). ``` await client.fileVersions.getFileVersions(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetFileVersionsOptionalsInput` ### Returns This function returns a value of type `FileVersions`. Returns an array of past versions for this file. ## Get file version Retrieve a specific version of a file. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `getFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions-id/). ``` await client.fileVersions.getFileVersionById( file.id, fileVersions.entries![0].id, ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `string` - The ID of the file version. Example: "1234" optionalsInput `GetFileVersionByIdOptionalsInput` ### Returns This function returns a value of type `FileVersionFull`. Returns a specific version of a file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Remove file version Move a file version to the trash. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `deleteFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-versions-id/). ``` await client.fileVersions.deleteFileVersionById(file.id, fileVersion.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `string` - The ID of the file version. Example: "1234" optionalsInput `DeleteFileVersionByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the file has been successfully deleted. ## Restore file version Restores a specific version of a file after it was deleted. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `updateFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-versions-id/). ``` await client.fileVersions.updateFileVersionById(file.id, fileVersion.id, { requestBody: { trashedAt: createNull(), } satisfies UpdateFileVersionByIdRequestBody, } satisfies UpdateFileVersionByIdOptionalsInput); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `string` - The ID of the file version. Example: "1234" optionalsInput `UpdateFileVersionByIdOptionalsInput` ### Returns This function returns a value of type `FileVersionFull`. Returns a restored file version object. ## Promote file version Promote a specific version of a file. If previous versions exist, this method can be used to promote one of the older versions to the top of the version history. This creates a new copy of the old version and puts it at the top of the versions history. The file will have the exact same contents as the older version, with the the same hash digest, `etag`, and name as the original. Other properties such as comments do not get updated to their former values. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `promoteFileVersion`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-versions-current/). ``` await client.fileVersions.promoteFileVersion(file.id, { requestBody: { id: fileVersions.entries![0].id, type: 'file_version' as PromoteFileVersionRequestBodyTypeField, } satisfies PromoteFileVersionRequestBody, } satisfies PromoteFileVersionOptionalsInput); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `PromoteFileVersionOptionalsInput` ### Returns This function returns a value of type `FileVersionFull`. Returns a newly created file version object. --- ## Untitled *Type: page* FileWatermarksManager Get watermark on file Apply watermark to file Remove watermark from file Get watermark on file Retrieve the watermark… # FileWatermarksManager - [Get watermark on file](#get-watermark-on-file) - [Apply watermark to file](#apply-watermark-to-file) - [Remove watermark from file](#remove-watermark-from-file) ## Get watermark on file Retrieve the watermark for a file. This operation is performed by calling function `getFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-watermark/). ``` await client.fileWatermarks.getFileWatermark(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetFileWatermarkOptionalsInput` ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this file. ## Apply watermark to file Applies or update a watermark on a file. This operation is performed by calling function `updateFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-watermark/). ``` await client.fileWatermarks.updateFileWatermark(file.id, { watermark: new UpdateFileWatermarkRequestBodyWatermarkField({ imprint: 'default' as UpdateFileWatermarkRequestBodyWatermarkImprintField, }), } satisfies UpdateFileWatermarkRequestBody); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateFileWatermarkRequestBody` - Request body of updateFileWatermark method optionalsInput `UpdateFileWatermarkOptionalsInput` ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this file.Returns a new watermark if no watermark existed on this file yet. ## Remove watermark from file Removes the watermark from a file. This operation is performed by calling function `deleteFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-watermark/). ``` await client.fileWatermarks.deleteFileWatermark(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `DeleteFileWatermarkOptionalsInput` ### Returns This function returns a value of type `undefined`. Removes the watermark and returns an empty response. --- ## Untitled *Type: page* FilesManager Get file information Update file Delete file Copy file Get file thumbnail URL Get file thumbnail Get file information Retrieves… # FilesManager - [Get file information](#get-file-information) - [Update file](#update-file) - [Delete file](#delete-file) - [Copy file](#copy-file) - [Get file thumbnail URL](#get-file-thumbnail-url) - [Get file thumbnail](#get-file-thumbnail) ## Get file information Retrieves the details about a file. This operation is performed by calling function `getFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id/). ``` await client.files.getFileById(uploadedFile.id, { queryParams: { fields: ['is_externally_owned', 'has_collaborations'], } satisfies GetFileByIdQueryParams, } satisfies GetFileByIdOptionalsInput); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetFileByIdOptionalsInput` ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update file Updates a file. This can be used to rename or move a file, create a shared link, or lock a file. This operation is performed by calling function `updateFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id/). ``` await client.files.updateFileById(fileToUpdate.id, { requestBody: { name: updatedName, description: 'Updated description', } satisfies UpdateFileByIdRequestBody, } satisfies UpdateFileByIdOptionalsInput); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `UpdateFileByIdOptionalsInput` ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Delete file Deletes a file, either permanently or by moving it to the trash. The the enterprise settings determine whether the item will be permanently deleted from Box or moved to the trash. This operation is performed by calling function `deleteFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id/). ``` await client.files.deleteFileById(thumbnailFile.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `DeleteFileByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the file has been successfully deleted. ## Copy file Creates a copy of a file. This operation is performed by calling function `copyFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-copy/). ``` await client.files.copyFile(fileOrigin.id, { parent: { id: '0' } satisfies CopyFileRequestBodyParentField, name: copiedFileName, } satisfies CopyFileRequestBody); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CopyFileRequestBody` - Request body of copyFile method optionalsInput `CopyFileOptionalsInput` ### Returns This function returns a value of type `FileFull`. Returns a new file object representing the copied file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Get file thumbnail URL Get the download URL without downloading the content. This operation is performed by calling function `getFileThumbnailUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` await client.files.getFileThumbnailUrl( thumbnailFile.id, 'png' as GetFileThumbnailUrlExtension, ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension `GetFileThumbnailUrlExtension` - The file format for the thumbnail. Example: "png" optionalsInput `GetFileThumbnailUrlOptionalsInput` ### Returns This function returns a value of type `string`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. ## Get file thumbnail Retrieves a thumbnail, or smaller image representation, of a file. Sizes of `32x32`,`64x64`, `128x128`, and `256x256` can be returned in the `.png` format and sizes of `32x32`, `160x160`, and `320x320` can be returned in the `.jpg` format. Thumbnails can be generated for the image and video file formats listed [found on our community site](https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327). This operation is performed by calling function `getFileThumbnailById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` await client.files.getFileThumbnailById( thumbnailFile.id, 'png' as GetFileThumbnailByIdExtension, ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension `GetFileThumbnailByIdExtension` - The file format for the thumbnail. Example: "png" optionalsInput `GetFileThumbnailByIdOptionalsInput` ### Returns This function returns a value of type `undefined | ByteStream`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. --- ## Untitled *Type: page* FolderClassificationsManager Get classification on folder Add classification to folder Update classification on folder Remove classification… # FolderClassificationsManager - [Get classification on folder](#get-classification-on-folder) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Get classification on folder Retrieves the classification metadata instance that has been applied to a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `getClassificationOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.folderClassifications.getClassificationOnFolder(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `GetClassificationOnFolderOptionalsInput` ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to folder Adds a classification to a folder by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `addClassificationToFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.folderClassifications.addClassificationToFolder(folder.id, { requestBody: { boxSecurityClassificationKey: classification.key, } satisfies AddClassificationToFolderRequestBody, } satisfies AddClassificationToFolderOptionalsInput); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `AddClassificationToFolderOptionalsInput` ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the folder. ## Update classification on folder Updates a classification on a folder. The classification can only be updated if a classification has already been applied to the folder before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `updateClassificationOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.folderClassifications.updateClassificationOnFolder(folder.id, [ new UpdateClassificationOnFolderRequestBody({ value: secondClassification.key, }), ]); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `readonly UpdateClassificationOnFolderRequestBody[]` - Request body of updateClassificationOnFolder method optionalsInput `UpdateClassificationOnFolderOptionalsInput` ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from folder Removes any classifications from a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `deleteClassificationFromFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.folderClassifications.deleteClassificationFromFolder(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `DeleteClassificationFromFolderOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* FolderMetadataManager List metadata instances on folder Get metadata instance on folder Create metadata instance on folder Update metadata… # FolderMetadataManager - [List metadata instances on folder](#list-metadata-instances-on-folder) - [Get metadata instance on folder](#get-metadata-instance-on-folder) - [Create metadata instance on folder](#create-metadata-instance-on-folder) - [Update metadata instance on folder](#update-metadata-instance-on-folder) - [Remove metadata instance from folder](#remove-metadata-instance-from-folder) ## List metadata instances on folder Retrieves all metadata for a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getFolderMetadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata/). ``` await client.folderMetadata.getFolderMetadata(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `GetFolderMetadataOptionalsInput` ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a folder. This API does not support pagination and will therefore always return all of the metadata associated to the folder. ## Get metadata instance on folder Retrieves the instance of a metadata template that has been applied to a folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-id-id/). ``` await client.folderMetadata.getFolderMetadataById( folder.id, 'global' as GetFolderMetadataByIdScope, 'properties', ); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `GetFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" optionalsInput `GetFolderMetadataByIdOptionalsInput` ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on folder Applies an instance of a metadata template to a folder. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. To display the metadata template in the Box web app the enterprise needs to be configured to enable **Cascading Folder Level Metadata** for the user in the admin console. This operation is performed by calling function `createFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-id-id/). ``` await client.folderMetadata.createFolderMetadataById( folder.id, 'enterprise' as CreateFolderMetadataByIdScope, templateKey, { ['name']: 'John', ['age']: 23, ['birthDate']: '2001-01-03T02:20:50.520Z', ['countryCode']: 'US', ['sports']: ['basketball', 'tennis'], }, ); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `CreateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `CreateFolderMetadataByIdRequestBody` - Request body of createFolderMetadataById method optionalsInput `CreateFolderMetadataByIdOptionalsInput` ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the folder, including the data that was applied to the template. ## Update metadata instance on folder Updates a piece of metadata on a folder. The metadata instance can only be updated if the template has already been applied to the folder before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `updateFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-id-id/). ``` await client.folderMetadata.updateFolderMetadataById( folder.id, 'enterprise' as UpdateFolderMetadataByIdScope, templateKey, [ { op: 'replace' as UpdateFolderMetadataByIdRequestBodyOpField, path: '/name', value: 'Jack', } satisfies UpdateFolderMetadataByIdRequestBody, { op: 'replace' as UpdateFolderMetadataByIdRequestBodyOpField, path: '/age', value: 24, } satisfies UpdateFolderMetadataByIdRequestBody, { op: 'replace' as UpdateFolderMetadataByIdRequestBodyOpField, path: '/birthDate', value: '2000-01-03T02:20:50.520Z', } satisfies UpdateFolderMetadataByIdRequestBody, { op: 'replace' as UpdateFolderMetadataByIdRequestBodyOpField, path: '/countryCode', value: 'CA', } satisfies UpdateFolderMetadataByIdRequestBody, { op: 'replace' as UpdateFolderMetadataByIdRequestBodyOpField, path: '/sports', value: ['football'], } satisfies UpdateFolderMetadataByIdRequestBody, ], ); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `UpdateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `readonly UpdateFolderMetadataByIdRequestBody[]` - Request body of updateFolderMetadataById method optionalsInput `UpdateFolderMetadataByIdOptionalsInput` ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from folder Deletes a piece of folder metadata. This operation is performed by calling function `deleteFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-id-id/). ``` await client.folderMetadata.deleteFolderMetadataById( folder.id, 'enterprise' as DeleteFolderMetadataByIdScope, templateKey, ); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `DeleteFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" optionalsInput `DeleteFolderMetadataByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* FolderWatermarksManager Get watermark for folder Apply watermark to folder Remove watermark from folder Get watermark for folder Retrieve… # FolderWatermarksManager - [Get watermark for folder](#get-watermark-for-folder) - [Apply watermark to folder](#apply-watermark-to-folder) - [Remove watermark from folder](#remove-watermark-from-folder) ## Get watermark for folder Retrieve the watermark for a folder. This operation is performed by calling function `getFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-watermark/). ``` await client.folderWatermarks.getFolderWatermark(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `GetFolderWatermarkOptionalsInput` ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this folder. ## Apply watermark to folder Applies or update a watermark on a folder. This operation is performed by calling function `updateFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-watermark/). ``` await client.folderWatermarks.updateFolderWatermark(folder.id, { watermark: new UpdateFolderWatermarkRequestBodyWatermarkField({ imprint: 'default' as UpdateFolderWatermarkRequestBodyWatermarkImprintField, }), } satisfies UpdateFolderWatermarkRequestBody); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateFolderWatermarkRequestBody` - Request body of updateFolderWatermark method optionalsInput `UpdateFolderWatermarkOptionalsInput` ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this folder.Returns a new watermark if no watermark existed on this folder yet. ## Remove watermark from folder Removes the watermark from a folder. This operation is performed by calling function `deleteFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-watermark/). ``` await client.folderWatermarks.deleteFolderWatermark(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `DeleteFolderWatermarkOptionalsInput` ### Returns This function returns a value of type `undefined`. An empty response will be returned when the watermark was successfully deleted. --- ## Untitled *Type: page* FolderLocksManager List folder locks Create folder lock Delete folder lock List folder locks Retrieves folder lock details for a given… # FolderLocksManager - [List folder locks](#list-folder-locks) - [Create folder lock](#create-folder-lock) - [Delete folder lock](#delete-folder-lock) ## List folder locks Retrieves folder lock details for a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `getFolderLocks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folder-locks/). ``` await client.folderLocks.getFolderLocks({ folderId: folder.id, } satisfies GetFolderLocksQueryParams); ``` ### Arguments queryParams `GetFolderLocksQueryParams` - Query parameters of getFolderLocks method optionalsInput `GetFolderLocksOptionalsInput` ### Returns This function returns a value of type `FolderLocks`. Returns details for all folder locks applied to the folder, including the lock type and user that applied the lock. ## Create folder lock Creates a folder lock on a folder, preventing it from being moved and/or deleted. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `createFolderLock`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folder-locks/). ``` await client.folderLocks.createFolderLock({ folder: { id: folder.id, type: 'folder', } satisfies CreateFolderLockRequestBodyFolderField, lockedOperations: { move: true, delete: true, } satisfies CreateFolderLockRequestBodyLockedOperationsField, } satisfies CreateFolderLockRequestBody); ``` ### Arguments requestBody `CreateFolderLockRequestBody` - Request body of createFolderLock method optionalsInput `CreateFolderLockOptionalsInput` ### Returns This function returns a value of type `FolderLock`. Returns the instance of the folder lock that was applied to the folder, including the user that applied the lock and the operations set. ## Delete folder lock Deletes a folder lock on a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `deleteFolderLockById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folder-locks-id/). ``` await client.folderLocks.deleteFolderLockById(folderLock.id!); ``` ### Arguments folderLockId `string` - The ID of the folder lock. Example: "12345" optionalsInput `DeleteFolderLockByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the folder lock is successfully deleted. --- ## Untitled *Type: page* FoldersManager Get folder information Update folder Delete folder List items in folder Create folder Copy folder Get folder information… # FoldersManager - [Get folder information](#get-folder-information) - [Update folder](#update-folder) - [Delete folder](#delete-folder) - [List items in folder](#list-items-in-folder) - [Create folder](#create-folder) - [Copy folder](#copy-folder) ## Get folder information Retrieves details for a folder, including the first 100 entries in the folder. Passing `sort`, `direction`, `offset`, and `limit` parameters in query allows you to manage the list of returned [folder items](r://folder--full#param-item-collection). To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items) endpoint. This operation is performed by calling function `getFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id/). ``` await client.folders.getFolderById('0'); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `GetFolderByIdOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns a folder, including the first 100 entries in the folder. If you used query parameters like `sort`, `direction`, `offset`, or `limit` the *folder items list* will be affected accordingly. To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items)) endpoint. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update folder Updates a folder. This can be also be used to move the folder, create shared links, update collaborations, and more. This operation is performed by calling function `updateFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id/). ``` await client.folders.updateFolderById(folderToUpdate.id, { requestBody: { name: updatedName, description: 'Updated description', } satisfies UpdateFolderByIdRequestBody, } satisfies UpdateFolderByIdOptionalsInput); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `UpdateFolderByIdOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns a folder object for the updated folder Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. If the user is moving folders with a large number of items in all of their descendants, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. ## Delete folder Deletes a folder, either permanently or by moving it to the trash. This operation is performed by calling function `deleteFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id/). ``` await client.folders.deleteFolderById(newFolder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `DeleteFolderByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the folder is successfully deleted or moved to the trash. ## List items in folder Retrieves a page of items in a folder. These items can be files, folders, and web links. To request more information about the folder itself, like its size, use the [Get a folder](#get-folders-id) endpoint instead. This operation is performed by calling function `getFolderItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-items/). ``` await client.folders.getFolderItems(folderOrigin.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `GetFolderItemsOptionalsInput` ### Returns This function returns a value of type `Items`. Returns a collection of files, folders, and web links contained in a folder. ## Create folder Creates a new empty folder within the specified parent folder. This operation is performed by calling function `createFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders/). ``` await client.folders.createFolder({ name: newFolderName, parent: { id: '0' } satisfies CreateFolderRequestBodyParentField, } satisfies CreateFolderRequestBody); ``` ### Arguments requestBody `CreateFolderRequestBody` - Request body of createFolder method optionalsInput `CreateFolderOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns a folder object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Copy folder Creates a copy of a folder within a destination folder. The original folder will not be changed. This operation is performed by calling function `copyFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-copy/). ``` await client.folders.copyFolder(folderOrigin.id, { parent: { id: '0' } satisfies CopyFolderRequestBodyParentField, name: copiedFolderName, } satisfies CopyFolderRequestBody); ``` ### Arguments folderId `string` - The unique identifier of the folder to copy. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder with the ID `0` can not be copied. Example: "0" requestBody `CopyFolderRequestBody` - Request body of copyFolder method optionalsInput `CopyFolderOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns a new folder object representing the copied folder. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* GroupsManager List groups for enterprise Create group Get group Update group Remove group List groups for enterprise Retrieves all of the… # GroupsManager - [List groups for enterprise](#list-groups-for-enterprise) - [Create group](#create-group) - [Get group](#get-group) - [Update group](#update-group) - [Remove group](#remove-group) ## List groups for enterprise Retrieves all of the groups for a given enterprise. The user must have admin permissions to inspect enterprise's groups. This operation is performed by calling function `getGroups`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups/). ``` await client.groups.getGroups(); ``` ### Arguments queryParams `GetGroupsQueryParams` - Query parameters of getGroups method headersInput `GetGroupsHeadersInput` - Headers of getGroups method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `Groups`. Returns a collection of group objects. If there are no groups, an empty collection will be returned. ## Create group Creates a new group of users in an enterprise. Only users with admin permissions can create new groups. This operation is performed by calling function `createGroup`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups/). ``` await client.groups.createGroup({ name: groupName, description: groupDescription, } satisfies CreateGroupRequestBody); ``` ### Arguments requestBody `CreateGroupRequestBody` - Request body of createGroup method optionalsInput `CreateGroupOptionalsInput` ### Returns This function returns a value of type `GroupFull`. Returns the new group object. ## Get group Retrieves information about a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id/). ``` await client.groups.getGroupById(group.id, { queryParams: { fields: ['id', 'name', 'description', 'group_type'], } satisfies GetGroupByIdQueryParams, } satisfies GetGroupByIdOptionalsInput); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" optionalsInput `GetGroupByIdOptionalsInput` ### Returns This function returns a value of type `GroupFull`. Returns the group object. ## Update group Updates a specific group. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `updateGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-groups-id/). ``` await client.groups.updateGroupById(group.id, { requestBody: { name: updatedGroupName } satisfies UpdateGroupByIdRequestBody, } satisfies UpdateGroupByIdOptionalsInput); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" optionalsInput `UpdateGroupByIdOptionalsInput` ### Returns This function returns a value of type `GroupFull`. Returns the updated group object. ## Remove group Permanently deletes a group. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `deleteGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-groups-id/). ``` await client.groups.deleteGroupById(group.id); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" optionalsInput `DeleteGroupByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the group was successfully deleted. --- ## Untitled *Type: page* HubCollaborationsManager Get hub collaborations Create hub collaboration Get hub collaboration by collaboration ID Update hub collaboration… # HubCollaborationsManager - [Get hub collaborations](#get-hub-collaborations) - [Create hub collaboration](#create-hub-collaboration) - [Get hub collaboration by collaboration ID](#get-hub-collaboration-by-collaboration-id) - [Update hub collaboration](#update-hub-collaboration) - [Remove hub collaboration](#remove-hub-collaboration) ## Get hub collaborations Retrieves all collaborations for a hub. This operation is performed by calling function `getHubCollaborationsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations/). ``` await client.hubCollaborations.getHubCollaborationsV2025R0({ hubId: hub.id, } satisfies GetHubCollaborationsV2025R0QueryParams); ``` ### Arguments queryParams `GetHubCollaborationsV2025R0QueryParams` - Query parameters of getHubCollaborationsV2025R0 method optionalsInput `GetHubCollaborationsV2025R0OptionalsInput` ### Returns This function returns a value of type `HubCollaborationsV2025R0`. Retrieves the collaborations associated with the specified hub. ## Create hub collaboration Adds a collaboration for a single user or a single group to a hub. Collaborations can be created using email address, user IDs, or group IDs. This operation is performed by calling function `createHubCollaborationV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hub-collaborations/). ``` await client.hubCollaborations.createHubCollaborationV2025R0({ hub: new HubCollaborationCreateRequestV2025R0HubField({ id: hub.id }), accessibleBy: { type: 'user', id: user.id, } satisfies HubCollaborationCreateRequestV2025R0AccessibleByField, role: 'viewer', } satisfies HubCollaborationCreateRequestV2025R0); ``` ### Arguments requestBody `HubCollaborationCreateRequestV2025R0` - Request body of createHubCollaborationV2025R0 method optionalsInput `CreateHubCollaborationV2025R0OptionalsInput` ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a new hub collaboration object. ## Get hub collaboration by collaboration ID Retrieves details for a hub collaboration by collaboration ID. This operation is performed by calling function `getHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations-id/). ``` await client.hubCollaborations.getHubCollaborationByIdV2025R0( createdCollaboration.id, ); ``` ### Arguments hubCollaborationId `string` - The ID of the hub collaboration. Example: "1234" optionalsInput `GetHubCollaborationByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a hub collaboration object. ## Update hub collaboration Updates a hub collaboration. Can be used to change the hub role. This operation is performed by calling function `updateHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hub-collaborations-id/). ``` await client.hubCollaborations.updateHubCollaborationByIdV2025R0( createdCollaboration.id, { role: 'editor' } satisfies HubCollaborationUpdateRequestV2025R0, ); ``` ### Arguments hubCollaborationId `string` - The ID of the hub collaboration. Example: "1234" requestBody `HubCollaborationUpdateRequestV2025R0` - Request body of updateHubCollaborationByIdV2025R0 method optionalsInput `UpdateHubCollaborationByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns an updated hub collaboration object. ## Remove hub collaboration Deletes a single hub collaboration. This operation is performed by calling function `deleteHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hub-collaborations-id/). ``` await client.hubCollaborations.deleteHubCollaborationByIdV2025R0( createdCollaboration.id, ); ``` ### Arguments hubCollaborationId `string` - The ID of the hub collaboration. Example: "1234" optionalsInput `DeleteHubCollaborationByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the hub collaboration was successfully deleted. --- ## Untitled *Type: page* HubItemsManager Get hub items Manage hub items Get hub items Retrieves all items associated with a Hub. This operation is performed by… # HubItemsManager - [Get hub items](#get-hub-items) - [Manage hub items](#manage-hub-items) ## Get hub items Retrieves all items associated with a Hub. This operation is performed by calling function `getHubItemsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-items/). ``` await client.hubItems.getHubItemsV2025R0({ hubId: createdHub.id, } satisfies GetHubItemsV2025R0QueryParams); ``` ### Arguments queryParams `GetHubItemsV2025R0QueryParams` - Query parameters of getHubItemsV2025R0 method optionalsInput `GetHubItemsV2025R0OptionalsInput` ### Returns This function returns a value of type `HubItemsV2025R0`. Retrieves the items associated with the specified Hub. ## Manage hub items Adds and/or removes Hub items from a Hub. This operation is performed by calling function `manageHubItemsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-manage-items/). ``` await client.hubItems.manageHubItemsV2025R0(createdHub.id, { operations: [ { action: 'add' as HubItemOperationV2025R0ActionField, item: new FolderReferenceV2025R0({ id: folder.id }), } satisfies HubItemOperationV2025R0, ], } satisfies HubItemsManageRequestV2025R0); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubItemsManageRequestV2025R0` - Request body of manageHubItemsV2025R0 method optionalsInput `ManageHubItemsV2025R0OptionalsInput` ### Returns This function returns a value of type `HubItemsManageResponseV2025R0`. --- ## Untitled *Type: page* IntegrationMappingsManager List Slack integration mappings Create Slack integration mapping Update Slack integration mapping Delete Slack… # IntegrationMappingsManager - [List Slack integration mappings](#list-slack-integration-mappings) - [Create Slack integration mapping](#create-slack-integration-mapping) - [Update Slack integration mapping](#update-slack-integration-mapping) - [Delete Slack integration mapping](#delete-slack-integration-mapping) - [List Teams integration mappings](#list-teams-integration-mappings) - [Create Teams integration mapping](#create-teams-integration-mapping) - [Update Teams integration mapping](#update-teams-integration-mapping) - [Delete Teams integration mapping](#delete-teams-integration-mapping) ## List Slack integration mappings Lists [Slack integration mappings](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `getSlackIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-slack/). ``` await userClient.integrationMappings.getSlackIntegrationMapping(); ``` ### Arguments queryParams `GetSlackIntegrationMappingQueryParams` - Query parameters of getSlackIntegrationMapping method headersInput `GetSlackIntegrationMappingHeadersInput` - Headers of getSlackIntegrationMapping method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `IntegrationMappings`. Returns a collection of integration mappings. ## Create Slack integration mapping Creates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) by mapping a Slack channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `createSlackIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-slack/). ``` await userClient.integrationMappings.createSlackIntegrationMapping({ partnerItem: new IntegrationMappingPartnerItemSlack({ id: slackPartnerItemId, slackOrgId: slackOrgId, }), boxItem: new IntegrationMappingBoxItemSlack({ id: folder.id }), } satisfies IntegrationMappingSlackCreateRequest); ``` ### Arguments requestBody `IntegrationMappingSlackCreateRequest` - Request body of createSlackIntegrationMapping method optionalsInput `CreateSlackIntegrationMappingOptionalsInput` ### Returns This function returns a value of type `IntegrationMapping`. Returns the created integration mapping. ## Update Slack integration mapping Updates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `updateSlackIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-slack-id/). ``` await userClient.integrationMappings.updateSlackIntegrationMappingById( slackIntegrationMapping.id, { requestBody: { boxItem: new IntegrationMappingBoxItemSlack({ id: folder.id }), } satisfies UpdateSlackIntegrationMappingByIdRequestBody, } satisfies UpdateSlackIntegrationMappingByIdOptionalsInput, ); ``` ### Arguments integrationMappingId `string` - An ID of an integration mapping. Example: "11235432" optionalsInput `UpdateSlackIntegrationMappingByIdOptionalsInput` ### Returns This function returns a value of type `IntegrationMapping`. Returns the updated integration mapping object. ## Delete Slack integration mapping Deletes a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `deleteSlackIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-slack-id/). ``` await userClient.integrationMappings.deleteSlackIntegrationMappingById( slackIntegrationMapping.id, ); ``` ### Arguments integrationMappingId `string` - An ID of an integration mapping. Example: "11235432" optionalsInput `DeleteSlackIntegrationMappingByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Empty body in response. ## List Teams integration mappings Lists [Teams integration mappings](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `getTeamsIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-teams/). ``` await userClient.integrationMappings.getTeamsIntegrationMapping(); ``` ### Arguments queryParams `GetTeamsIntegrationMappingQueryParams` - Query parameters of getTeamsIntegrationMapping method headersInput `GetTeamsIntegrationMappingHeadersInput` - Headers of getTeamsIntegrationMapping method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `IntegrationMappingsTeams`. Returns a collection of integration mappings. ## Create Teams integration mapping Creates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) by mapping a Teams channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `createTeamsIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-teams/). ``` await userClient.integrationMappings.createTeamsIntegrationMapping({ partnerItem: { type: 'channel' as IntegrationMappingPartnerItemTeamsCreateRequestTypeField, id: partnerItemId, tenantId: tenantId, teamId: teamId, } satisfies IntegrationMappingPartnerItemTeamsCreateRequest, boxItem: new FolderReference({ id: folder.id }), } satisfies IntegrationMappingTeamsCreateRequest); ``` ### Arguments requestBody `IntegrationMappingTeamsCreateRequest` - Request body of createTeamsIntegrationMapping method optionalsInput `CreateTeamsIntegrationMappingOptionalsInput` ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the created integration mapping. ## Update Teams integration mapping Updates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `updateTeamsIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-teams-id/). ``` await userClient.integrationMappings.updateTeamsIntegrationMappingById( integrationMappingId, { requestBody: { boxItem: new FolderReference({ id: '1234567' }), } satisfies UpdateTeamsIntegrationMappingByIdRequestBody, } satisfies UpdateTeamsIntegrationMappingByIdOptionalsInput, ); ``` ### Arguments integrationMappingId `string` - An ID of an integration mapping. Example: "11235432" optionalsInput `UpdateTeamsIntegrationMappingByIdOptionalsInput` ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the updated integration mapping object. ## Delete Teams integration mapping Deletes a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `deleteTeamsIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-teams-id/). ``` await userClient.integrationMappings.deleteTeamsIntegrationMappingById( integrationMappingId, ); ``` ### Arguments integrationMappingId `string` - An ID of an integration mapping. Example: "11235432" optionalsInput `DeleteTeamsIntegrationMappingByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Empty body in response. --- ## Untitled *Type: page* HubsManager List all hubs Create hub List all hubs for requesting enterprise Get hub information by ID Update hub information by ID Delete… # HubsManager - [List all hubs](#list-all-hubs) - [Create hub](#create-hub) - [List all hubs for requesting enterprise](#list-all-hubs-for-requesting-enterprise) - [Get hub information by ID](#get-hub-information-by-id) - [Update hub information by ID](#update-hub-information-by-id) - [Delete hub](#delete-hub) - [Copy hub](#copy-hub) ## List all hubs Retrieves all hubs for requesting user. This operation is performed by calling function `getHubsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs/). ``` await client.hubs.getHubsV2025R0({ scope: 'all', sort: 'name', direction: 'ASC' as GetHubsV2025R0QueryParamsDirectionField, } satisfies GetHubsV2025R0QueryParams); ``` ### Arguments queryParams `GetHubsV2025R0QueryParams` - Query parameters of getHubsV2025R0 method headersInput `GetHubsV2025R0HeadersInput` - Headers of getHubsV2025R0 method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Create hub Creates a new Hub. This operation is performed by calling function `createHubV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs/). ``` await client.hubs.createHubV2025R0({ title: hubTitle, description: hubDescription, } satisfies HubCreateRequestV2025R0); ``` ### Arguments requestBody `HubCreateRequestV2025R0` - Request body of createHubV2025R0 method optionalsInput `CreateHubV2025R0OptionalsInput` ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. ## List all hubs for requesting enterprise Retrieves all hubs for a given enterprise. Admins or Hub Co-admins of an enterprise with GCM scope can make this call. This operation is performed by calling function `getEnterpriseHubsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-enterprise-hubs/). ``` await client.hubs.getEnterpriseHubsV2025R0({ sort: 'name', direction: 'ASC' as GetEnterpriseHubsV2025R0QueryParamsDirectionField, } satisfies GetEnterpriseHubsV2025R0QueryParams); ``` ### Arguments queryParams `GetEnterpriseHubsV2025R0QueryParams` - Query parameters of getEnterpriseHubsV2025R0 method headersInput `GetEnterpriseHubsV2025R0HeadersInput` - Headers of getEnterpriseHubsV2025R0 method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Get hub information by ID Retrieves details for a hub by its ID. This operation is performed by calling function `getHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs-id/). ``` await client.hubs.getHubByIdV2025R0(hubId); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" optionalsInput `GetHubByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `HubV2025R0`. Returns a hub object. ## Update hub information by ID Updates a Hub. Can be used to change title, description, or Hub settings. This operation is performed by calling function `updateHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hubs-id/). ``` await client.hubs.updateHubByIdV2025R0(hubId, { title: newHubTitle, description: newHubDescription, } satisfies HubUpdateRequestV2025R0); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubUpdateRequestV2025R0` - Request body of updateHubByIdV2025R0 method optionalsInput `UpdateHubByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `HubV2025R0`. Returns a Hub object. ## Delete hub Deletes a single hub. This operation is performed by calling function `deleteHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hubs-id/). ``` await client.hubs.deleteHubByIdV2025R0(hubId); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" optionalsInput `DeleteHubByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the hub was successfully deleted. ## Copy hub Creates a copy of a Hub. The original Hub will not be modified. This operation is performed by calling function `copyHubV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-copy/). ``` await client.hubs.copyHubV2025R0(createdHub.id, { title: copiedHubTitle, description: copiedHubDescription, } satisfies HubCopyRequestV2025R0); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubCopyRequestV2025R0` - Request body of copyHubV2025R0 method optionalsInput `CopyHubV2025R0OptionalsInput` ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. --- ## Untitled *Type: page* InvitesManager Create user invite Get user invite status Create user invite Invites an existing external user to join an enterprise. The… # InvitesManager - [Create user invite](#create-user-invite) - [Get user invite status](#get-user-invite-status) ## Create user invite Invites an existing external user to join an enterprise. The existing user can not be part of another enterprise and must already have a Box account. Once invited, the user will receive an email and are prompted to accept the invitation within the Box web application. This method requires the "Manage An Enterprise" scope enabled for the application, which can be enabled within the developer console. This operation is performed by calling function `createInvite`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-invites/). ``` await client.invites.createInvite({ enterprise: { id: currentUser.enterprise!.id!, } satisfies CreateInviteRequestBodyEnterpriseField, actionableBy: { login: email, } satisfies CreateInviteRequestBodyActionableByField, } satisfies CreateInviteRequestBody); ``` ### Arguments requestBody `CreateInviteRequestBody` - Request body of createInvite method optionalsInput `CreateInviteOptionalsInput` ### Returns This function returns a value of type `Invite`. Returns a new invite object. ## Get user invite status Returns the status of a user invite. This operation is performed by calling function `getInviteById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-invites-id/). ``` await client.invites.getInviteById(invitation.id); ``` ### Arguments inviteId `string` - The ID of an invite. Example: "213723" optionalsInput `GetInviteByIdOptionalsInput` ### Returns This function returns a value of type `Invite`. Returns an invite object. --- ## Untitled *Type: page* LegalHoldPoliciesManager List all legal hold policies Create legal hold policy Get legal hold policy Update legal hold policy Remove legal… # LegalHoldPoliciesManager - [List all legal hold policies](#list-all-legal-hold-policies) - [Create legal hold policy](#create-legal-hold-policy) - [Get legal hold policy](#get-legal-hold-policy) - [Update legal hold policy](#update-legal-hold-policy) - [Remove legal hold policy](#remove-legal-hold-policy) ## List all legal hold policies Retrieves a list of legal hold policies that belong to an enterprise. This operation is performed by calling function `getLegalHoldPolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies/). ``` await client.legalHoldPolicies.getLegalHoldPolicies(); ``` ### Arguments queryParams `GetLegalHoldPoliciesQueryParams` - Query parameters of getLegalHoldPolicies method headersInput `GetLegalHoldPoliciesHeadersInput` - Headers of getLegalHoldPolicies method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `LegalHoldPolicies`. Returns a list of legal hold policies. ## Create legal hold policy Create a new legal hold policy. This operation is performed by calling function `createLegalHoldPolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policies/). ``` await client.legalHoldPolicies.createLegalHoldPolicy({ policyName: legalHoldPolicyName, description: legalHoldDescription, isOngoing: false, filterStartedAt: filterStartedAt, filterEndedAt: filterEndedAt, } satisfies CreateLegalHoldPolicyRequestBody); ``` ### Arguments requestBody `CreateLegalHoldPolicyRequestBody` - Request body of createLegalHoldPolicy method optionalsInput `CreateLegalHoldPolicyOptionalsInput` ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Get legal hold policy Retrieve a legal hold policy. This operation is performed by calling function `getLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies-id/). ``` await client.legalHoldPolicies.getLegalHoldPolicyById(legalHoldPolicyId); ``` ### Arguments legalHoldPolicyId `string` - The ID of the legal hold policy. Example: "324432" optionalsInput `GetLegalHoldPolicyByIdOptionalsInput` ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a legal hold policy object. ## Update legal hold policy Update legal hold policy. This operation is performed by calling function `updateLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-legal-hold-policies-id/). ``` await client.legalHoldPolicies.updateLegalHoldPolicyById(legalHoldPolicyId, { requestBody: { policyName: updatedLegalHoldPolicyName, } satisfies UpdateLegalHoldPolicyByIdRequestBody, } satisfies UpdateLegalHoldPolicyByIdOptionalsInput); ``` ### Arguments legalHoldPolicyId `string` - The ID of the legal hold policy. Example: "324432" optionalsInput `UpdateLegalHoldPolicyByIdOptionalsInput` ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Remove legal hold policy Delete an existing legal hold policy. This is an asynchronous process. The policy will not be fully deleted yet when the response returns. This operation is performed by calling function `deleteLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policies-id/). ``` await client.legalHoldPolicies.deleteLegalHoldPolicyById(legalHoldPolicy.id); ``` ### Arguments legalHoldPolicyId `string` - The ID of the legal hold policy. Example: "324432" optionalsInput `DeleteLegalHoldPolicyByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the policy was successfully deleted. --- ## Untitled *Type: page* LegalHoldPolicyAssignmentsManager List legal hold policy assignments Assign legal hold policy Get legal hold policy assignment Unassign… # LegalHoldPolicyAssignmentsManager - [List legal hold policy assignments](#list-legal-hold-policy-assignments) - [Assign legal hold policy](#assign-legal-hold-policy) - [Get legal hold policy assignment](#get-legal-hold-policy-assignment) - [Unassign legal hold policy](#unassign-legal-hold-policy) - [List files with current file versions for legal hold policy assignment](#list-files-with-current-file-versions-for-legal-hold-policy-assignment) ## List legal hold policy assignments Retrieves a list of items a legal hold policy has been assigned to. This operation is performed by calling function `getLegalHoldPolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments/). ``` await client.legalHoldPolicyAssignments.getLegalHoldPolicyAssignments({ policyId: legalHoldPolicyId, } satisfies GetLegalHoldPolicyAssignmentsQueryParams); ``` ### Arguments queryParams `GetLegalHoldPolicyAssignmentsQueryParams` - Query parameters of getLegalHoldPolicyAssignments method optionalsInput `GetLegalHoldPolicyAssignmentsOptionalsInput` ### Returns This function returns a value of type `LegalHoldPolicyAssignments`. Returns a list of legal hold policy assignments. ## Assign legal hold policy Assign a legal hold to a file, file version, folder, or user. This operation is performed by calling function `createLegalHoldPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policy-assignments/). ``` await client.legalHoldPolicyAssignments.createLegalHoldPolicyAssignment({ policyId: legalHoldPolicyId, assignTo: { type: 'file' as CreateLegalHoldPolicyAssignmentRequestBodyAssignToTypeField, id: fileId, } satisfies CreateLegalHoldPolicyAssignmentRequestBodyAssignToField, } satisfies CreateLegalHoldPolicyAssignmentRequestBody); ``` ### Arguments requestBody `CreateLegalHoldPolicyAssignmentRequestBody` - Request body of createLegalHoldPolicyAssignment method optionalsInput `CreateLegalHoldPolicyAssignmentOptionalsInput` ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a new legal hold policy assignment. ## Get legal hold policy assignment Retrieve a legal hold policy assignment. This operation is performed by calling function `getLegalHoldPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id/). ``` await client.legalHoldPolicyAssignments.getLegalHoldPolicyAssignmentById( legalHoldPolicyAssignmentId, ); ``` ### Arguments legalHoldPolicyAssignmentId `string` - The ID of the legal hold policy assignment. Example: "753465" optionalsInput `GetLegalHoldPolicyAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a legal hold policy object. ## Unassign legal hold policy Remove a legal hold from an item. This is an asynchronous process. The policy will not be fully removed yet when the response returns. This operation is performed by calling function `deleteLegalHoldPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policy-assignments-id/). ``` await client.legalHoldPolicyAssignments.deleteLegalHoldPolicyAssignmentById( legalHoldPolicyAssignmentId, ); ``` ### Arguments legalHoldPolicyAssignmentId `string` - The ID of the legal hold policy assignment. Example: "753465" optionalsInput `DeleteLegalHoldPolicyAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the assignment was successfully deleted. ## List files with current file versions for legal hold policy assignment Get a list of files with current file versions for a legal hold assignment. In some cases you may want to get previous file versions instead. In these cases, use the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API instead to return any previous versions of a file for this legal hold policy assignment. Due to ongoing re-architecture efforts this API might not return all file versions held for this policy ID. Instead, this API will only return the latest file version held in the newly developed architecture. The `GET /file_version_legal_holds` API can be used to fetch current and past versions of files held within the legacy architecture. This endpoint does not support returning any content that is on hold due to a Custodian collaborating on a Hub. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. This operation is performed by calling function `getLegalHoldPolicyAssignmentFileOnHold`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id-files-on-hold/). ``` await client.legalHoldPolicyAssignments.getLegalHoldPolicyAssignmentFileOnHold( legalHoldPolicyAssignmentId, ); ``` ### Arguments legalHoldPolicyAssignmentId `string` - The ID of the legal hold policy assignment. Example: "753465" optionalsInput `GetLegalHoldPolicyAssignmentFileOnHoldOptionalsInput` ### Returns This function returns a value of type `FilesOnHold`. Returns the list of current file versions held under legal hold for a specific legal hold policy assignment. --- ## Untitled *Type: page* ListCollaborationsManager List file collaborations List folder collaborations List pending collaborations List group collaborations List… # ListCollaborationsManager - [List file collaborations](#list-file-collaborations) - [List folder collaborations](#list-folder-collaborations) - [List pending collaborations](#list-pending-collaborations) - [List group collaborations](#list-group-collaborations) ## List file collaborations Retrieves a list of pending and active collaborations for a file. This returns all the users that have access to the file or have been invited to the file. This operation is performed by calling function `getFileCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-collaborations/). ``` await client.listCollaborations.getFileCollaborations(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetFileCollaborationsOptionalsInput` ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this file an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List folder collaborations Retrieves a list of pending and active collaborations for a folder. This returns all the users that have access to the folder or have been invited to the folder. This operation is performed by calling function `getFolderCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-collaborations/). ``` await client.listCollaborations.getFolderCollaborations(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. Example: "12345" optionalsInput `GetFolderCollaborationsOptionalsInput` ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this folder an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List pending collaborations Retrieves all pending collaboration invites for this user. This operation is performed by calling function `getCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations/). ``` await client.listCollaborations.getCollaborations({ status: 'pending' as GetCollaborationsQueryParamsStatusField, } satisfies GetCollaborationsQueryParams); ``` ### Arguments queryParams `GetCollaborationsQueryParams` - Query parameters of getCollaborations method optionalsInput `GetCollaborationsOptionalsInput` ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of pending collaboration objects. If the user has no pending collaborations, the collection will be empty. ## List group collaborations Retrieves all the collaborations for a group. The user must have admin permissions to inspect enterprise's groups. Each collaboration object has details on which files or folders the group has access to and with what role. This operation is performed by calling function `getGroupCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-collaborations/). ``` await client.listCollaborations.getGroupCollaborations(group.id); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" optionalsInput `GetGroupCollaborationsOptionalsInput` ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of collaboration objects. If there are no collaborations, an empty collection will be returned. --- ## Untitled *Type: page* MembershipsManager List user's groups List members of group Add user to group Get group membership Update group membership Remove user from… # MembershipsManager - [List user's groups](#list-users-groups) - [List members of group](#list-members-of-group) - [Add user to group](#add-user-to-group) - [Get group membership](#get-group-membership) - [Update group membership](#update-group-membership) - [Remove user from group](#remove-user-from-group) ## List user's groups Retrieves all the groups for a user. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getUserMemberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-memberships/). ``` await client.memberships.getUserMemberships(user.id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" optionalsInput `GetUserMembershipsOptionalsInput` ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## List members of group Retrieves all the members for a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupMemberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-memberships/). ``` await client.memberships.getGroupMemberships(group.id); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" optionalsInput `GetGroupMembershipsOptionalsInput` ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## Add user to group Creates a group membership. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `createGroupMembership`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-group-memberships/). ``` await client.memberships.createGroupMembership({ user: { id: user.id } satisfies CreateGroupMembershipRequestBodyUserField, group: { id: group.id } satisfies CreateGroupMembershipRequestBodyGroupField, } satisfies CreateGroupMembershipRequestBody); ``` ### Arguments requestBody `CreateGroupMembershipRequestBody` - Request body of createGroupMembership method optionalsInput `CreateGroupMembershipOptionalsInput` ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Get group membership Retrieves a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-group-memberships-id/). ``` await client.memberships.getGroupMembershipById(groupMembership.id!); ``` ### Arguments groupMembershipId `string` - The ID of the group membership. Example: "434534" optionalsInput `GetGroupMembershipByIdOptionalsInput` ### Returns This function returns a value of type `GroupMembership`. Returns the group membership object. ## Update group membership Updates a user's group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `updateGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-group-memberships-id/). ``` await client.memberships.updateGroupMembershipById(groupMembership.id!, { requestBody: { role: 'admin' as UpdateGroupMembershipByIdRequestBodyRoleField, } satisfies UpdateGroupMembershipByIdRequestBody, } satisfies UpdateGroupMembershipByIdOptionalsInput); ``` ### Arguments groupMembershipId `string` - The ID of the group membership. Example: "434534" optionalsInput `UpdateGroupMembershipByIdOptionalsInput` ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Remove user from group Deletes a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `deleteGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-group-memberships-id/). ``` await client.memberships.deleteGroupMembershipById(groupMembership.id!); ``` ### Arguments groupMembershipId `string` - The ID of the group membership. Example: "434534" optionalsInput `DeleteGroupMembershipByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the membership was successfully deleted. --- ## Untitled *Type: page* MetadataCascadePoliciesManager List metadata cascade policies Create metadata cascade policy Get metadata cascade policy Remove metadata… # MetadataCascadePoliciesManager - [List metadata cascade policies](#list-metadata-cascade-policies) - [Create metadata cascade policy](#create-metadata-cascade-policy) - [Get metadata cascade policy](#get-metadata-cascade-policy) - [Remove metadata cascade policy](#remove-metadata-cascade-policy) - [Force-apply metadata cascade policy to folder](#force-apply-metadata-cascade-policy-to-folder) ## List metadata cascade policies Retrieves a list of all the metadata cascade policies that are applied to a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getMetadataCascadePolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies/). ``` await client.metadataCascadePolicies.getMetadataCascadePolicies({ folderId: folder.id, } satisfies GetMetadataCascadePoliciesQueryParams); ``` ### Arguments queryParams `GetMetadataCascadePoliciesQueryParams` - Query parameters of getMetadataCascadePolicies method optionalsInput `GetMetadataCascadePoliciesOptionalsInput` ### Returns This function returns a value of type `MetadataCascadePolicies`. Returns a list of metadata cascade policies. ## Create metadata cascade policy Creates a new metadata cascade policy that applies a given metadata template to a given folder and automatically cascades it down to any files within that folder. In order for the policy to be applied a metadata instance must first be applied to the folder the policy is to be applied to. This operation is performed by calling function `createMetadataCascadePolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies/). ``` await client.metadataCascadePolicies.createMetadataCascadePolicy({ folderId: folder.id, scope: 'enterprise' as CreateMetadataCascadePolicyRequestBodyScopeField, templateKey: templateKey, } satisfies CreateMetadataCascadePolicyRequestBody); ``` ### Arguments requestBody `CreateMetadataCascadePolicyRequestBody` - Request body of createMetadataCascadePolicy method optionalsInput `CreateMetadataCascadePolicyOptionalsInput` ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a new of metadata cascade policy. ## Get metadata cascade policy Retrieve a specific metadata cascade policy assigned to a folder. This operation is performed by calling function `getMetadataCascadePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies-id/). ``` await client.metadataCascadePolicies.getMetadataCascadePolicyById( cascadePolicyId, ); ``` ### Arguments metadataCascadePolicyId `string` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" optionalsInput `GetMetadataCascadePolicyByIdOptionalsInput` ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a metadata cascade policy. ## Remove metadata cascade policy Deletes a metadata cascade policy. This operation is performed by calling function `deleteMetadataCascadePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-cascade-policies-id/). ``` await client.metadataCascadePolicies.deleteMetadataCascadePolicyById( cascadePolicyId, ); ``` ### Arguments metadataCascadePolicyId `string` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" optionalsInput `DeleteMetadataCascadePolicyByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the policy is successfully deleted. ## Force-apply metadata cascade policy to folder Force the metadata on a folder with a metadata cascade policy to be applied to all of its children. This can be used after creating a new cascade policy to enforce the metadata to be cascaded down to all existing files within that folder. This operation is performed by calling function `applyMetadataCascadePolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies-id-apply/). ``` await client.metadataCascadePolicies.applyMetadataCascadePolicy( cascadePolicyId, { conflictResolution: 'overwrite' as ApplyMetadataCascadePolicyRequestBodyConflictResolutionField, } satisfies ApplyMetadataCascadePolicyRequestBody, ); ``` ### Arguments metadataCascadePolicyId `string` - The ID of the cascade policy to force-apply. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" requestBody `ApplyMetadataCascadePolicyRequestBody` - Request body of applyMetadataCascadePolicy method optionalsInput `ApplyMetadataCascadePolicyOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the API call was successful. The metadata cascade operation will be performed asynchronously. The API call will return directly, before the cascade operation is complete. There is currently no API to check for the status of this operation. --- ## Untitled *Type: page* RetentionPolicyAssignmentsManager List retention policy assignments Assign retention policy Get retention policy assignment Remove retention… # RetentionPolicyAssignmentsManager - [List retention policy assignments](#list-retention-policy-assignments) - [Assign retention policy](#assign-retention-policy) - [Get retention policy assignment](#get-retention-policy-assignment) - [Remove retention policy assignment](#remove-retention-policy-assignment) - [Get files under retention](#get-files-under-retention) ## List retention policy assignments Returns a list of all retention policy assignments associated with a specified retention policy. This operation is performed by calling function `getRetentionPolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id-assignments/). ``` await client.retentionPolicyAssignments.getRetentionPolicyAssignments( retentionPolicy.id, ); ``` ### Arguments retentionPolicyId `string` - The ID of the retention policy. Example: "982312" optionalsInput `GetRetentionPolicyAssignmentsOptionalsInput` ### Returns This function returns a value of type `RetentionPolicyAssignments`. Returns a list of the retention policy assignments associated with the specified retention policy. ## Assign retention policy Assigns a retention policy to an item. This operation is performed by calling function `createRetentionPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policy-assignments/). ``` await client.retentionPolicyAssignments.createRetentionPolicyAssignment({ policyId: retentionPolicy.id, assignTo: { type: 'folder' as CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField, id: folder.id, } satisfies CreateRetentionPolicyAssignmentRequestBodyAssignToField, } satisfies CreateRetentionPolicyAssignmentRequestBody); ``` ### Arguments requestBody `CreateRetentionPolicyAssignmentRequestBody` - Request body of createRetentionPolicyAssignment method optionalsInput `CreateRetentionPolicyAssignmentOptionalsInput` ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns a new retention policy assignment object. ## Get retention policy assignment Retrieves a retention policy assignment. This operation is performed by calling function `getRetentionPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id/). ``` await client.retentionPolicyAssignments.getRetentionPolicyAssignmentById( retentionPolicyAssignment.id, ); ``` ### Arguments retentionPolicyAssignmentId `string` - The ID of the retention policy assignment. Example: "1233123" optionalsInput `GetRetentionPolicyAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns the retention policy assignment object. ## Remove retention policy assignment Removes a retention policy assignment applied to content. This operation is performed by calling function `deleteRetentionPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policy-assignments-id/). ``` await client.retentionPolicyAssignments.deleteRetentionPolicyAssignmentById( retentionPolicyAssignment.id, ); ``` ### Arguments retentionPolicyAssignmentId `string` - The ID of the retention policy assignment. Example: "1233123" optionalsInput `DeleteRetentionPolicyAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the policy assignment is successfully deleted. ## Get files under retention Returns a list of files under retention for a retention policy assignment. This operation is performed by calling function `getFilesUnderRetentionPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention/). ``` await client.retentionPolicyAssignments.getFilesUnderRetentionPolicyAssignment( retentionPolicyAssignment.id, ); ``` ### Arguments retentionPolicyAssignmentId `string` - The ID of the retention policy assignment. Example: "1233123" optionalsInput `GetFilesUnderRetentionPolicyAssignmentOptionalsInput` ### Returns This function returns a value of type `FilesUnderRetention`. Returns a list of files under retention that are associated with the specified retention policy assignment. --- ## Untitled *Type: page* SearchManager Query files/folders by metadata Search for content Query files/folders by metadata Create a search using SQL-like syntax to… # SearchManager - [Query files/folders by metadata](#query-files-folders-by-metadata) - [Search for content](#search-for-content) ## Query files/folders by metadata Create a search using SQL-like syntax to return items that match specific metadata. By default, this endpoint returns only the most basic info about the items for which the query matches. To get additional fields for each item, including any of the metadata, use the `fields` attribute in the query. This operation is performed by calling function `searchByMetadataQuery`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-queries-execute-read/). ``` await client.search.searchByMetadataQuery({ ancestorFolderId: '0', from: searchFrom, query: 'name = :name AND age < :age AND birthDate >= :birthDate AND countryCode = :countryCode AND sports = :sports', queryParams: { ['name']: 'John', ['age']: 50, ['birthDate']: '2001-01-01T02:20:10.120Z', ['countryCode']: 'US', ['sports']: ['basketball', 'tennis'], }, } satisfies MetadataQuery); ``` ### Arguments requestBody `MetadataQuery` - Request body of searchByMetadataQuery method optionalsInput `SearchByMetadataQueryOptionalsInput` ### Returns This function returns a value of type `MetadataQueryResults`. Returns a list of files and folders that match this metadata query. ## Search for content Searches for files, folders, web links, and shared files across the users content or across the entire enterprise. This operation is performed by calling function `searchForContent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-search/). ``` await client.search.searchForContent({ ancestorFolderIds: ['0'], mdfilters: [ { filters: searchFilters, scope: 'enterprise' as MetadataFilterScopeField, templateKey: templateKey, } satisfies MetadataFilter, ], } satisfies SearchForContentQueryParams); ``` ### Arguments queryParams `SearchForContentQueryParams` - Query parameters of searchForContent method headersInput `SearchForContentHeadersInput` - Headers of searchForContent method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `SearchResultsOrSearchResultsWithSharedLinks`. Returns a collection of search results. If there are no matching search results, the `entries` array will be empty. --- ## Untitled *Type: page* MetadataTemplatesManager Find metadata template by instance ID Get metadata template by name Update metadata template Remove metadata… # MetadataTemplatesManager - [Find metadata template by instance ID](#find-metadata-template-by-instance-id) - [Get metadata template by name](#get-metadata-template-by-name) - [Update metadata template](#update-metadata-template) - [Remove metadata template](#remove-metadata-template) - [Get metadata template by ID](#get-metadata-template-by-id) - [List all global metadata templates](#list-all-global-metadata-templates) - [List all metadata templates for enterprise](#list-all-metadata-templates-for-enterprise) - [Create metadata template](#create-metadata-template) ## Find metadata template by instance ID Finds a metadata template by searching for the ID of an instance of the template. This operation is performed by calling function `getMetadataTemplatesByInstanceId`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates/). ``` await client.metadataTemplates.getMetadataTemplatesByInstanceId({ metadataInstanceId: createdMetadataInstance.id!, } satisfies GetMetadataTemplatesByInstanceIdQueryParams); ``` ### Arguments queryParams `GetMetadataTemplatesByInstanceIdQueryParams` - Query parameters of getMetadataTemplatesByInstanceId method optionalsInput `GetMetadataTemplatesByInstanceIdOptionalsInput` ### Returns This function returns a value of type `MetadataTemplates`. Returns a list containing the 1 metadata template that matches the instance ID. ## Get metadata template by name Retrieves a metadata template by its `scope` and `templateKey` values. To find the `scope` and `templateKey` for a template, list all templates for an enterprise or globally, or list all templates applied to a file or folder. This operation is performed by calling function `getMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id-id-schema/). ``` await client.metadataTemplates.getMetadataTemplate( 'enterprise' as GetMetadataTemplateScope, template.templateKey!, ); ``` ### Arguments scope `GetMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" optionalsInput `GetMetadataTemplateOptionalsInput` ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template matching the `scope` and `template` name. ## Update metadata template Updates a metadata template. The metadata template can only be updated if the template already exists. The update is applied atomically. If any errors occur during the application of the operations, the metadata template will not be changed. This operation is performed by calling function `updateMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-id-id-schema/). ``` await client.metadataTemplates.updateMetadataTemplate( 'enterprise' as UpdateMetadataTemplateScope, templateKey, [ { op: 'addField' as UpdateMetadataTemplateRequestBodyOpField, fieldKey: 'newfieldname', data: { ['type']: 'string', ['displayName']: 'newFieldName' }, } satisfies UpdateMetadataTemplateRequestBody, ], ); ``` ### Arguments scope `UpdateMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `readonly UpdateMetadataTemplateRequestBody[]` - Request body of updateMetadataTemplate method optionalsInput `UpdateMetadataTemplateOptionalsInput` ### Returns This function returns a value of type `MetadataTemplate`. Returns the updated metadata template, with the custom template data included. ## Remove metadata template Delete a metadata template and its instances. This deletion is permanent and can not be reversed. This operation is performed by calling function `deleteMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-templates-id-id-schema/). ``` await client.metadataTemplates.deleteMetadataTemplate( 'enterprise' as DeleteMetadataTemplateScope, template.templateKey!, ); ``` ### Arguments scope `DeleteMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" optionalsInput `DeleteMetadataTemplateOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the metadata template is successfully deleted. ## Get metadata template by ID Retrieves a metadata template by its ID. This operation is performed by calling function `getMetadataTemplateById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id/). ``` await client.metadataTemplates.getMetadataTemplateById(template.id); ``` ### Arguments templateId `string` - The ID of the template. Example: "f7a9891f" optionalsInput `GetMetadataTemplateByIdOptionalsInput` ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template that matches the ID. ## List all global metadata templates Used to retrieve all generic, global metadata templates available to all enterprises using Box. This operation is performed by calling function `getGlobalMetadataTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-global/). ``` await client.metadataTemplates.getGlobalMetadataTemplates(); ``` ### Arguments queryParams `GetGlobalMetadataTemplatesQueryParams` - Query parameters of getGlobalMetadataTemplates method headersInput `GetGlobalMetadataTemplatesHeadersInput` - Headers of getGlobalMetadataTemplates method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates available to all enterprises and their corresponding schema. ## List all metadata templates for enterprise Used to retrieve all metadata templates created to be used specifically within the user's enterprise. This operation is performed by calling function `getEnterpriseMetadataTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise/). ``` await client.metadataTemplates.getEnterpriseMetadataTemplates(); ``` ### Arguments queryParams `GetEnterpriseMetadataTemplatesQueryParams` - Query parameters of getEnterpriseMetadataTemplates method headersInput `GetEnterpriseMetadataTemplatesHeadersInput` - Headers of getEnterpriseMetadataTemplates method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates within an enterprise and their corresponding schema. ## Create metadata template Creates a new metadata template that can be applied to files and folders. This operation is performed by calling function `createMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema/). ``` await client.metadataTemplates.createMetadataTemplate({ scope: 'enterprise', displayName: templateKey, templateKey: templateKey, fields: [ { type: 'string' as CreateMetadataTemplateRequestBodyFieldsTypeField, key: 'testName', displayName: 'testName', } satisfies CreateMetadataTemplateRequestBodyFieldsField, { type: 'float' as CreateMetadataTemplateRequestBodyFieldsTypeField, key: 'age', displayName: 'age', } satisfies CreateMetadataTemplateRequestBodyFieldsField, { type: 'date' as CreateMetadataTemplateRequestBodyFieldsTypeField, key: 'birthDate', displayName: 'birthDate', } satisfies CreateMetadataTemplateRequestBodyFieldsField, { type: 'enum' as CreateMetadataTemplateRequestBodyFieldsTypeField, key: 'countryCode', displayName: 'countryCode', options: [ { key: 'US', } satisfies CreateMetadataTemplateRequestBodyFieldsOptionsField, { key: 'CA', } satisfies CreateMetadataTemplateRequestBodyFieldsOptionsField, ], } satisfies CreateMetadataTemplateRequestBodyFieldsField, { type: 'multiSelect' as CreateMetadataTemplateRequestBodyFieldsTypeField, key: 'sports', displayName: 'sports', options: [ { key: 'basketball', } satisfies CreateMetadataTemplateRequestBodyFieldsOptionsField, { key: 'football', } satisfies CreateMetadataTemplateRequestBodyFieldsOptionsField, { key: 'tennis', } satisfies CreateMetadataTemplateRequestBodyFieldsOptionsField, ], } satisfies CreateMetadataTemplateRequestBodyFieldsField, ], } satisfies CreateMetadataTemplateRequestBody); ``` ### Arguments requestBody `CreateMetadataTemplateRequestBody` - Request body of createMetadataTemplate method optionalsInput `CreateMetadataTemplateOptionalsInput` ### Returns This function returns a value of type `MetadataTemplate`. The schema representing the metadata template created. --- ## Untitled *Type: page* SessionTerminationManager Create jobs to terminate users session Create jobs to terminate user group session Create jobs to terminate users… # SessionTerminationManager - [Create jobs to terminate users session](#create-jobs-to-terminate-users-session) - [Create jobs to terminate user group session](#create-jobs-to-terminate-user-group-session) ## Create jobs to terminate users session Validates the roles and permissions of the user, and creates asynchronous jobs to terminate the user's sessions. Returns the status for the POST request. This operation is performed by calling function `terminateUsersSessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-terminate-sessions/). ``` await client.sessionTermination.terminateUsersSessions({ userIds: [getEnvVar('USER_ID')], userLogins: [user.login!], } satisfies TerminateUsersSessionsRequestBody); ``` ### Arguments requestBody `TerminateUsersSessionsRequestBody` - Request body of terminateUsersSessions method optionalsInput `TerminateUsersSessionsOptionalsInput` ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. ## Create jobs to terminate user group session Validates the roles and permissions of the group, and creates asynchronous jobs to terminate the group's sessions. Returns the status for the POST request. This operation is performed by calling function `terminateGroupsSessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups-terminate-sessions/). ``` await client.sessionTermination.terminateGroupsSessions({ groupIds: [group.id], } satisfies TerminateGroupsSessionsRequestBody); ``` ### Arguments requestBody `TerminateGroupsSessionsRequestBody` - Request body of terminateGroupsSessions method optionalsInput `TerminateGroupsSessionsOptionalsInput` ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. --- ## Untitled *Type: page* RecentItemsManager List recently accessed items List recently accessed items Returns information about the recent items accessed by a user… # RecentItemsManager - [List recently accessed items](#list-recently-accessed-items) ## List recently accessed items Returns information about the recent items accessed by a user, either in the last 90 days or up to the last 1000 items accessed. This operation is performed by calling function `getRecentItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-recent-items/). ``` await client.recentItems.getRecentItems(); ``` ### Arguments queryParams `GetRecentItemsQueryParams` - Query parameters of getRecentItems method headersInput `GetRecentItemsHeadersInput` - Headers of getRecentItems method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `RecentItems`. Returns a list recent items access by a user. --- ## Untitled *Type: page* SharedLinksAppItemsManager Find app item for shared link Find app item for shared link Returns the app item represented by a shared link… # SharedLinksAppItemsManager - [Find app item for shared link](#find-app-item-for-shared-link) ## Find app item for shared link Returns the app item represented by a shared link. The link can originate from the current enterprise or another. This operation is performed by calling function `findAppItemForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--app-items/). ``` await client.sharedLinksAppItems.findAppItemForSharedLink({ boxapi: ''.concat('shared_link=', appItemSharedLink) as string, } satisfies FindAppItemForSharedLinkHeadersInput); ``` ### Arguments headersInput `FindAppItemForSharedLinkHeadersInput` - Headers of findAppItemForSharedLink method optionalsInput `FindAppItemForSharedLinkOptionalsInput` ### Returns This function returns a value of type `AppItem`. Returns a full app item resource if the shared link is valid and the user has access to it. --- ## Untitled *Type: page* RetentionPoliciesManager List retention policies Create retention policy Get retention policy Update retention policy Delete retention… # RetentionPoliciesManager - [List retention policies](#list-retention-policies) - [Create retention policy](#create-retention-policy) - [Get retention policy](#get-retention-policy) - [Update retention policy](#update-retention-policy) - [Delete retention policy](#delete-retention-policy) ## List retention policies Retrieves all of the retention policies for an enterprise. This operation is performed by calling function `getRetentionPolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies/). ``` await client.retentionPolicies.getRetentionPolicies(); ``` ### Arguments queryParams `GetRetentionPoliciesQueryParams` - Query parameters of getRetentionPolicies method headersInput `GetRetentionPoliciesHeadersInput` - Headers of getRetentionPolicies method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `RetentionPolicies`. Returns a list retention policies in the enterprise. ## Create retention policy Creates a retention policy. This operation is performed by calling function `createRetentionPolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policies/). ``` await client.retentionPolicies.createRetentionPolicy({ policyName: retentionPolicyName, policyType: 'finite' as CreateRetentionPolicyRequestBodyPolicyTypeField, areOwnersNotified: true, canOwnerExtendRetention: true, description: retentionDescription, dispositionAction: 'remove_retention' as CreateRetentionPolicyRequestBodyDispositionActionField, retentionLength: '1', retentionType: 'modifiable' as CreateRetentionPolicyRequestBodyRetentionTypeField, } satisfies CreateRetentionPolicyRequestBody); ``` ### Arguments requestBody `CreateRetentionPolicyRequestBody` - Request body of createRetentionPolicy method optionalsInput `CreateRetentionPolicyOptionalsInput` ### Returns This function returns a value of type `RetentionPolicy`. Returns a new retention policy object. ## Get retention policy Retrieves a retention policy. This operation is performed by calling function `getRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id/). ``` await client.retentionPolicies.getRetentionPolicyById(retentionPolicy.id); ``` ### Arguments retentionPolicyId `string` - The ID of the retention policy. Example: "982312" optionalsInput `GetRetentionPolicyByIdOptionalsInput` ### Returns This function returns a value of type `RetentionPolicy`. Returns the retention policy object. ## Update retention policy Updates a retention policy. This operation is performed by calling function `updateRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-retention-policies-id/). ``` await client.retentionPolicies.updateRetentionPolicyById(retentionPolicy.id, { requestBody: { policyName: updatedRetentionPolicyName, } satisfies UpdateRetentionPolicyByIdRequestBody, } satisfies UpdateRetentionPolicyByIdOptionalsInput); ``` ### Arguments retentionPolicyId `string` - The ID of the retention policy. Example: "982312" optionalsInput `UpdateRetentionPolicyByIdOptionalsInput` ### Returns This function returns a value of type `RetentionPolicy`. Returns the updated retention policy object. ## Delete retention policy Permanently deletes a retention policy. This operation is performed by calling function `deleteRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policies-id/). ``` await client.retentionPolicies.deleteRetentionPolicyById(retentionPolicy.id); ``` ### Arguments retentionPolicyId `string` - The ID of the retention policy. Example: "982312" optionalsInput `DeleteRetentionPolicyByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the policy has been deleted. --- ## Untitled *Type: page* SharedLinksFilesManager Find file for shared link Get shared link for file Add shared link to file Update shared link on file Remove shared… # SharedLinksFilesManager - [Find file for shared link](#find-file-for-shared-link) - [Get shared link for file](#get-shared-link-for-file) - [Add shared link to file](#add-shared-link-to-file) - [Update shared link on file](#update-shared-link-on-file) - [Remove shared link from file](#remove-shared-link-from-file) ## Find file for shared link Returns the file represented by a shared link. A shared file can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared file when only given a shared link. The `shared_link_permission_options` array field can be returned by requesting it in the `fields` query parameter. This operation is performed by calling function `findFileForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items/). ``` await userClient.sharedLinksFiles.findFileForSharedLink( {} satisfies FindFileForSharedLinkQueryParams, { boxapi: ''.concat( 'shared_link=', fileFromApi.sharedLink!.url, '&shared_link_password=Secret123@', ) as string, } satisfies FindFileForSharedLinkHeadersInput, ); ``` ### Arguments queryParams `FindFileForSharedLinkQueryParams` - Query parameters of findFileForSharedLink method headersInput `FindFileForSharedLinkHeadersInput` - Headers of findFileForSharedLink method optionalsInput `FindFileForSharedLinkOptionalsInput` ### Returns This function returns a value of type `FileFull`. Returns a full file resource if the shared link is valid and the user has access to it. ## Get shared link for file Gets the information for a shared link on a file. This operation is performed by calling function `getSharedLinkForFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id--get-shared-link/). ``` await client.sharedLinksFiles.getSharedLinkForFile(fileId, { fields: 'shared_link', } satisfies GetSharedLinkForFileQueryParams); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetSharedLinkForFileQueryParams` - Query parameters of getSharedLinkForFile method optionalsInput `GetSharedLinkForFileOptionalsInput` ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with the additional shared link information. ## Add shared link to file Adds a shared link to a file. This operation is performed by calling function `addShareLinkToFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--add-shared-link/). ``` await client.sharedLinksFiles.addShareLinkToFile( fileId, { sharedLink: { access: 'open' as AddShareLinkToFileRequestBodySharedLinkAccessField, password: 'Secret123@', } satisfies AddShareLinkToFileRequestBodySharedLinkField, } satisfies AddShareLinkToFileRequestBody, { fields: 'shared_link' } satisfies AddShareLinkToFileQueryParams, ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `AddShareLinkToFileRequestBody` - Request body of addShareLinkToFile method queryParams `AddShareLinkToFileQueryParams` - Query parameters of addShareLinkToFile method optionalsInput `AddShareLinkToFileOptionalsInput` ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with a new shared link attached. ## Update shared link on file Updates a shared link on a file. This operation is performed by calling function `updateSharedLinkOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--update-shared-link/). ``` await client.sharedLinksFiles.updateSharedLinkOnFile( fileId, { sharedLink: { access: 'collaborators' as UpdateSharedLinkOnFileRequestBodySharedLinkAccessField, } satisfies UpdateSharedLinkOnFileRequestBodySharedLinkField, } satisfies UpdateSharedLinkOnFileRequestBody, { fields: 'shared_link' } satisfies UpdateSharedLinkOnFileQueryParams, ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateSharedLinkOnFileRequestBody` - Request body of updateSharedLinkOnFile method queryParams `UpdateSharedLinkOnFileQueryParams` - Query parameters of updateSharedLinkOnFile method optionalsInput `UpdateSharedLinkOnFileOptionalsInput` ### Returns This function returns a value of type `FileFull`. Returns a basic representation of the file, with the updated shared link attached. ## Remove shared link from file Removes a shared link from a file. This operation is performed by calling function `removeSharedLinkFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--remove-shared-link/). ``` await client.sharedLinksFiles.removeSharedLinkFromFile( fileId, { sharedLink: createNull() } satisfies RemoveSharedLinkFromFileRequestBody, { fields: 'shared_link' } satisfies RemoveSharedLinkFromFileQueryParams, ); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `RemoveSharedLinkFromFileRequestBody` - Request body of removeSharedLinkFromFile method queryParams `RemoveSharedLinkFromFileQueryParams` - Query parameters of removeSharedLinkFromFile method optionalsInput `RemoveSharedLinkFromFileOptionalsInput` ### Returns This function returns a value of type `FileFull`. Returns a basic representation of a file, with the shared link removed. --- ## Untitled *Type: page* SharedLinksFoldersManager Find folder for shared link Get shared link for folder Add shared link to folder Update shared link on folder… # SharedLinksFoldersManager - [Find folder for shared link](#find-folder-for-shared-link) - [Get shared link for folder](#get-shared-link-for-folder) - [Add shared link to folder](#add-shared-link-to-folder) - [Update shared link on folder](#update-shared-link-on-folder) - [Remove shared link from folder](#remove-shared-link-from-folder) ## Find folder for shared link Return the folder represented by a shared link. A shared folder can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared folder when only given a shared link. This operation is performed by calling function `findFolderForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--folders/). ``` await userClient.sharedLinksFolders.findFolderForSharedLink( {} satisfies FindFolderForSharedLinkQueryParams, { boxapi: ''.concat( 'shared_link=', folderFromApi.sharedLink!.url, '&shared_link_password=Secret123@', ) as string, } satisfies FindFolderForSharedLinkHeadersInput, ); ``` ### Arguments queryParams `FindFolderForSharedLinkQueryParams` - Query parameters of findFolderForSharedLink method headersInput `FindFolderForSharedLinkHeadersInput` - Headers of findFolderForSharedLink method optionalsInput `FindFolderForSharedLinkOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns a full folder resource if the shared link is valid and the user has access to it. ## Get shared link for folder Gets the information for a shared link on a folder. This operation is performed by calling function `getSharedLinkForFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id--get-shared-link/). ``` await client.sharedLinksFolders.getSharedLinkForFolder(folder.id, { fields: 'shared_link', } satisfies GetSharedLinkForFolderQueryParams); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetSharedLinkForFolderQueryParams` - Query parameters of getSharedLinkForFolder method optionalsInput `GetSharedLinkForFolderOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with the additional shared link information. ## Add shared link to folder Adds a shared link to a folder. This operation is performed by calling function `addShareLinkToFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--add-shared-link/). ``` await client.sharedLinksFolders.addShareLinkToFolder( folder.id, { sharedLink: { access: 'open' as AddShareLinkToFolderRequestBodySharedLinkAccessField, password: 'Secret123@', } satisfies AddShareLinkToFolderRequestBodySharedLinkField, } satisfies AddShareLinkToFolderRequestBody, { fields: 'shared_link' } satisfies AddShareLinkToFolderQueryParams, ); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `AddShareLinkToFolderRequestBody` - Request body of addShareLinkToFolder method queryParams `AddShareLinkToFolderQueryParams` - Query parameters of addShareLinkToFolder method optionalsInput `AddShareLinkToFolderOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with a new shared link attached. ## Update shared link on folder Updates a shared link on a folder. This operation is performed by calling function `updateSharedLinkOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--update-shared-link/). ``` await client.sharedLinksFolders.updateSharedLinkOnFolder( folder.id, { sharedLink: { access: 'collaborators' as UpdateSharedLinkOnFolderRequestBodySharedLinkAccessField, } satisfies UpdateSharedLinkOnFolderRequestBodySharedLinkField, } satisfies UpdateSharedLinkOnFolderRequestBody, { fields: 'shared_link' } satisfies UpdateSharedLinkOnFolderQueryParams, ); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateSharedLinkOnFolderRequestBody` - Request body of updateSharedLinkOnFolder method queryParams `UpdateSharedLinkOnFolderQueryParams` - Query parameters of updateSharedLinkOnFolder method optionalsInput `UpdateSharedLinkOnFolderOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of the folder, with the updated shared link attached. ## Remove shared link from folder Removes a shared link from a folder. This operation is performed by calling function `removeSharedLinkFromFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--remove-shared-link/). ``` await client.sharedLinksFolders.removeSharedLinkFromFolder( folder.id, { sharedLink: createNull() } satisfies RemoveSharedLinkFromFolderRequestBody, { fields: 'shared_link' } satisfies RemoveSharedLinkFromFolderQueryParams, ); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `RemoveSharedLinkFromFolderRequestBody` - Request body of removeSharedLinkFromFolder method queryParams `RemoveSharedLinkFromFolderQueryParams` - Query parameters of removeSharedLinkFromFolder method optionalsInput `RemoveSharedLinkFromFolderOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of a folder, with the shared link removed. --- ## Untitled *Type: page* SharedLinksWebLinksManager Find web link for shared link Get shared link for web link Add shared link to web link Update shared link on web… # SharedLinksWebLinksManager - [Find web link for shared link](#find-web-link-for-shared-link) - [Get shared link for web link](#get-shared-link-for-web-link) - [Add shared link to web link](#add-shared-link-to-web-link) - [Update shared link on web link](#update-shared-link-on-web-link) - [Remove shared link from web link](#remove-shared-link-from-web-link) ## Find web link for shared link Returns the web link represented by a shared link. A shared web link can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared web link when only given a shared link. This operation is performed by calling function `findWebLinkForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--web-links/). ``` await userClient.sharedLinksWebLinks.findWebLinkForSharedLink( {} satisfies FindWebLinkForSharedLinkQueryParams, { boxapi: ''.concat( 'shared_link=', webLinkFromApi.sharedLink!.url, '&shared_link_password=Secret123@', ) as string, } satisfies FindWebLinkForSharedLinkHeadersInput, ); ``` ### Arguments queryParams `FindWebLinkForSharedLinkQueryParams` - Query parameters of findWebLinkForSharedLink method headersInput `FindWebLinkForSharedLinkHeadersInput` - Headers of findWebLinkForSharedLink method optionalsInput `FindWebLinkForSharedLinkOptionalsInput` ### Returns This function returns a value of type `WebLink`. Returns a full web link resource if the shared link is valid and the user has access to it. ## Get shared link for web link Gets the information for a shared link on a web link. This operation is performed by calling function `getSharedLinkForWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id--get-shared-link/). ``` await client.sharedLinksWebLinks.getSharedLinkForWebLink(webLinkId, { fields: 'shared_link', } satisfies GetSharedLinkForWebLinkQueryParams); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" queryParams `GetSharedLinkForWebLinkQueryParams` - Query parameters of getSharedLinkForWebLink method optionalsInput `GetSharedLinkForWebLinkOptionalsInput` ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with the additional shared link information. ## Add shared link to web link Adds a shared link to a web link. This operation is performed by calling function `addShareLinkToWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--add-shared-link/). ``` await client.sharedLinksWebLinks.addShareLinkToWebLink( webLinkId, { sharedLink: { access: 'open' as AddShareLinkToWebLinkRequestBodySharedLinkAccessField, password: 'Secret123@', } satisfies AddShareLinkToWebLinkRequestBodySharedLinkField, } satisfies AddShareLinkToWebLinkRequestBody, { fields: 'shared_link' } satisfies AddShareLinkToWebLinkQueryParams, ); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" requestBody `AddShareLinkToWebLinkRequestBody` - Request body of addShareLinkToWebLink method queryParams `AddShareLinkToWebLinkQueryParams` - Query parameters of addShareLinkToWebLink method optionalsInput `AddShareLinkToWebLinkOptionalsInput` ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with a new shared link attached. ## Update shared link on web link Updates a shared link on a web link. This operation is performed by calling function `updateSharedLinkOnWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--update-shared-link/). ``` await client.sharedLinksWebLinks.updateSharedLinkOnWebLink( webLinkId, { sharedLink: { access: 'collaborators' as UpdateSharedLinkOnWebLinkRequestBodySharedLinkAccessField, } satisfies UpdateSharedLinkOnWebLinkRequestBodySharedLinkField, } satisfies UpdateSharedLinkOnWebLinkRequestBody, { fields: 'shared_link' } satisfies UpdateSharedLinkOnWebLinkQueryParams, ); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" requestBody `UpdateSharedLinkOnWebLinkRequestBody` - Request body of updateSharedLinkOnWebLink method queryParams `UpdateSharedLinkOnWebLinkQueryParams` - Query parameters of updateSharedLinkOnWebLink method optionalsInput `UpdateSharedLinkOnWebLinkOptionalsInput` ### Returns This function returns a value of type `WebLink`. Returns a basic representation of the web link, with the updated shared link attached. ## Remove shared link from web link Removes a shared link from a web link. This operation is performed by calling function `removeSharedLinkFromWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--remove-shared-link/). ``` await client.sharedLinksWebLinks.removeSharedLinkFromWebLink( webLinkId, { sharedLink: createNull() } satisfies RemoveSharedLinkFromWebLinkRequestBody, { fields: 'shared_link' } satisfies RemoveSharedLinkFromWebLinkQueryParams, ); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" requestBody `RemoveSharedLinkFromWebLinkRequestBody` - Request body of removeSharedLinkFromWebLink method queryParams `RemoveSharedLinkFromWebLinkQueryParams` - Query parameters of removeSharedLinkFromWebLink method optionalsInput `RemoveSharedLinkFromWebLinkOptionalsInput` ### Returns This function returns a value of type `WebLink`. Returns a basic representation of a web link, with the shared link removed. --- ## Untitled *Type: page* ShieldInformationBarrierReportsManager List shield information barrier reports Create shield information barrier report Get shield… # ShieldInformationBarrierReportsManager - [List shield information barrier reports](#list-shield-information-barrier-reports) - [Create shield information barrier report](#create-shield-information-barrier-report) - [Get shield information barrier report by ID](#get-shield-information-barrier-report-by-id) ## List shield information barrier reports Lists shield information barrier reports. This operation is performed by calling function `getShieldInformationBarrierReports`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports/). ``` await client.shieldInformationBarrierReports.getShieldInformationBarrierReports( { shieldInformationBarrierId: barrierId, } satisfies GetShieldInformationBarrierReportsQueryParams, ); ``` ### Arguments queryParams `GetShieldInformationBarrierReportsQueryParams` - Query parameters of getShieldInformationBarrierReports method optionalsInput `GetShieldInformationBarrierReportsOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierReports`. Returns a paginated list of shield information barrier report objects. ## Create shield information barrier report Creates a shield information barrier report for a given barrier. This operation is performed by calling function `createShieldInformationBarrierReport`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-reports/). ``` await client.shieldInformationBarrierReports.createShieldInformationBarrierReport( { shieldInformationBarrier: { id: barrierId, type: 'shield_information_barrier' as ShieldInformationBarrierBaseTypeField, } satisfies ShieldInformationBarrierBase, } satisfies ShieldInformationBarrierReference, ); ``` ### Arguments requestBody `ShieldInformationBarrierReference` - Request body of createShieldInformationBarrierReport method optionalsInput `CreateShieldInformationBarrierReportOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report information object. ## Get shield information barrier report by ID Retrieves a shield information barrier report by its ID. This operation is performed by calling function `getShieldInformationBarrierReportById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports-id/). ``` await client.shieldInformationBarrierReports.getShieldInformationBarrierReportById( createdReport.id!, ); ``` ### Arguments shieldInformationBarrierReportId `string` - The ID of the shield information barrier Report. Example: "3423" optionalsInput `GetShieldInformationBarrierReportByIdOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentMembersManager Get shield information barrier segment member by ID Delete shield information barrier segment… # ShieldInformationBarrierSegmentMembersManager - [Get shield information barrier segment member by ID](#get-shield-information-barrier-segment-member-by-id) - [Delete shield information barrier segment member by ID](#delete-shield-information-barrier-segment-member-by-id) - [List shield information barrier segment members](#list-shield-information-barrier-segment-members) - [Create shield information barrier segment member](#create-shield-information-barrier-segment-member) ## Get shield information barrier segment member by ID Retrieves a shield information barrier segment member by its ID. This operation is performed by calling function `getShieldInformationBarrierSegmentMemberById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members-id/). ``` await client.shieldInformationBarrierSegmentMembers.getShieldInformationBarrierSegmentMemberById( segmentMember.id!, ); ``` ### Arguments shieldInformationBarrierSegmentMemberId `string` - The ID of the shield information barrier segment Member. Example: "7815" optionalsInput `GetShieldInformationBarrierSegmentMemberByIdOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns the shield information barrier segment member object. ## Delete shield information barrier segment member by ID Deletes a shield information barrier segment member based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentMemberById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-members-id/). ``` await client.shieldInformationBarrierSegmentMembers.deleteShieldInformationBarrierSegmentMemberById( segmentMember.id!, ); ``` ### Arguments shieldInformationBarrierSegmentMemberId `string` - The ID of the shield information barrier segment Member. Example: "7815" optionalsInput `DeleteShieldInformationBarrierSegmentMemberByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response if the segment member was deleted successfully. ## List shield information barrier segment members Lists shield information barrier segment members based on provided segment IDs. This operation is performed by calling function `getShieldInformationBarrierSegmentMembers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members/). ``` await client.shieldInformationBarrierSegmentMembers.getShieldInformationBarrierSegmentMembers( { shieldInformationBarrierSegmentId: segment.id!, } satisfies GetShieldInformationBarrierSegmentMembersQueryParams, ); ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentMembersQueryParams` - Query parameters of getShieldInformationBarrierSegmentMembers method optionalsInput `GetShieldInformationBarrierSegmentMembersOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMembers`. Returns a paginated list of shield information barrier segment member objects. ## Create shield information barrier segment member Creates a new shield information barrier segment member. This operation is performed by calling function `createShieldInformationBarrierSegmentMember`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-members/). ``` await client.shieldInformationBarrierSegmentMembers.createShieldInformationBarrierSegmentMember( { shieldInformationBarrierSegment: { id: segment.id!, type: 'shield_information_barrier_segment' as CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentTypeField, } satisfies CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentField, user: new UserBase({ id: getEnvVar('USER_ID') }), } satisfies CreateShieldInformationBarrierSegmentMemberRequestBody, ); ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentMemberRequestBody` - Request body of createShieldInformationBarrierSegmentMember method optionalsInput `CreateShieldInformationBarrierSegmentMemberOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns a new shield information barrier segment member object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentRestrictionsManager Get shield information barrier segment restriction by ID Delete shield information… # ShieldInformationBarrierSegmentRestrictionsManager - [Get shield information barrier segment restriction by ID](#get-shield-information-barrier-segment-restriction-by-id) - [Delete shield information barrier segment restriction by ID](#delete-shield-information-barrier-segment-restriction-by-id) - [List shield information barrier segment restrictions](#list-shield-information-barrier-segment-restrictions) - [Create shield information barrier segment restriction](#create-shield-information-barrier-segment-restriction) ## Get shield information barrier segment restriction by ID Retrieves a shield information barrier segment restriction based on provided ID. This operation is performed by calling function `getShieldInformationBarrierSegmentRestrictionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions-id/). ``` await client.shieldInformationBarrierSegmentRestrictions.getShieldInformationBarrierSegmentRestrictionById( segmentRestrictionId, ); ``` ### Arguments shieldInformationBarrierSegmentRestrictionId `string` - The ID of the shield information barrier segment Restriction. Example: "4563" optionalsInput `GetShieldInformationBarrierSegmentRestrictionByIdOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the shield information barrier segment restriction object. ## Delete shield information barrier segment restriction by ID Delete shield information barrier segment restriction based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentRestrictionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-restrictions-id/). ``` await client.shieldInformationBarrierSegmentRestrictions.deleteShieldInformationBarrierSegmentRestrictionById( segmentRestrictionId, ); ``` ### Arguments shieldInformationBarrierSegmentRestrictionId `string` - The ID of the shield information barrier segment Restriction. Example: "4563" optionalsInput `DeleteShieldInformationBarrierSegmentRestrictionByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Empty body in response. ## List shield information barrier segment restrictions Lists shield information barrier segment restrictions based on provided segment ID. This operation is performed by calling function `getShieldInformationBarrierSegmentRestrictions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions/). ``` await client.shieldInformationBarrierSegmentRestrictions.getShieldInformationBarrierSegmentRestrictions( { shieldInformationBarrierSegmentId: segmentId, } satisfies GetShieldInformationBarrierSegmentRestrictionsQueryParams, ); ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentRestrictionsQueryParams` - Query parameters of getShieldInformationBarrierSegmentRestrictions method optionalsInput `GetShieldInformationBarrierSegmentRestrictionsOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestrictions`. Returns a paginated list of shield information barrier segment restriction objects. ## Create shield information barrier segment restriction Creates a shield information barrier segment restriction object. This operation is performed by calling function `createShieldInformationBarrierSegmentRestriction`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-restrictions/). ``` await client.shieldInformationBarrierSegmentRestrictions.createShieldInformationBarrierSegmentRestriction( { restrictedSegment: { id: segmentToRestrictId, type: 'shield_information_barrier_segment' as CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentTypeField, } satisfies CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentField, shieldInformationBarrierSegment: { id: segmentId, type: 'shield_information_barrier_segment' as CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentTypeField, } satisfies CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentField, type: 'shield_information_barrier_segment_restriction' as CreateShieldInformationBarrierSegmentRestrictionRequestBodyTypeField, } satisfies CreateShieldInformationBarrierSegmentRestrictionRequestBodyInput, ); ``` ### Arguments requestBodyInput `CreateShieldInformationBarrierSegmentRestrictionRequestBodyInput` - Request body of createShieldInformationBarrierSegmentRestriction method optionalsInput `CreateShieldInformationBarrierSegmentRestrictionOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the newly created Shield Information Barrier Segment Restriction object. --- ## Untitled *Type: page* ShieldInformationBarriersManager Get shield information barrier with specified ID Add changed status of shield information barrier with… # ShieldInformationBarriersManager - [Get shield information barrier with specified ID](#get-shield-information-barrier-with-specified-id) - [Add changed status of shield information barrier with specified ID](#add-changed-status-of-shield-information-barrier-with-specified-id) - [List shield information barriers](#list-shield-information-barriers) - [Create shield information barrier](#create-shield-information-barrier) ## Get shield information barrier with specified ID Get shield information barrier based on provided ID. This operation is performed by calling function `getShieldInformationBarrierById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers-id/). ``` await client.shieldInformationBarriers.getShieldInformationBarrierById( barrierId, ); ``` ### Arguments shieldInformationBarrierId `string` - The ID of the shield information barrier. Example: "1910967" optionalsInput `GetShieldInformationBarrierByIdOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the shield information barrier object. ## Add changed status of shield information barrier with specified ID Change status of shield information barrier with the specified ID. This operation is performed by calling function `updateShieldInformationBarrierStatus`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers-change-status/). ``` await client.shieldInformationBarriers.updateShieldInformationBarrierStatus({ id: barrierId, status: 'disabled' as UpdateShieldInformationBarrierStatusRequestBodyStatusField, } satisfies UpdateShieldInformationBarrierStatusRequestBody); ``` ### Arguments requestBody `UpdateShieldInformationBarrierStatusRequestBody` - Request body of updateShieldInformationBarrierStatus method optionalsInput `UpdateShieldInformationBarrierStatusOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the updated shield information barrier object. ## List shield information barriers Retrieves a list of shield information barrier objects for the enterprise of JWT. This operation is performed by calling function `getShieldInformationBarriers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers/). ``` await client.shieldInformationBarriers.getShieldInformationBarriers(); ``` ### Arguments queryParams `GetShieldInformationBarriersQueryParams` - Query parameters of getShieldInformationBarriers method headersInput `GetShieldInformationBarriersHeadersInput` - Headers of getShieldInformationBarriers method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarriers`. Returns a paginated list of shield information barrier objects, empty list if currently no barrier. ## Create shield information barrier Creates a shield information barrier to separate individuals/groups within the same firm and prevents confidential information passing between them. This operation is performed by calling function `createShieldInformationBarrier`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers/). ``` await client.shieldInformationBarriers.createShieldInformationBarrier({ enterprise: { id: enterpriseId } satisfies EnterpriseBase, } satisfies CreateShieldInformationBarrierRequestBody); ``` ### Arguments requestBody `CreateShieldInformationBarrierRequestBody` - Request body of createShieldInformationBarrier method optionalsInput `CreateShieldInformationBarrierOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns a new shield information barrier object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentsManager Get shield information barrier segment with specified ID Delete shield information barrier segment… # ShieldInformationBarrierSegmentsManager - [Get shield information barrier segment with specified ID](#get-shield-information-barrier-segment-with-specified-id) - [Delete shield information barrier segment](#delete-shield-information-barrier-segment) - [Update shield information barrier segment with specified ID](#update-shield-information-barrier-segment-with-specified-id) - [List shield information barrier segments](#list-shield-information-barrier-segments) - [Create shield information barrier segment](#create-shield-information-barrier-segment) ## Get shield information barrier segment with specified ID Retrieves shield information barrier segment based on provided ID.. This operation is performed by calling function `getShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments-id/). ``` await client.shieldInformationBarrierSegments.getShieldInformationBarrierSegmentById( segmentId, ); ``` ### Arguments shieldInformationBarrierSegmentId `string` - The ID of the shield information barrier segment. Example: "3423" optionalsInput `GetShieldInformationBarrierSegmentByIdOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the shield information barrier segment object. ## Delete shield information barrier segment Deletes the shield information barrier segment based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segments-id/). ``` await client.shieldInformationBarrierSegments.deleteShieldInformationBarrierSegmentById( segmentId, ); ``` ### Arguments shieldInformationBarrierSegmentId `string` - The ID of the shield information barrier segment. Example: "3423" optionalsInput `DeleteShieldInformationBarrierSegmentByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Empty body in response. ## Update shield information barrier segment with specified ID Updates the shield information barrier segment based on provided ID.. This operation is performed by calling function `updateShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-shield-information-barrier-segments-id/). ``` await client.shieldInformationBarrierSegments.updateShieldInformationBarrierSegmentById( segmentId, { requestBody: { description: updatedSegmentDescription, } satisfies UpdateShieldInformationBarrierSegmentByIdRequestBody, } satisfies UpdateShieldInformationBarrierSegmentByIdOptionalsInput, ); ``` ### Arguments shieldInformationBarrierSegmentId `string` - The ID of the shield information barrier segment. Example: "3423" optionalsInput `UpdateShieldInformationBarrierSegmentByIdOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the updated shield information barrier segment object. ## List shield information barrier segments Retrieves a list of shield information barrier segment objects for the specified Information Barrier ID. This operation is performed by calling function `getShieldInformationBarrierSegments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments/). ``` await client.shieldInformationBarrierSegments.getShieldInformationBarrierSegments( { shieldInformationBarrierId: barrierId, } satisfies GetShieldInformationBarrierSegmentsQueryParams, ); ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentsQueryParams` - Query parameters of getShieldInformationBarrierSegments method optionalsInput `GetShieldInformationBarrierSegmentsOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegments`. Returns a paginated list of shield information barrier segment objects. ## Create shield information barrier segment Creates a shield information barrier segment. This operation is performed by calling function `createShieldInformationBarrierSegment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segments/). ``` await client.shieldInformationBarrierSegments.createShieldInformationBarrierSegment( { shieldInformationBarrier: { id: barrierId, type: 'shield_information_barrier' as ShieldInformationBarrierBaseTypeField, } satisfies ShieldInformationBarrierBase, name: segmentName, description: segmentDescription, } satisfies CreateShieldInformationBarrierSegmentRequestBody, ); ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentRequestBody` - Request body of createShieldInformationBarrierSegment method optionalsInput `CreateShieldInformationBarrierSegmentOptionalsInput` ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns a new shield information barrier segment object. --- ## Untitled *Type: page* ShieldListsManager Get all shield lists in enterprise Create shield list Get single shield list by shield list id Delete single shield list… # ShieldListsManager - [Get all shield lists in enterprise](#get-all-shield-lists-in-enterprise) - [Create shield list](#create-shield-list) - [Get single shield list by shield list id](#get-single-shield-list-by-shield-list-id) - [Delete single shield list by shield list id](#delete-single-shield-list-by-shield-list-id) - [Update shield list](#update-shield-list) ## Get all shield lists in enterprise Retrieves all shield lists in the enterprise. This operation is performed by calling function `getShieldListsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists/). ``` await client.shieldLists.getShieldListsV2025R0(); ``` ### Arguments headersInput `GetShieldListsV2025R0HeadersInput` - Headers of getShieldListsV2025R0 method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldListsV2025R0`. Returns the list of shield list objects. ## Create shield list Creates a shield list. This operation is performed by calling function `createShieldListV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-shield-lists/). ``` await client.shieldLists.createShieldListV2025R0({ name: shieldListCountryName, description: 'A list of things that are shielded', content: new ShieldListContentCountryV2025R0({ type: 'country' as ShieldListContentCountryV2025R0TypeField, countryCodes: ['US', 'PL'], }), } satisfies ShieldListsCreateV2025R0); ``` ### Arguments requestBody `ShieldListsCreateV2025R0` - Request body of createShieldListV2025R0 method optionalsInput `CreateShieldListV2025R0OptionalsInput` ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Get single shield list by shield list id Retrieves a single shield list by its ID. This operation is performed by calling function `getShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists-id/). ``` await client.shieldLists.getShieldListByIdV2025R0(shieldListCountry.id); ``` ### Arguments shieldListId `string` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " optionalsInput `GetShieldListByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Delete single shield list by shield list id Delete a single shield list by its ID. This operation is performed by calling function `deleteShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-shield-lists-id/). ``` await client.shieldLists.deleteShieldListByIdV2025R0(shieldListCountry.id); ``` ### Arguments shieldListId `string` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " optionalsInput `DeleteShieldListByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `undefined`. Shield List correctly removed. No content in response. ## Update shield list Updates a shield list. This operation is performed by calling function `updateShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-shield-lists-id/). ``` await client.shieldLists.updateShieldListByIdV2025R0(shieldListCountry.id, { name: shieldListCountryName, description: 'Updated description', content: new ShieldListContentCountryV2025R0({ type: 'country' as ShieldListContentCountryV2025R0TypeField, countryCodes: ['US'], }), } satisfies ShieldListsUpdateV2025R0); ``` ### Arguments shieldListId `string` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " requestBody `ShieldListsUpdateV2025R0` - Request body of updateShieldListByIdV2025R0 method optionalsInput `UpdateShieldListByIdV2025R0OptionalsInput` ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. --- ## Untitled *Type: page* SignRequestsManager Cancel Box Sign request Resend Box Sign request Get Box Sign request by ID List Box Sign requests Create Box Sign… # SignRequestsManager - [Cancel Box Sign request](#cancel-box-sign-request) - [Resend Box Sign request](#resend-box-sign-request) - [Get Box Sign request by ID](#get-box-sign-request-by-id) - [List Box Sign requests](#list-box-sign-requests) - [Create Box Sign request](#create-box-sign-request) ## Cancel Box Sign request Cancels a sign request. This operation is performed by calling function `cancelSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-cancel/). ``` await client.signRequests.cancelSignRequest(createdSignRequest.id!); ``` ### Arguments signRequestId `string` - The ID of the signature request. Example: "33243242" optionalsInput `CancelSignRequestOptionalsInput` ### Returns This function returns a value of type `SignRequest`. Returns a Sign Request object. ## Resend Box Sign request Resends a signature request email to all outstanding signers. This operation is performed by calling function `resendSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-resend/). *Currently we don't have an example for calling `resendSignRequest` in integration tests* ### Arguments signRequestId `string` - The ID of the signature request. Example: "33243242" optionalsInput `ResendSignRequestOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the API call was successful. The email notifications will be sent asynchronously. ## Get Box Sign request by ID Gets a sign request by ID. This operation is performed by calling function `getSignRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests-id/). ``` await client.signRequests.getSignRequestById(createdSignRequest.id!); ``` ### Arguments signRequestId `string` - The ID of the signature request. Example: "33243242" optionalsInput `GetSignRequestByIdOptionalsInput` ### Returns This function returns a value of type `SignRequest`. Returns a signature request. ## List Box Sign requests Gets signature requests created by a user. If the `sign_files` and/or `parent_folder` are deleted, the signature request will not return in the list. This operation is performed by calling function `getSignRequests`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests/). ``` await client.signRequests.getSignRequests(); ``` ### Arguments queryParams `GetSignRequestsQueryParams` - Query parameters of getSignRequests method headersInput `GetSignRequestsHeadersInput` - Headers of getSignRequests method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `SignRequests`. Returns a collection of sign requests. ## Create Box Sign request Creates a signature request. This involves preparing a document for signing and sending the signature request to signers. This operation is performed by calling function `createSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests/). ``` await client.signRequests.createSignRequest({ signers: [ { email: signerEmail, suppressNotifications: true, declinedRedirectUrl: 'https://www.box.com', embedUrlExternalUserId: '123', isInPerson: false, loginRequired: false, password: 'password', role: 'signer' as SignRequestCreateSignerRoleField, } satisfies SignRequestCreateSigner, ], areRemindersEnabled: true, areTextSignaturesEnabled: true, daysValid: 30, declinedRedirectUrl: 'https://www.box.com', emailMessage: 'Please sign this document', emailSubject: 'Sign this document', externalId: '123', externalSystemName: 'BoxSignIntegration', isDocumentPreparationNeeded: false, name: 'Sign Request', parentFolder: new FolderMini({ id: destinationFolder.id }), redirectUrl: 'https://www.box.com', prefillTags: [ { dateValue: dateFromString('2035-01-01'), documentTagId: '0', } satisfies SignRequestPrefillTag, ], sourceFiles: [new FileBase({ id: fileToSign.id })], } satisfies SignRequestCreateRequest); ``` ### Arguments requestBody `SignRequestCreateRequest` - Request body of createSignRequest method optionalsInput `CreateSignRequestOptionalsInput` ### Returns This function returns a value of type `SignRequest`. Returns a Box Sign request object. --- ## Untitled *Type: page* SignTemplatesManager List Box Sign templates Get Box Sign template by ID List Box Sign templates Gets Box Sign templates created by a user… # SignTemplatesManager - [List Box Sign templates](#list-box-sign-templates) - [Get Box Sign template by ID](#get-box-sign-template-by-id) ## List Box Sign templates Gets Box Sign templates created by a user. This operation is performed by calling function `getSignTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates/). ``` await client.signTemplates.getSignTemplates({ limit: 2, } satisfies GetSignTemplatesQueryParams); ``` ### Arguments queryParams `GetSignTemplatesQueryParams` - Query parameters of getSignTemplates method headersInput `GetSignTemplatesHeadersInput` - Headers of getSignTemplates method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `SignTemplates`. Returns a collection of templates. ## Get Box Sign template by ID Fetches details of a specific Box Sign template. This operation is performed by calling function `getSignTemplateById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates-id/). ``` await client.signTemplates.getSignTemplateById(signTemplates.entries![0].id!); ``` ### Arguments templateId `string` - The ID of a Box Sign template. Example: "123075213-7d117509-8f05-42e4-a5ef-5190a319d41d" optionalsInput `GetSignTemplateByIdOptionalsInput` ### Returns This function returns a value of type `SignTemplate`. Returns details of a template. --- ## Untitled *Type: page* StoragePoliciesManager List storage policies Get storage policy List storage policies Fetches all the storage policies in the enterprise… # StoragePoliciesManager - [List storage policies](#list-storage-policies) - [Get storage policy](#get-storage-policy) ## List storage policies Fetches all the storage policies in the enterprise. This operation is performed by calling function `getStoragePolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies/). ``` await client.storagePolicies.getStoragePolicies(); ``` ### Arguments queryParams `GetStoragePoliciesQueryParams` - Query parameters of getStoragePolicies method headersInput `GetStoragePoliciesHeadersInput` - Headers of getStoragePolicies method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `StoragePolicies`. Returns a collection of storage policies. ## Get storage policy Fetches a specific storage policy. This operation is performed by calling function `getStoragePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies-id/). ``` await client.storagePolicies.getStoragePolicyById(storagePolicy.id); ``` ### Arguments storagePolicyId `string` - The ID of the storage policy. Example: "34342" optionalsInput `GetStoragePolicyByIdOptionalsInput` ### Returns This function returns a value of type `StoragePolicy`. Returns a storage policy object. --- ## Untitled *Type: page* StoragePolicyAssignmentsManager List storage policy assignments Assign storage policy Get storage policy assignment Update storage policy… # StoragePolicyAssignmentsManager - [List storage policy assignments](#list-storage-policy-assignments) - [Assign storage policy](#assign-storage-policy) - [Get storage policy assignment](#get-storage-policy-assignment) - [Update storage policy assignment](#update-storage-policy-assignment) - [Unassign storage policy](#unassign-storage-policy) ## List storage policy assignments Fetches all the storage policy assignment for an enterprise or user. This operation is performed by calling function `getStoragePolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments/). ``` await client.storagePolicyAssignments.getStoragePolicyAssignments({ resolvedForType: 'user' as GetStoragePolicyAssignmentsQueryParamsResolvedForTypeField, resolvedForId: userId, } satisfies GetStoragePolicyAssignmentsQueryParams); ``` ### Arguments queryParams `GetStoragePolicyAssignmentsQueryParams` - Query parameters of getStoragePolicyAssignments method optionalsInput `GetStoragePolicyAssignmentsOptionalsInput` ### Returns This function returns a value of type `StoragePolicyAssignments`. Returns a collection of storage policies for the enterprise or user. ## Assign storage policy Creates a storage policy assignment for an enterprise or user. This operation is performed by calling function `createStoragePolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-storage-policy-assignments/). ``` await client.storagePolicyAssignments.createStoragePolicyAssignment({ storagePolicy: new CreateStoragePolicyAssignmentRequestBodyStoragePolicyField( { id: policyId }, ), assignedTo: { id: userId, type: 'user' as CreateStoragePolicyAssignmentRequestBodyAssignedToTypeField, } satisfies CreateStoragePolicyAssignmentRequestBodyAssignedToField, } satisfies CreateStoragePolicyAssignmentRequestBody); ``` ### Arguments requestBody `CreateStoragePolicyAssignmentRequestBody` - Request body of createStoragePolicyAssignment method optionalsInput `CreateStoragePolicyAssignmentOptionalsInput` ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns the new storage policy assignment created. ## Get storage policy assignment Fetches a specific storage policy assignment. This operation is performed by calling function `getStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments-id/). ``` await client.storagePolicyAssignments.getStoragePolicyAssignmentById( storagePolicyAssignment.id, ); ``` ### Arguments storagePolicyAssignmentId `string` - The ID of the storage policy assignment. Example: "932483" optionalsInput `GetStoragePolicyAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns a storage policy assignment object. ## Update storage policy assignment Updates a specific storage policy assignment. This operation is performed by calling function `updateStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-storage-policy-assignments-id/). ``` await client.storagePolicyAssignments.updateStoragePolicyAssignmentById( storagePolicyAssignment.id, { storagePolicy: new UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyField({ id: storagePolicy2.id, }), } satisfies UpdateStoragePolicyAssignmentByIdRequestBody, ); ``` ### Arguments storagePolicyAssignmentId `string` - The ID of the storage policy assignment. Example: "932483" requestBody `UpdateStoragePolicyAssignmentByIdRequestBody` - Request body of updateStoragePolicyAssignmentById method optionalsInput `UpdateStoragePolicyAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns an updated storage policy assignment object. ## Unassign storage policy Delete a storage policy assignment. Deleting a storage policy assignment on a user will have the user inherit the enterprise's default storage policy. There is a rate limit for calling this endpoint of only twice per user in a 24 hour time frame. This operation is performed by calling function `deleteStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-storage-policy-assignments-id/). ``` await client.storagePolicyAssignments.deleteStoragePolicyAssignmentById( storagePolicyAssignment.id, ); ``` ### Arguments storagePolicyAssignmentId `string` - The ID of the storage policy assignment. Example: "932483" optionalsInput `DeleteStoragePolicyAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the storage policy assignment is successfully deleted. --- ## Untitled *Type: page* TaskAssignmentsManager List task assignments Assign task Get task assignment Update task assignment Unassign task List task assignments… # TaskAssignmentsManager - [List task assignments](#list-task-assignments) - [Assign task](#assign-task) - [Get task assignment](#get-task-assignment) - [Update task assignment](#update-task-assignment) - [Unassign task](#unassign-task) ## List task assignments Lists all of the assignments for a given task. This operation is performed by calling function `getTaskAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id-assignments/). ``` await client.taskAssignments.getTaskAssignments(task.id!); ``` ### Arguments taskId `string` - The ID of the task. Example: "12345" optionalsInput `GetTaskAssignmentsOptionalsInput` ### Returns This function returns a value of type `TaskAssignments`. Returns a collection of task assignment defining what task on a file has been assigned to which users and by who. ## Assign task Assigns a task to a user. A task can be assigned to more than one user by creating multiple assignments. This operation is performed by calling function `createTaskAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-task-assignments/). ``` await client.taskAssignments.createTaskAssignment({ task: new CreateTaskAssignmentRequestBodyTaskField({ type: 'task' as CreateTaskAssignmentRequestBodyTaskTypeField, id: task.id!, }), assignTo: { id: currentUser.id, } satisfies CreateTaskAssignmentRequestBodyAssignToField, } satisfies CreateTaskAssignmentRequestBody); ``` ### Arguments requestBody `CreateTaskAssignmentRequestBody` - Request body of createTaskAssignment method optionalsInput `CreateTaskAssignmentOptionalsInput` ### Returns This function returns a value of type `TaskAssignment`. Returns a new task assignment object. ## Get task assignment Retrieves information about a task assignment. This operation is performed by calling function `getTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-task-assignments-id/). ``` await client.taskAssignments.getTaskAssignmentById(taskAssignment.id!); ``` ### Arguments taskAssignmentId `string` - The ID of the task assignment. Example: "12345" optionalsInput `GetTaskAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `TaskAssignment`. Returns a task assignment, specifying who the task has been assigned to and by whom. ## Update task assignment Updates a task assignment. This endpoint can be used to update the state of a task assigned to a user. This operation is performed by calling function `updateTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-task-assignments-id/). ``` await client.taskAssignments.updateTaskAssignmentById(taskAssignment.id!, { requestBody: { message: 'updated message', resolutionState: 'approved' as UpdateTaskAssignmentByIdRequestBodyResolutionStateField, } satisfies UpdateTaskAssignmentByIdRequestBody, } satisfies UpdateTaskAssignmentByIdOptionalsInput); ``` ### Arguments taskAssignmentId `string` - The ID of the task assignment. Example: "12345" optionalsInput `UpdateTaskAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `TaskAssignment`. Returns the updated task assignment object. ## Unassign task Deletes a specific task assignment. This operation is performed by calling function `deleteTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-task-assignments-id/). ``` await client.taskAssignments.deleteTaskAssignmentById(taskAssignment.id!); ``` ### Arguments taskAssignmentId `string` - The ID of the task assignment. Example: "12345" optionalsInput `DeleteTaskAssignmentByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the task assignment was successfully deleted. --- ## Untitled *Type: page* TasksManager List tasks on file Create task Get task Update task Remove task List tasks on file Retrieves a list of all the tasks for a file… # TasksManager - [List tasks on file](#list-tasks-on-file) - [Create task](#create-task) - [Get task](#get-task) - [Update task](#update-task) - [Remove task](#remove-task) ## List tasks on file Retrieves a list of all the tasks for a file. This endpoint does not support pagination. This operation is performed by calling function `getFileTasks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-tasks/). ``` await client.tasks.getFileTasks(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetFileTasksOptionalsInput` ### Returns This function returns a value of type `Tasks`. Returns a list of tasks on a file. If there are no tasks on this file an empty collection is returned instead. ## Create task Creates a single task on a file. This task is not assigned to any user and will need to be assigned separately. This operation is performed by calling function `createTask`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-tasks/). ``` await client.tasks.createTask({ item: { type: 'file' as CreateTaskRequestBodyItemTypeField, id: file.id, } satisfies CreateTaskRequestBodyItemField, message: 'test message', dueAt: dateTime, action: 'review' as CreateTaskRequestBodyActionField, completionRule: 'all_assignees' as CreateTaskRequestBodyCompletionRuleField, } satisfies CreateTaskRequestBody); ``` ### Arguments requestBody `CreateTaskRequestBody` - Request body of createTask method optionalsInput `CreateTaskOptionalsInput` ### Returns This function returns a value of type `Task`. Returns the newly created task. ## Get task Retrieves information about a specific task. This operation is performed by calling function `getTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id/). ``` await client.tasks.getTaskById(task.id!); ``` ### Arguments taskId `string` - The ID of the task. Example: "12345" optionalsInput `GetTaskByIdOptionalsInput` ### Returns This function returns a value of type `Task`. Returns a task object. ## Update task Updates a task. This can be used to update a task's configuration, or to update its completion state. This operation is performed by calling function `updateTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-tasks-id/). ``` await client.tasks.updateTaskById(task.id!, { requestBody: { message: 'updated message', } satisfies UpdateTaskByIdRequestBody, } satisfies UpdateTaskByIdOptionalsInput); ``` ### Arguments taskId `string` - The ID of the task. Example: "12345" optionalsInput `UpdateTaskByIdOptionalsInput` ### Returns This function returns a value of type `Task`. Returns the updated task object. ## Remove task Removes a task from a file. This operation is performed by calling function `deleteTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-tasks-id/). ``` await client.tasks.deleteTaskById(task.id!); ``` ### Arguments taskId `string` - The ID of the task. Example: "12345" optionalsInput `DeleteTaskByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the task was successfully deleted. --- ## Untitled *Type: page* TermsOfServiceUserStatusesManager List terms of service user statuses Create terms of service status for new user Update terms of service… # TermsOfServiceUserStatusesManager - [List terms of service user statuses](#list-terms-of-service-user-statuses) - [Create terms of service status for new user](#create-terms-of-service-status-for-new-user) - [Update terms of service status for existing user](#update-terms-of-service-status-for-existing-user) ## List terms of service user statuses Retrieves an overview of users and their status for a terms of service, including Whether they have accepted the terms and when. This operation is performed by calling function `getTermsOfServiceUserStatuses`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-service-user-statuses/). ``` await client.termsOfServiceUserStatuses.getTermsOfServiceUserStatuses({ tosId: tos.id, userId: user.id, } satisfies GetTermsOfServiceUserStatusesQueryParams); ``` ### Arguments queryParams `GetTermsOfServiceUserStatusesQueryParams` - Query parameters of getTermsOfServiceUserStatuses method optionalsInput `GetTermsOfServiceUserStatusesOptionalsInput` ### Returns This function returns a value of type `TermsOfServiceUserStatuses`. Returns a list of terms of service statuses. ## Create terms of service status for new user Sets the status for a terms of service for a user. This operation is performed by calling function `createTermsOfServiceStatusForUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-service-user-statuses/). ``` await client.termsOfServiceUserStatuses.createTermsOfServiceStatusForUser({ tos: new CreateTermsOfServiceStatusForUserRequestBodyTosField({ id: tos.id }), user: new CreateTermsOfServiceStatusForUserRequestBodyUserField({ id: user.id, }), isAccepted: false, } satisfies CreateTermsOfServiceStatusForUserRequestBody); ``` ### Arguments requestBody `CreateTermsOfServiceStatusForUserRequestBody` - Request body of createTermsOfServiceStatusForUser method optionalsInput `CreateTermsOfServiceStatusForUserOptionalsInput` ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns a terms of service status object. ## Update terms of service status for existing user Updates the status for a terms of service for a user. This operation is performed by calling function `updateTermsOfServiceStatusForUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-service-user-statuses-id/). ``` await client.termsOfServiceUserStatuses.updateTermsOfServiceStatusForUserById( createdTosUserStatus.id, { isAccepted: true, } satisfies UpdateTermsOfServiceStatusForUserByIdRequestBody, ); ``` ### Arguments termsOfServiceUserStatusId `string` - The ID of the terms of service status. Example: "324234" requestBody `UpdateTermsOfServiceStatusForUserByIdRequestBody` - Request body of updateTermsOfServiceStatusForUserById method optionalsInput `UpdateTermsOfServiceStatusForUserByIdOptionalsInput` ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns the updated terms of service status object. --- ## Untitled *Type: page* SkillsManager List Box Skill cards on file Create Box Skill cards on file Update Box Skill cards on file Remove Box Skill cards from file… # SkillsManager - [List Box Skill cards on file](#list-box-skill-cards-on-file) - [Create Box Skill cards on file](#create-box-skill-cards-on-file) - [Update Box Skill cards on file](#update-box-skill-cards-on-file) - [Remove Box Skill cards from file](#remove-box-skill-cards-from-file) - [Update all Box Skill cards on file](#update-all-box-skill-cards-on-file) ## List Box Skill cards on file List the Box Skills metadata cards that are attached to a file. This operation is performed by calling function `getBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-global-boxSkillsCards/). ``` await client.skills.getBoxSkillCardsOnFile(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetBoxSkillCardsOnFileOptionalsInput` ### Returns This function returns a value of type `SkillCardsMetadata`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Create Box Skill cards on file Applies one or more Box Skills metadata cards to a file. This operation is performed by calling function `createBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-global-boxSkillsCards/). ``` await client.skills.createBoxSkillCardsOnFile(file.id, { cards: cardsToCreate, } satisfies CreateBoxSkillCardsOnFileRequestBody); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CreateBoxSkillCardsOnFileRequestBody` - Request body of createBoxSkillCardsOnFile method optionalsInput `CreateBoxSkillCardsOnFileOptionalsInput` ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update Box Skill cards on file Updates one or more Box Skills metadata cards to a file. This operation is performed by calling function `updateBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-global-boxSkillsCards/). ``` await client.skills.updateBoxSkillCardsOnFile(file.id, [ { op: 'replace' as UpdateBoxSkillCardsOnFileRequestBodyOpField, path: '/cards/0', value: cardToUpdate, } satisfies UpdateBoxSkillCardsOnFileRequestBody, ]); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `readonly UpdateBoxSkillCardsOnFileRequestBody[]` - Request body of updateBoxSkillCardsOnFile method optionalsInput `UpdateBoxSkillCardsOnFileOptionalsInput` ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the updated metadata template, with the custom template data included. ## Remove Box Skill cards from file Removes any Box Skills cards metadata from a file. This operation is performed by calling function `deleteBoxSkillCardsFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-global-boxSkillsCards/). ``` await client.skills.deleteBoxSkillCardsFromFile(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `DeleteBoxSkillCardsFromFileOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the cards are successfully deleted. ## Update all Box Skill cards on file An alternative method that can be used to overwrite and update all Box Skill metadata cards on a file. This operation is performed by calling function `updateAllSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-skill-invocations-id/). *Currently we don't have an example for calling `updateAllSkillCardsOnFile` in integration tests* ### Arguments skillId `string` - The ID of the skill to apply this metadata for. Example: "33243242" requestBody `UpdateAllSkillCardsOnFileRequestBody` - Request body of updateAllSkillCardsOnFile method optionalsInput `UpdateAllSkillCardsOnFileOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the card has been successfully updated. --- ## Untitled *Type: page* TermsOfServicesManager List terms of services Create terms of service Get terms of service Update terms of service List terms of services… # TermsOfServicesManager - [List terms of services](#list-terms-of-services) - [Create terms of service](#create-terms-of-service) - [Get terms of service](#get-terms-of-service) - [Update terms of service](#update-terms-of-service) ## List terms of services Returns the current terms of service text and settings for the enterprise. This operation is performed by calling function `getTermsOfService`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services/). ``` await client.termsOfServices.getTermsOfService(); ``` ### Arguments queryParams `GetTermsOfServiceQueryParams` - Query parameters of getTermsOfService method headersInput `GetTermsOfServiceHeadersInput` - Headers of getTermsOfService method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `TermsOfServices`. Returns a collection of terms of service text and settings for the enterprise. ## Create terms of service Creates a terms of service for a given enterprise and type of user. This operation is performed by calling function `createTermsOfService`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-services/). ``` await client.termsOfServices.createTermsOfService({ status: 'disabled' as CreateTermsOfServiceRequestBodyStatusField, tosType: 'managed' as CreateTermsOfServiceRequestBodyTosTypeField, text: 'Test TOS', } satisfies CreateTermsOfServiceRequestBody); ``` ### Arguments requestBody `CreateTermsOfServiceRequestBody` - Request body of createTermsOfService method optionalsInput `CreateTermsOfServiceOptionalsInput` ### Returns This function returns a value of type `TermsOfService`. Returns a new task object. ## Get terms of service Fetches a specific terms of service. This operation is performed by calling function `getTermsOfServiceById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services-id/). *Currently we don't have an example for calling `getTermsOfServiceById` in integration tests* ### Arguments termsOfServiceId `string` - The ID of the terms of service. Example: "324234" optionalsInput `GetTermsOfServiceByIdOptionalsInput` ### Returns This function returns a value of type `TermsOfService`. Returns a terms of service object. ## Update terms of service Updates a specific terms of service. This operation is performed by calling function `updateTermsOfServiceById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-services-id/). ``` await client.termsOfServices.updateTermsOfServiceById(tos.id, { status: 'disabled' as UpdateTermsOfServiceByIdRequestBodyStatusField, text: 'TOS', } satisfies UpdateTermsOfServiceByIdRequestBody); ``` ### Arguments termsOfServiceId `string` - The ID of the terms of service. Example: "324234" requestBody `UpdateTermsOfServiceByIdRequestBody` - Request body of updateTermsOfServiceById method optionalsInput `UpdateTermsOfServiceByIdOptionalsInput` ### Returns This function returns a value of type `TermsOfService`. Returns an updated terms of service object. --- ## Untitled *Type: page* TrashedFilesManager Restore file Get trashed file Permanently remove file Restore file Restores a file that has been moved to the trash. An… # TrashedFilesManager - [Restore file](#restore-file) - [Get trashed file](#get-trashed-file) - [Permanently remove file](#permanently-remove-file) ## Restore file Restores a file that has been moved to the trash. An optional new parent ID can be provided to restore the file to in case the original folder has been deleted. This operation is performed by calling function `restoreFileFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id/). ``` await client.trashedFiles.restoreFileFromTrash(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `RestoreFileFromTrashOptionalsInput` ### Returns This function returns a value of type `TrashFileRestored`. Returns a file object when the file has been restored. ## Get trashed file Retrieves a file that has been moved to the trash. Please note that only if the file itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `getTrashedFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-trash/). ``` await client.trashedFiles.getTrashedFileById(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `GetTrashedFileByIdOptionalsInput` ### Returns This function returns a value of type `TrashFile`. Returns the file that was trashed, including information about when the it was moved to the trash. ## Permanently remove file Permanently deletes a file that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-trash/). ``` await client.trashedFiles.deleteTrashedFileById(file.id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" optionalsInput `DeleteTrashedFileByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the file was permanently deleted. --- ## Untitled *Type: page* TransferManager Transfer owned folders Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into… # TransferManager - [Transfer owned folders](#transfer-owned-folders) ## Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into another user's account Only the root folder (`0`) can be transferred. Folders can only be moved across users by users with administrative permissions. All existing shared links and folder-level collaborations are transferred during the operation. Please note that while collaborations at the individual file-level are transferred during the operation, the collaborations are deleted when the original user is deleted. If the user has a large number of items across all folders, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. If the destination path has a metadata cascade policy attached to any of the parent folders, a metadata cascade operation will be kicked off asynchronously. There is currently no way to check for when this operation is finished. The destination folder's name will be in the format `{User}'s Files and Folders`, where `{User}` is the display name of the user. To make this API call your application will need to have the "Read and write all files and folders stored in Box" scope enabled. Please make sure the destination user has access to `Relay` or `Relay Lite`, and has access to the files and folders involved in the workflows being transferred. Admins will receive an email when the operation is completed. This operation is performed by calling function `transferOwnedFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id-folders-0/). ``` await client.transfer.transferOwnedFolder( sourceUser.id, { ownedBy: { id: targetUser.id, } satisfies TransferOwnedFolderRequestBodyOwnedByField, } satisfies TransferOwnedFolderRequestBody, { queryParams: { notify: false } satisfies TransferOwnedFolderQueryParams, } satisfies TransferOwnedFolderOptionalsInput, ); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" requestBody `TransferOwnedFolderRequestBody` - Request body of transferOwnedFolder method optionalsInput `TransferOwnedFolderOptionalsInput` ### Returns This function returns a value of type `FolderFull`. Returns the information for the newly created destination folder. --- ## Untitled *Type: page* TrashedFoldersManager Restore folder Get trashed folder Permanently remove folder Restore folder Restores a folder that has been moved to… # TrashedFoldersManager - [Restore folder](#restore-folder) - [Get trashed folder](#get-trashed-folder) - [Permanently remove folder](#permanently-remove-folder) ## Restore folder Restores a folder that has been moved to the trash. An optional new parent ID can be provided to restore the folder to in case the original folder has been deleted. During this operation, part of the file tree will be locked, mainly the source folder and all of its descendants, as well as the destination folder. For the duration of the operation, no other move, copy, delete, or restore operation can performed on any of the locked folders. This operation is performed by calling function `restoreFolderFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id/). ``` await client.trashedFolders.restoreFolderFromTrash(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `RestoreFolderFromTrashOptionalsInput` ### Returns This function returns a value of type `TrashFolderRestored`. Returns a folder object when the folder has been restored. ## Get trashed folder Retrieves a folder that has been moved to the trash. Please note that only if the folder itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `getTrashedFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-trash/). ``` await client.trashedFolders.getTrashedFolderById(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `GetTrashedFolderByIdOptionalsInput` ### Returns This function returns a value of type `TrashFolder`. Returns the folder that was trashed, including information about when the it was moved to the trash. ## Permanently remove folder Permanently deletes a folder that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-trash/). ``` await client.trashedFolders.deleteTrashedFolderById(folder.id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" optionalsInput `DeleteTrashedFolderByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the folder was permanently deleted. --- ## Untitled *Type: page* TrashedWebLinksManager Restore web link Get trashed web link Permanently remove web link Restore web link Restores a web link that has been… # TrashedWebLinksManager - [Restore web link](#restore-web-link) - [Get trashed web link](#get-trashed-web-link) - [Permanently remove web link](#permanently-remove-web-link) ## Restore web link Restores a web link that has been moved to the trash. An optional new parent ID can be provided to restore the web link to in case the original folder has been deleted. This operation is performed by calling function `restoreWeblinkFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links-id/). ``` await client.trashedWebLinks.restoreWeblinkFromTrash(weblink.id); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" optionalsInput `RestoreWeblinkFromTrashOptionalsInput` ### Returns This function returns a value of type `TrashWebLinkRestored`. Returns a web link object when it has been restored. ## Get trashed web link Retrieves a web link that has been moved to the trash. This operation is performed by calling function `getTrashedWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id-trash/). ``` await client.trashedWebLinks.getTrashedWebLinkById(weblink.id); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" optionalsInput `GetTrashedWebLinkByIdOptionalsInput` ### Returns This function returns a value of type `TrashWebLink`. Returns the web link that was trashed, including information about when the it was moved to the trash. ## Permanently remove web link Permanently deletes a web link that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id-trash/). ``` await client.trashedWebLinks.deleteTrashedWebLinkById(weblink.id); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" optionalsInput `DeleteTrashedWebLinkByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Returns an empty response when the web link was permanently deleted. --- ## Untitled *Type: page* TrashedItemsManager List trashed items List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute… # TrashedItemsManager - [List trashed items](#list-trashed-items) ## List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute in the full files or folders objects can be passed in with the `fields` parameter to retrieve those specific attributes that are not returned by default. This endpoint defaults to use offset-based pagination, yet also supports marker-based pagination using the `marker` parameter. This operation is performed by calling function `getTrashedItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-trash-items/). ``` await client.trashedItems.getTrashedItems(); ``` ### Arguments queryParams `GetTrashedItemsQueryParams` - Query parameters of getTrashedItems method headersInput `GetTrashedItemsHeadersInput` - Headers of getTrashedItems method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `Items`. Returns a list of items that have been deleted. --- ## Untitled *Type: page* UploadsManager Upload file version Preflight check before upload Upload file Upload file version Update a file's content. For file sizes… # UploadsManager - [Upload file version](#upload-file-version) - [Preflight check before upload](#preflight-check-before-upload) - [Upload file](#upload-file) ## Upload file version Update a file's content. For file sizes over 50MB we recommend using the Chunk Upload APIs. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. This operation is performed by calling function `uploadFileVersion`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-content/). ``` await client.uploads.uploadFileVersion(file.id, { attributes: { name: file.name!, } satisfies UploadFileVersionRequestBodyAttributesField, file: generateByteStream(20), } satisfies UploadFileVersionRequestBody); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UploadFileVersionRequestBody` - Request body of uploadFileVersion method optionalsInput `UploadFileVersionOptionalsInput` ### Returns This function returns a value of type `Files`. Returns the new file object in a list. ## Preflight check before upload Performs a check to verify that a file will be accepted by Box before you upload the entire file. This operation is performed by calling function `preflightFileUploadCheck`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-files-content/). ``` await client.uploads.preflightFileUploadCheck({ name: newFileName, size: 1024 * 1024, parent: { id: '0' } satisfies PreflightFileUploadCheckRequestBodyParentField, } satisfies PreflightFileUploadCheckRequestBody); ``` ### Arguments requestBody `PreflightFileUploadCheckRequestBody` - Request body of preflightFileUploadCheck method headersInput `PreflightFileUploadCheckHeadersInput` - Headers of preflightFileUploadCheck method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `UploadUrl`. If the check passed, the response will include a session URL that can be used to upload the file to. ## Upload file Uploads a small file to Box. For file sizes over 50MB we recommend using the Chunk Upload APIs. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. This operation is performed by calling function `uploadFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-content/). ``` const fs = require('fs'); const attrs = { name: 'filename.txt', parent: { id: '0' } }; const body = { attributes: attrs, file: fs.createReadStream('filename.txt'), }; const files = await client.uploads.uploadFile(body); const file = files.entries[0]; console.log(`File uploaded with id ${file.id}, name ${file.name}`); ``` ### Arguments requestBody `UploadFileRequestBody` - Request body of uploadFile method ## optionalsInput UploadFileOptionalsInput ### Returns This function returns a value of type `Files`. Returns the new file object in a list. --- ## Untitled *Type: page* UserCollaborationsManager Get collaboration Update collaboration Remove collaboration Create collaboration Get collaboration Retrieves a… # UserCollaborationsManager - [Get collaboration](#get-collaboration) - [Update collaboration](#update-collaboration) - [Remove collaboration](#remove-collaboration) - [Create collaboration](#create-collaboration) ## Get collaboration Retrieves a single collaboration. This operation is performed by calling function `getCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations-id/). ``` await client.userCollaborations.getCollaborationById(collaborationId); ``` ### Arguments collaborationId `string` - The ID of the collaboration. Example: "1234" optionalsInput `GetCollaborationByIdOptionalsInput` ### Returns This function returns a value of type `Collaboration`. Returns a collaboration object. ## Update collaboration Updates a collaboration. Can be used to change the owner of an item, or to accept collaboration invites. This operation is performed by calling function `updateCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-collaborations-id/). ``` await client.userCollaborations.updateCollaborationById(collaborationId, { role: 'viewer' as UpdateCollaborationByIdRequestBodyRoleField, } satisfies UpdateCollaborationByIdRequestBody); ``` ### Arguments collaborationId `string` - The ID of the collaboration. Example: "1234" requestBody `UpdateCollaborationByIdRequestBody` - Request body of updateCollaborationById method optionalsInput `UpdateCollaborationByIdOptionalsInput` ### Returns This function returns a value of type `undefined | Collaboration`. Returns an updated collaboration object unless the owner has changed.If the role is changed to `owner`, the collaboration is deleted and a new collaboration is created. The previous `owner` of the old collaboration will be a `co-owner` on the new collaboration. ## Remove collaboration Deletes a single collaboration. This operation is performed by calling function `deleteCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaborations-id/). ``` await client.userCollaborations.deleteCollaborationById(collaborationId); ``` ### Arguments collaborationId `string` - The ID of the collaboration. Example: "1234" optionalsInput `DeleteCollaborationByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. A blank response is returned if the collaboration was successfully deleted. ## Create collaboration Adds a collaboration for a single user or a single group to a file or folder. Collaborations can be created using email address, user IDs, or a group IDs. If a collaboration is being created with a group, access to this endpoint is dependent on the group's ability to be invited. If collaboration is in `pending` status, the following fields are redacted: `login` and `name` are hidden if a collaboration was created using `user_id`, - `name` is hidden if a collaboration was created using `login`. This operation is performed by calling function `createCollaboration`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaborations/). ``` await client.userCollaborations.createCollaboration({ item: { type: 'folder' as CreateCollaborationRequestBodyItemTypeField, id: folder.id, } satisfies CreateCollaborationRequestBodyItemField, accessibleBy: { type: 'user' as CreateCollaborationRequestBodyAccessibleByTypeField, id: user.id, } satisfies CreateCollaborationRequestBodyAccessibleByField, role: 'editor' as CreateCollaborationRequestBodyRoleField, } satisfies CreateCollaborationRequestBody); ``` ### Arguments requestBody `CreateCollaborationRequestBody` - Request body of createCollaboration method optionalsInput `CreateCollaborationOptionalsInput` ### Returns This function returns a value of type `Collaboration`. Returns a new collaboration object. --- ## Untitled *Type: page* WorkflowsManager List workflows Starts workflow based on request body List workflows Returns list of workflows that act on a given folder ID… # WorkflowsManager - [List workflows](#list-workflows) - [Starts workflow based on request body](#starts-workflow-based-on-request-body) ## List workflows Returns list of workflows that act on a given `folder ID`, and have a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in to use this endpoint. This operation is performed by calling function `getWorkflows`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-workflows/). ``` await adminClient.workflows.getWorkflows({ folderId: workflowFolderId, } satisfies GetWorkflowsQueryParams); ``` ### Arguments queryParams `GetWorkflowsQueryParams` - Query parameters of getWorkflows method optionalsInput `GetWorkflowsOptionalsInput` ### Returns This function returns a value of type `Workflows`. Returns the workflow. ## Starts workflow based on request body Initiates a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console. This operation is performed by calling function `startWorkflow`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-workflows-id-start/). ``` await adminClient.workflows.startWorkflow(workflowToRun.id!, { type: 'workflow_parameters' as StartWorkflowRequestBodyTypeField, flow: { type: 'flow', id: workflowToRun.flows![0].id!, } satisfies StartWorkflowRequestBodyFlowField, files: [ { type: 'file' as StartWorkflowRequestBodyFilesTypeField, id: workflowFileId, } satisfies StartWorkflowRequestBodyFilesField, ], folder: { type: 'folder' as StartWorkflowRequestBodyFolderTypeField, id: workflowFolderId, } satisfies StartWorkflowRequestBodyFolderField, } satisfies StartWorkflowRequestBody); ``` ### Arguments workflowId `string` - The ID of the workflow. Example: "12345" requestBody `StartWorkflowRequestBody` - Request body of startWorkflow method optionalsInput `StartWorkflowOptionalsInput` ### Returns This function returns a value of type `undefined`. Starts the workflow. --- ## Untitled *Type: page* UsersManager List enterprise users Create user Get current user Get user Update user Delete user List enterprise users Returns a list of all… # UsersManager - [List enterprise users](#list-enterprise-users) - [Create user](#create-user) - [Get current user](#get-current-user) - [Get user](#get-user) - [Update user](#update-user) - [Delete user](#delete-user) ## List enterprise users Returns a list of all users for the Enterprise along with their `user_id`, `public_name`, and `login`. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This operation is performed by calling function `getUsers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users/). ``` await client.users.getUsers(); ``` ### Arguments queryParams `GetUsersQueryParams` - Query parameters of getUsers method headersInput `GetUsersHeadersInput` - Headers of getUsers method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `Users`. Returns all of the users in the enterprise. ## Create user Creates a new managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `createUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users/). ``` await client.users.createUser({ name: userName, login: userLogin, isPlatformAccessOnly: true, } satisfies CreateUserRequestBody); ``` ### Arguments requestBody `CreateUserRequestBody` - Request body of createUser method optionalsInput `CreateUserOptionalsInput` ### Returns This function returns a value of type `UserFull`. Returns a user object for the newly created user. ## Get current user Retrieves information about the user who is currently authenticated. In the case of a client-side authenticated OAuth 2.0 application this will be the user who authorized the app. In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default. Use the `As-User` header to change who this API call is made on behalf of. This operation is performed by calling function `getUserMe`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-me/). ``` await client.users.getUserMe(); ``` ### Arguments queryParams `GetUserMeQueryParams` - Query parameters of getUserMe method headersInput `GetUserMeHeadersInput` - Headers of getUserMe method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `UserFull`. Returns a single user object. ## Get user Retrieves information about a user in the enterprise. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This endpoint also returns a limited set of information for external users who are collaborated on content owned by the enterprise for authenticated users with the right scopes. In this case, disallowed fields will return null instead. This operation is performed by calling function `getUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id/). ``` await client.users.getUserById(user.id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" optionalsInput `GetUserByIdOptionalsInput` ### Returns This function returns a value of type `UserFull`. Returns a single user object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields using the [fields](#get-users-id--request--fields) parameter. ## Update user Updates a managed or app user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `updateUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id/). ``` await client.users.updateUserById(user.id, { requestBody: { name: updatedUserName } satisfies UpdateUserByIdRequestBody, } satisfies UpdateUserByIdOptionalsInput); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" optionalsInput `UpdateUserByIdOptionalsInput` ### Returns This function returns a value of type `UserFull`. Returns the updated user object. ## Delete user Deletes a user. By default this will fail if the user still owns any content. Move their owned content first before proceeding, or use the `force` field to delete the user and their files. This operation is performed by calling function `deleteUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id/). ``` await client.users.deleteUserById(user.id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" optionalsInput `DeleteUserByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. Removes the user and returns an empty response. --- ## Untitled *Type: page* ZipDownloadsManager Create zip download Download zip archive Get zip download status Download ZIP Create zip download Creates a request to… # ZipDownloadsManager - [Create zip download](#create-zip-download) - [Download zip archive](#download-zip-archive) - [Get zip download status](#get-zip-download-status) - [Download ZIP](#download-zip) ## Create zip download Creates a request to download multiple files and folders as a single `zip` archive file. This API does not return the archive but instead performs all the checks to ensure that the user has access to all the items, and then returns a `download_url` and a `status_url` that can be used to download the archive. The limit for an archive is either the Account's upload limit or 10,000 files, whichever is met first. **Note**: Downloading a large file can be affected by various factors such as distance, network latency, bandwidth, and congestion, as well as packet loss ratio and current server load. For these reasons we recommend that a maximum ZIP archive total size does not exceed 25GB. This operation is performed by calling function `createZipDownload`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-zip-downloads/). ``` await client.zipDownloads.createZipDownload({ items: [ { id: file1.id, type: 'file' as ZipDownloadRequestItemsTypeField, } satisfies ZipDownloadRequestItemsField, { id: file2.id, type: 'file' as ZipDownloadRequestItemsTypeField, } satisfies ZipDownloadRequestItemsField, { id: folder1.id, type: 'folder' as ZipDownloadRequestItemsTypeField, } satisfies ZipDownloadRequestItemsField, ], downloadFileName: 'zip', } satisfies ZipDownloadRequest); ``` ### Arguments requestBody `ZipDownloadRequest` - Request body of createZipDownload method optionalsInput `CreateZipDownloadOptionalsInput` ### Returns This function returns a value of type `ZipDownload`. If the `zip` archive is ready to be downloaded, the API will return a response that will include a `download_url`, a `status_url`, as well as any conflicts that might have occurred when creating the request. ## Download zip archive Returns the contents of a `zip` archive in binary format. This URL does not require any form of authentication and could be used in a user's browser to download the archive to a user's device. By default, this URL is only valid for a few seconds from the creation of the request for this archive. Once a download has started it can not be stopped and resumed, instead a new request for a zip archive would need to be created. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `download_url` field in the response to this endpoint. This operation is performed by calling function `getZipDownloadContent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-content/). ``` await client.zipDownloads.getZipDownloadContent(zipDownload.downloadUrl!); ``` ### Arguments downloadUrl `string` - The URL that can be used to download created `zip` archive. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content` optionalsInput `GetZipDownloadContentOptionalsInput` ### Returns This function returns a value of type `ByteStream`. Returns the content of the items requested for this download, formatted as a stream of files and folders in a `zip` archive. ## Get zip download status Returns the download status of a `zip` archive, allowing an application to inspect the progress of the download as well as the number of items that might have been skipped. This endpoint can only be accessed once the download has started. Subsequently this endpoint is valid for 12 hours from the start of the download. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `status_url` field in the response to this endpoint. This operation is performed by calling function `getZipDownloadStatus`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-status/). ``` await client.zipDownloads.getZipDownloadStatus(zipDownload.statusUrl!); ``` ### Arguments statusUrl `string` - The URL that can be used to get the status of the `zip` archive being downloaded. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status` optionalsInput `GetZipDownloadStatusOptionalsInput` ### Returns This function returns a value of type `ZipDownloadStatus`. Returns the status of the `zip` archive that is being downloaded. ## Download ZIP Creates a zip and downloads its content This operation is performed by calling function `downloadZip`. ``` await client.zipDownloads.downloadZip({ items: [ { id: file1.id, type: 'file' as ZipDownloadRequestItemsTypeField, } satisfies ZipDownloadRequestItemsField, { id: file2.id, type: 'file' as ZipDownloadRequestItemsTypeField, } satisfies ZipDownloadRequestItemsField, { id: folder1.id, type: 'folder' as ZipDownloadRequestItemsTypeField, } satisfies ZipDownloadRequestItemsField, ], downloadFileName: 'zip', } satisfies ZipDownloadRequest); ``` ### Arguments requestBody `ZipDownloadRequest` - Zip download request body optionalsInput `DownloadZipOptionalsInput` ### Returns This function returns a value of type `ByteStream`. --- ## Untitled *Type: page* Handling null values in Box Typescript SDK Gen While using Box Typescript SDK it's important to understand how null values behave. This… # Handling null values in Box Typescript SDK Gen While using Box Typescript SDK it's important to understand how null values behave. This document provides a general overview of null value behaviour in Box Typescript SDK to help developers manage data consistently and predictably. ## Understanding null behaviour The Box Typescript SDK follows a consistent pattern when handling null values in update operations. This behaviour applies to most endpoints that modify resources such as users, files, folders and metadata. The updating field behaves differently depending on weather you omit it, set it to null, or provide a value: - Omitting the field: The field won't be included in request and the value will remain unchanged - Setting it to null: Setting a field to null, will cause sending HTTP request with field value set to null, what will result in removing its current value or disassociates it from the resource. - Providing a value: Providing a non-null value assigns or updates the field to that value. ## Example Usage The client.files.updateFileById() method demonstrates null handling when modifying the lock field while updating the file: ``` async function create_update_file(client) { fileId = '12345'; // locking the file const fileWithLock = await client.files.updateFileById(fileId, { requestBody: { lock: { access: 'lock' } }, queryParams: { fields: ['lock'] }, }); console.log('File with lock ', fileWithLock); // unlocking the file using lock value as null const fileWithoutLock = await client.files.updateFileById(fileId, { requestBody: { lock: null }, queryParams: { fields: ['lock'] }, }); console.log('File without lock ', fileWithoutLock); } ``` ## Summary To summarize, if you omit the field, the field remains unchanged. If you set it to null, it clears/removes the value. If you provide a value to that field, the field gets updated to that specified value. --- ## Untitled *Type: page* WebhooksManager List all webhooks Create webhook Get webhook Update webhook Remove webhook Validate a webhook message List all webhooks… # WebhooksManager - [List all webhooks](#list-all-webhooks) - [Create webhook](#create-webhook) - [Get webhook](#get-webhook) - [Update webhook](#update-webhook) - [Remove webhook](#remove-webhook) - [Validate a webhook message](#validate-a-webhook-message) ## List all webhooks Returns all defined webhooks for the requesting application. This API only returns webhooks that are applied to files or folders that are owned by the authenticated user. This means that an admin can not see webhooks created by a service account unless the admin has access to those folders, and vice versa. This operation is performed by calling function `getWebhooks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks/). ``` await client.webhooks.getWebhooks(); ``` ### Arguments queryParams `GetWebhooksQueryParams` - Query parameters of getWebhooks method headersInput `GetWebhooksHeadersInput` - Headers of getWebhooks method cancellationToken `undefined | CancellationToken` - Token used for request cancellation. ### Returns This function returns a value of type `Webhooks`. Returns a list of webhooks. ## Create webhook Creates a webhook. This operation is performed by calling function `createWebhook`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-webhooks/). ``` await client.webhooks.createWebhook({ target: { id: folder.id, type: 'folder' as CreateWebhookRequestBodyTargetTypeField, } satisfies CreateWebhookRequestBodyTargetField, address: 'https://example.com/new-webhook', triggers: ['FILE.UPLOADED' as CreateWebhookRequestBodyTriggersField], } satisfies CreateWebhookRequestBody); ``` ### Arguments requestBody `CreateWebhookRequestBody` - Request body of createWebhook method optionalsInput `CreateWebhookOptionalsInput` ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Get webhook Retrieves a specific webhook. This operation is performed by calling function `getWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks-id/). ``` await client.webhooks.getWebhookById(webhook.id!); ``` ### Arguments webhookId `string` - The ID of the webhook. Example: "3321123" optionalsInput `GetWebhookByIdOptionalsInput` ### Returns This function returns a value of type `Webhook`. Returns a webhook object. ## Update webhook Updates a webhook. This operation is performed by calling function `updateWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-webhooks-id/). ``` await client.webhooks.updateWebhookById(webhook.id!, { requestBody: { address: 'https://example.com/updated-webhook', } satisfies UpdateWebhookByIdRequestBody, } satisfies UpdateWebhookByIdOptionalsInput); ``` ### Arguments webhookId `string` - The ID of the webhook. Example: "3321123" optionalsInput `UpdateWebhookByIdOptionalsInput` ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Remove webhook Deletes a webhook. This operation is performed by calling function `deleteWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-webhooks-id/). ``` await client.webhooks.deleteWebhookById(webhook.id!); ``` ### Arguments webhookId `string` - The ID of the webhook. Example: "3321123" optionalsInput `DeleteWebhookByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. An empty response will be returned when the webhook was successfully deleted. ## Validate a webhook message Validate a webhook message by verifying the signature and the delivery timestamp This operation is performed by calling function `validateMessage`. ``` await WebhooksManager.validateMessage( body, headersWithCorrectDatetime, primaryKey, { secondaryKey: secondaryKey } satisfies ValidateMessageOptionalsInput, ); ``` ### Arguments body `string` - The request body of the webhook message headers `{ readonly [key: string]: string; }` - The headers of the webhook message primaryKey `string` - The primary signature to verify the message with optionalsInput `ValidateMessageOptionalsInput` ### Returns This function returns a value of type `boolean`. --- ## Untitled *Type: page* WebLinksManager Create web link Get web link Update web link Remove web link Create web link Creates a web link object within a folder. This… # WebLinksManager - [Create web link](#create-web-link) - [Get web link](#get-web-link) - [Update web link](#update-web-link) - [Remove web link](#remove-web-link) ## Create web link Creates a web link object within a folder. This operation is performed by calling function `createWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links/). ``` await client.webLinks.createWebLink({ url: 'https://www.box.com', parent: { id: parent.id } satisfies CreateWebLinkRequestBodyParentField, name: getUuid(), description: 'Weblink description', } satisfies CreateWebLinkRequestBody); ``` ### Arguments requestBody `CreateWebLinkRequestBody` - Request body of createWebLink method optionalsInput `CreateWebLinkOptionalsInput` ### Returns This function returns a value of type `WebLink`. Returns the newly created web link object. ## Get web link Retrieve information about a web link. This operation is performed by calling function `getWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id/). ``` await client.webLinks.getWebLinkById(weblink.id); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" optionalsInput `GetWebLinkByIdOptionalsInput` ### Returns This function returns a value of type `WebLink`. Returns the web link object. ## Update web link Updates a web link object. This operation is performed by calling function `updateWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id/). ``` await client.webLinks.updateWebLinkById(weblink.id, { requestBody: { name: updatedName, sharedLink: { access: 'open' as UpdateWebLinkByIdRequestBodySharedLinkAccessField, password: password, } satisfies UpdateWebLinkByIdRequestBodySharedLinkField, } satisfies UpdateWebLinkByIdRequestBody, } satisfies UpdateWebLinkByIdOptionalsInput); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" optionalsInput `UpdateWebLinkByIdOptionalsInput` ### Returns This function returns a value of type `WebLink`. Returns the updated web link object. ## Remove web link Deletes a web link. This operation is performed by calling function `deleteWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id/). ``` await client.webLinks.deleteWebLinkById(webLinkId); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" optionalsInput `DeleteWebLinkByIdOptionalsInput` ### Returns This function returns a value of type `undefined`. An empty response will be returned when the web link was successfully deleted. --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - this project is generated using [Box Codegen](https://github.com/box/box-codegen) based on[Box OpenAPI 3.0 Specification](https://github.com/box/box-openapi), so if you want found something you want to change in the generated code, you'll need to modify the codegen project and submit a pull request there. --- ## Untitled *Type: page* Migration Guide: From Box Node SDK to Box TypeScript SDK Migration Guide: From Box Node SDK to Box TypeScript SDK Introduction Installation… # Migration Guide: From Box Node SDK to Box TypeScript SDK [Migration Guide: From `Box Node SDK` to `Box TypeScript SDK`](#migration-guide-from-box-node-sdk-to-box-typescript-sdk) - [Introduction](#introduction) - [Installation](#installation) [Highlighting the Key Differences](#highlighting-the-key-differences) - [Native support for async-await and Promises](#native-support-for-async-await-and-promises) - [Embracing Explicitly Defined Schemas](#embracing-explicitly-defined-schemas) - [Immutable design](#immutable-design) [Diving into Authentication](#diving-into-authentication) - [Developer Token](#developer-token) [JWT Authentication](#jwt-authentication) - [Leveraging the JWT Configuration File](#leveraging-the-jwt-configuration-file) - [Manually Providing JWT Configuration](#manually-providing-jwt-configuration) - [User Authentication Simplified](#user-authentication-simplified) [Client Credentials Grant](#client-credentials-grant) - [Service Account Token Acquisition](#service-account-token-acquisition) - [User Token Acquisition](#user-token-acquisition) [Smooth Switching between Service Account and User](#smooth-switching-between-service-account-and-user) [OAuth 2.0 Authentication](#oauth-20-authentication) - [Fetching the Authorization URL](#fetching-the-authorization-url) - [Seamless Authentication](#seamless-authentication) [Customizable Token Storage and Retrieval Callbacks](#customizable-token-storage-and-retrieval-callbacks) [Downscope token](#downscope-token) [Revoke token](#revoke-token) [Configuration](#configuration) - [As-User header](#as-user-header) - [Custom Base URLs](#custom-base-urls) [Convenience methods](#convenience-methods) - [Webhook validation](#webhook-validation) - [Chunked upload of big files](#chunked-upload-of-big-files) ## Introduction Welcome to the `Box TypeScript SDK`, the pinnacle of Box's SDK evolution tailored for developers eager to integrate with the Box API using TypeScript. This next-generation toolkit is meticulously crafted with contemporary development practices, ensuring an unparalleled, seamless experience. While the `Box Node SDK` served its purpose well, the `Box TypeScript SDK` elevates the experience to new heights. One of its standout features is its auto-generation directly from the Open API Specification. This guarantees that developers are always equipped with the latest Box API features, eliminating any lag or discrepancies. This guide is your compass, offering insights and directions for a smooth migration from the legacy `Box Node SDK` to the state-of-the-art `Box TypeScript SDK`. As we journey through, we'll spotlight the key differences, enhanced functionalities, and the myriad benefits that await. For those who wish to delve deeper into the intricacies and advantages of the new SDK, the [official README](https://github.com/box/box-typescript-sdk-gen/blob/main/README.md) is a treasure trove of information. ## Installation Embarking on your journey with the `Box TypeScript SDK` is straightforward. Here's how you can set it up: ``` npm install box-typescript-sdk-gen ``` For those who are hesitant to make the full leap, fear not. The `Box TypeScript SDK` can coexist peacefully alongside the legacy `Box Node SDK` within the same project. This coexistence offers a gentle migration path, allowing developers to transition at their own pace. However, for an optimal experience, a complete transition to the new SDK is recommended in due course. ## Highlighting the Key Differences ### Native support for async-await and Promises The new SDK introduces a more organized and intuitive method of interacting with the Box API. Let's explore the changes: **Legacy (`Box Node SDK`):** In the older SDK, API interactions allowed for passing `callback` as the last argument ``` function callback(user) { console.log('hello', user); } client.users.get('123456', {} /* options */, callback); ``` If you didn't provide the `callback` a Promise would be returned. **Modern (`Box TypeScript SDK`):** The new SDK ensures promises are used consistently across the full SDK. ``` const user = await client.users.getUserById('123456'); ``` ### Embracing Explicitly Defined Schemas The new SDK brings clarity to data interactions by providing explicit data type definitions: **Legacy (`Box Node SDK`):** The older SDK was more ambiguous, which could lead to potential issues: ``` const file = await client.files.get('12345678'); /* file has generic Object type */ ``` **Modern (`Box TypeScript SDK`):** With the new SDK, developers can be confident in the data structures they're working with: ``` interface FileBase { id: string; type: FileBaseTypeField; etag?: string; } ``` ### Immutable design The new SDK is designed to be mostly immutable. This means that methods, which used to modify the existing object in old SDK now return a new instance of the class with the modified state. This design pattern is used to avoid side effects and make the code more predictable and easier to reason about. Methods, which returns a new modified instance of an object, will always have a prefix `with` in their names, e.g. **New (`box-sdk-gen`)** ``` asUserClient: BoxClient = client.withAsUserHeader('USER_ID'); ``` ## Diving into Authentication Authentication is a crucial aspect of any SDK. Let's delve into the authentication methods supported by both SDKs and understand the enhancements in the new version: ### Developer Token The Developer Token remains a straightforward method for authentication: **Legacy (`Box Node SDK`):** ``` var BoxSDK = require('box-node-sdk'); var sdk = new BoxSDK({ clientID: 'YOUR-CLIENT-ID', clientSecret: 'YOUR-CLIENT_SECRET', }); var client = sdk.getBasicClient('YOUR-DEVELOPER-TOKEN'); ``` **Modern (`Box TypeScript SDK`):** The new SDK offers a more streamlined approach: ``` import { BoxClient, BoxDeveloperTokenAuth } from 'box-typescript-sdk-gen'; const auth = new BoxDeveloperTokenAuth({ token: 'DEVELOPER_TOKEN_GOES_HERE' }); const client = new BoxClient({ auth }); ``` ### JWT Authentication JSON Web Tokens (JWT) offer a secure method of authentication. Here's how the process has evolved: #### Leveraging the JWT Configuration File **Legacy (`Box Node SDK`):** ``` var BoxSDK = require('box-node-sdk'); var jsonConfig = require('/path/to/config.json'); var sdk = BoxSDK.getPreconfiguredInstance(jsonConfig); var serviceAccountClient = sdk.getAppAuthClient('enterprise'); ``` **Modern (`Box TypeScript SDK`):** The new SDK provides a more organized approach: ``` import { BoxClient, BoxJwtAuth, JwtConfig } from 'box-typescript-sdk-gen'; const jwtConfig = JwtConfig.fromConfigFile('/path/to/config.json'); const auth = new BoxJwtAuth({ config: jwtConfig }); const client = new BoxClient({ auth }); ``` #### Manually Providing JWT Configuration For those who prefer manual configurations, both SDKs offer flexibility: **Legacy (`Box Node SDK`):** ``` var BoxSDK = require('box-node-sdk'); var sdk = new BoxSDK({ clientID: 'YOUR-CLIENT-ID', clientSecret: 'YOUR-CLIENT_SECRET', appAuth: { keyID: 'YOUR-KEY-ID', privateKey: 'YOUR-PRIVATE_KEY', passphrase: 'YOUR-PRIVATE-KEY-PASSPHRASE', }, }); var serviceAccountClient = sdk.getAppAuthClient( 'enterprise', 'YOUR-ENTERPRISE-ID', ); ``` **Modern (`Box TypeScript SDK`):** The new SDK introduces a more structured approach: ``` import { BoxJwtAuth, JwtConfig } from 'box-typescript-sdk-gen'; const jwtConfig = new JwtConfig({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', enterpriseId: 'YOUR_ENTERPRISE_ID', userId: 'USER_ID', jwtKeyId: 'YOUR_JWT_KEY_ID', privateKey: 'YOUR_PRIVATE_KEY', privateKeyPassphrase: 'PASSPHRASE', jwtAlgorithm: 'RS256', }); const auth = new BoxJwtAuth({ config: jwtConfig }); ``` #### User Authentication Simplified To authenticate as user you need to call `withUserSubject` method with id of the user to authenticate. The method returns a new instance of `BoxJwtAuth` class, which will perform authentication call in scope of the user on the first API call. The new auth instance can be used to create a new user client instance. **Legacy (`Box Node SDK`):** ``` const userClient = sdk.getAppAuthClient('user', 'USER_ID'); ``` **Modern (`Box TypeScript SDK`):** ``` const userAuth = jwtAuth.withUserSubject('USER_ID'); const userClient = new BoxClient({ auth: userAuth }); ``` ### Client Credentials Grant The Client Credentials Grant method is a popular choice for many developers. Let's see how it's been enhanced: #### Service Account Token Acquisition **Legacy (`Box Node SDK`):** ``` const BoxSDK = require('box-node-sdk'); const sdkConfig = { boxAppSettings: { clientID: 'CLIENT_ID', clientSecret: 'CLIENT_SECRET', }, enterpriseID: 'ENTERPRISE_ID', }; const sdk = BoxSDK.getPreconfiguredInstance(sdkConfig); const client = sdk.getAnonymousClient(); ``` **Modern (`Box TypeScript SDK`):** The new SDK offers a more organized structure: ``` import { CcgConfig, BoxCcgAuth, BoxClient } from 'box-typescript-sdk-gen'; const ccgConfig = new CcgConfig({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', enterpriseId: 'YOUR_ENTERPRISE_ID', }); const auth = new BoxCcgAuth({ config: ccgConfig }); const client = new BoxClient({ auth }); ``` #### User Token Acquisition **Legacy (`Box Node SDK`):** ``` const BoxSDK = require('box-node-sdk'); const sdkConfig = { boxAppSettings: { clientID: 'CLIENT_ID', clientSecret: 'CLIENT_SECRET', }, enterpriseID: 'ENTERPRISE_ID', // The enterprise id in this case is optional and can be omitted. }; const sdk = BoxSDK.getPreconfiguredInstance(sdkConfig); const client = sdk.getCCGClientForUser('USER_ID'); ``` **Modern (`Box TypeScript SDK`):** The new SDK streamlines the process: ``` import { CcgConfig, BoxCcgAuth, BoxClient } from 'box-typescript-sdk-gen'; const ccgConfig = new CcgConfig({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', userId: 'YOUR_USER_ID', }); const auth = new BoxCcgAuth({ config: ccgConfig }); const client = new BoxClient({ auth }); ``` ### Smooth Switching between Service Account and User In the new SDK, to keep the immutability design, the methods responsible for switching authenticated subject return a new instance of `BoxCcgAuth` class. The new instance will fetch a new token on the next API call. The new auth instance can be used to create a new client instance. The old instance of `BoxCcgAuth` class will remain unchanged and will still use the old token. **Legacy (`Box Node SDK`):** ``` const client = sdk.getCCGClientForUser('USER_ID'); ``` **Modern (`Box TypeScript SDK`):** To authenticate with enterprise subject call: ``` const enterpriseAuth = ccgAuth.withEnterpriseSubject('YOUR_ENTERPRISE_ID'); const enterpriseClient = new BoxClient({ auth: enterpriseAuth }); ``` To authenticate with user subject call: ``` const userAuth = ccgAuth.withUserSubject('YOUR_USER_ID'); const userClient = new BoxClient({ auth: userAuth }); ``` ### OAuth 2.0 Authentication OAuth 2.0 remains a robust authentication method. Let's explore the improvements: #### Fetching the Authorization URL **Legacy (`Box Node SDK`):** ``` var BoxSDK = require('box-node-sdk'); var sdk = new BoxSDK({ clientID: 'YOUR-CLIENT-ID', clientSecret: 'YOUR-CLIENT_SECRET', }); // the URL to redirect the user to var authorize_url = sdk.getAuthorizeURL({ response_type: 'code', }); ``` **Modern (`Box TypeScript SDK`):** The new SDK provides more flexibility: ``` import { BoxOAuth, OAuthConfig } from 'box-typescript-sdk-gen'; const config = new OAuthConfig({ clientId: 'OAUTH_CLIENT_ID', clientSecret: 'OAUTH_CLIENT_SECRET', }); const oauth = new BoxOAuth({ config: config }); var authorize_url = oauth.getAuthorizeUrl(); ``` #### Seamless Authentication **Legacy (`Box Node SDK`):** ``` sdk.getTokensAuthorizationCodeGrant('<CODE>', null, function (err, tokenInfo) { if (err) { // handle error } var tokenStore = new TokenStore(); tokenStore.write(tokenInfo, function (storeErr) { if (storeErr) { // handle token write error } var client = sdk.getPersistentClient(tokenInfo, tokenStore); }); }); ``` **Modern (`Box TypeScript SDK`):** The new SDK simplifies the process: ``` await oauth.getTokensAuthorizationCodeGrant('code'); const client = new BoxClient({ auth: oauth }); ``` ### Customizable Token Storage and Retrieval Callbacks Token management is crucial for maintaining secure sessions. The new SDK offers enhanced flexibility: **Legacy (`Box Node SDK`):** ``` function TokenStore() { // The token store constructor should create a specific store instance // for the user in question — it may need to take in a user ID or other // identifier. } TokenStore.prototype.read = function (callback) { // Read the user's tokens from your data store and // call the callback. // callback(error) if some error occured // callback(null, tokenInfo) if the read succeeded }; TokenStore.prototype.write = function (tokenInfo, callback) { // Write the token information to the store. // The tokenInfo argument is an Object, and can be // serialized as JSON for storage. // Call the callback after the write. // callback(error) if some error occured // callback(null) if the write succeeded }; TokenStore.prototype.clear = function (callback) { // Delete the user's token information from the store, // and call the callback after the write. // callback(error) if some error occured // callback(null) if the deletion succeeded }; ``` **Modern (`Box TypeScript SDK`):** The new SDK allows developers to define custom classes for token storage: ``` import { BoxOAuth } from 'box-typescript-sdk-gen'; import { TokenStorage } from 'box-typescript-sdk-gen/box/tokenStorage.generated'; import { AccessToken } from 'box-typescript-sdk-gen/schemas/accessToken.generated'; class CustomTokenStorage extends TokenStorage { async store(token: AccessToken): Promise<undefined> { // Store token } async get(): Promise<undefined | AccessToken> { // Retrieve token return token; } async clear(): Promise<undefined> { // Clear token } } const tokenStorage = new CustomTokenStorage(); const authConfig = { /* ... , */ tokenStorage }; const auth = new BoxOAuth({ config: authConfig }); ``` ### Downscope token To process of downscoping token in the new SDK is enhanced and more flexible. **Legacy (`Box Node SDK`):** ``` client .exchangeToken('item_preview', 'https://api.box.com/2.0/files/123456789') .then((tokenInfo) => { // tokenInfo.accessToken contains the new downscoped access token }); ``` **Modern (`Box TypeScript SDK`):** ``` let resource = 'https://api.box.com/2.0/files/123456789'; let token = await oauth.downscopeToken(['item_preview'], resource); const auth = new BoxDeveloperTokenAuth({ token: token.accessToken }); const client = new BoxClient({ auth }); ``` ### Revoke token The difference between the old and new SDK in the process of revoking token is as follows. **Legacy (`Box Node SDK`):** ``` client.revokeTokens('<TOKEN>').then(() => { // the client's access token have been revoked }); ``` **Modern (`Box TypeScript SDK`):** ``` await auth.revokeTokens(); ``` ## Configuration ### As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an `As-User: USER-ID` header. The following examples assume that the client has been instantiated with an access token with appropriate privileges to make As-User calls. In old SDK the client `asUser(userID)` method set up the client to impersonate a given user. It modified existing client, so that all calls made with its instance were made in context of the impersonated user. **Legacy (`Box Node SDK`):** ``` client.asUser('USER-ID'); client.folders.getItems('0').then((items) => { // items contains the collection of files and folders // in the root folder of the user with USER-ID }); ``` **Modern (`Box TypeScript SDK`):** In the new SDK the method was renamed to `withAsUserHeader(userId: string): BoxClient` and returns a new instance of `BoxClient` class with the As-User header appended to all API calls made by the client. ``` const userClient = client.withAsUserHeader('1234567'); ``` ### Custom Base URLs **Legacy (`Box Node SDK`):** In old SDK you could specify the custom base URLs, which will be used for API calls made by using the `configure` method on the SDK instance: ``` const sdk = BoxSDKNode.getPreconfiguredInstance(APP_SETTINGS); var additonalParams = { apiRootURL: 'https://my.company.url.com', uploadAPIRootURL: 'https://my.company.url.com/upload', authorizeRootURL: 'https://my.company.url.com/authorize', }; sdk.configure(additonalParams); ``` **Modern (`Box TypeScript SDK`):** In the new SDK this functionality has been implemented as part of the `BoxClient` class. By calling the `client.withCustomBaseUrls()` method, you can specify the custom base URLs that will be used for API calls made by client. Following the immutability pattern, this call creates a new client, leaving the original client unmodified. ``` const newClient = client.withCustomBaseUrls({ baseUrl: 'https://api.box.com', uploadUrl: 'https://upload.box.com/api', oauth2Url: 'https://account.box.com/api/oauth2', }); ``` ## Convenience methods ### Webhook validation Webhook validation is used to validate a webhook message by verifying the signature and the delivery timestamp. **Legacy (`Box Node SDK`):** In the old SDK, you could pass the `body` as either a `JSON` object or a `string`, and it would return a `boolean` value indicating whether the message was valid. ``` let isValid = BoxSDK.validateWebhookMessage( body, headers, primaryKey, secondaryKey, ); ``` **Modern (`Box TypeScript SDK`):** In the new SDK, the `WebhooksManager.validateMessage()` method requires the `body` to be of type `string`. So if the body is in `JSON` type, you must convert it to a `string` using `JSON.stringify(body)` before calling `validateMessage()`. ``` let stringBody = JSON.stringify(body); let isValid = await WebhooksManager.validateMessage( stringBody, headers, primaryKey, { secondaryKey: secondaryKey } satisfies ValidateMessageOptionalsInput, ); ``` ### Chunked upload of big files For large files or in cases where the network connection is less reliable, you may want to upload the file in parts. This allows a single part to fail without aborting the entire upload, and failed parts are being retried automatically. **Legacy (`Box Node SDK`):** In the old SDK, you could use the `getChunkedUploader()` method to create a chunked uploader object. Then, you would call the `start()` method to begin the upload process. The `getChunkedUploader()` method requires the `parentFolderId`, `fileSize`, `fileName` and `stream` parameters. ``` var stream = fs.createReadStream('/path/to/file.txt'); var fileName = 'new_name.txt'; var fileSize = fs.statSync('/path/to/file.txt').size; var parentFolderId = '0'; client.files .getChunkedUploader(parentFolderId, fileSize, fileName, stream) .then((uploader) => uploader.start()) .then((file) => { /* ... */ }); ``` **Modern (`Box TypeScript SDK`):** In the new SDK, the equivalent method is `chunked_uploads.uploadBigFile()`. It accepts a `Readable` object as the `file` parameter, and the `fileName` and `fileSize` parameters are now passed as arguments. The `parentFolderId` parameter is also required to specify the folder where the file will be uploaded. ``` import { File } from 'box-typescript-sdk-gen/schemas/file.generated'; var fileByteStream = fs.createReadStream('/path/to/file.txt'); var fileName = 'new_name.txt'; var fileSize = fs.statSync('/path/to/file.txt').size; var parentFolderId = '0'; const uploadedFile: File = await client.chunkedUploads.uploadBigFile( fileByteStream, fileName, fileSize, parentFolderId, ); ``` --- ## Untitled *Type: page* Box TypeScript SDK Gen Project Status build npm version image Platform Coverage We are excited to introduce the stable release of the latest… # Box TypeScript SDK Gen [](http://opensource.box.com/badges) [](https://badge.fury.io/js/box-typescript-sdk-gen) [](https://badge.fury.io/js/box-typescript-sdk-gen) [](https://coveralls.io/github/box/box-typescript-sdk-gen?branch=main) We are excited to introduce the stable release of the latest generation of Box TypeScript SDK, designed to elevate the developer experience and streamline your integration with the Box Content Cloud. With this SDK, you’ll have access to: 1. Full API Support: The new generation of Box SDKs empowers developers with complete coverage of the Box API ecosystem. You can now access all the latest features and functionalities offered by Box, allowing you to build even more sophisticated and feature-rich applications. 2. Rapid API Updates: Say goodbye to waiting for new Box APIs to be incorporated into the SDK. With our new auto-generation development approach, we can now add new Box APIs to the SDK at a much faster pace (in a matter of days). This means you can leverage the most up-to-date features in your applications without delay. 3. Embedded Documentation: We understand that easy access to information is crucial for developers. With our new approach, we have included comprehensive documentation for all objects and parameters directly in the source code of the SDK. This means you no longer need to look up this information on the developer portal, saving you time and streamlining your development process. 4. Enhanced Convenience Methods: Our commitment to enhancing your development experience continues with the introduction of convenience methods. These methods cover various aspects such as chunk uploads, classification, and much more. 5. Seamless Start: The new SDKs integrate essential functionalities like authentication, automatic retries with exponential backoff, exception handling, request cancellation, and type checking, enabling you to focus solely on your application's business logic. Embrace the new generation of Box SDKs and unlock the full potential of the Box Content Cloud. # Table of contents - [Box TypeScript SDK Gen](#box-typescript-sdk-gen) - [Table of contents](#table-of-contents) - [Installing](#installing) - [Getting Started](#getting-started) - [Documentation](#documentation) - [Browser Support](#browser-support) - [Upgrades](#upgrades) [Integration Tests](#integration-tests) [Running integration tests locally](#running-integration-tests-locally) - [Create Platform Application](#create-platform-application) - [Export configuration](#export-configuration) [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) [Copyright and License](#copyright-and-license) # Installing ``` npm install box-typescript-sdk-gen ``` If you use yarn, please do this instead: ``` yarn add box-typescript-sdk-gen ``` This is autogenerated Box SDK version. # Getting Started To get started with the SDK, get a Developer Token from the Configuration page of your app in the Box Developer Console. You can use this token to make test calls for your own Box account. The SDK provides an `DeveloperTokenAuth` class, which allows you to authenticate using your Developer Token. Use instance of `DeveloperTokenAuth` to initialize `Client` object. Using `Client` object you can access managers, which allow you to perform some operations on your Box account. The example below demonstrates how to authenticate with Developer Token and print names of all items inside a root folder. ``` const { BoxClient, BoxDeveloperTokenAuth } = require('box-typescript-sdk-gen'); async function main(token) { let auth = new BoxDeveloperTokenAuth({ token }); let client = new BoxClient({ auth }); let entries = (await client.folders.getFolderItems('0')).entries; entries.forEach((entry) => console.log(entry)); } main('INSERT YOUR DEVELOPER TOKEN HERE'); ``` In order to use in browser make sure you include the `lib/bundle.js` file and then you can access the classes like so: ``` const { BoxClient, BoxDeveloperTokenAuth } = window['box-typescript-sdk-gen']; ``` See example.html for an example website using this SDK. To run the example locally: 1. Start the local server by running `npx serve -p 3000` in the project directory. 2. Make sure `http://localhost:3000` is allowlisted in CORS Domains of your application. 3. Head over to `http://localhost:3000/example.html`. 4. Provide a fresh Developer Token to the dialog window that shows up upon running the example. 5. Make sure that you get an alert message that includes your user name. # Documentation Browse the [docs](https://developer.box.com/677ee1162df8d3617dad0e717cd71eff/README.md) or see [API Reference](https://developer.box.com/reference/) for more information. # Browser Support This SDK works in modern browsers that support ES6+ features. It seamlessly integrates with frontend frameworks like ReactJS, Angular, and NextJS. Check out our example below: - [React Sample App](https://github.com/box-community/box-ts-sdk-react) # Upgrades Upgrading from our legacy SDKs to the new generation SDKs is a straightforward process. See our [migration guide](https://developer.box.com/c1cfc600776a3c86c94118d743d3765e/migration-guide.md) and [changelog](https://developer.box.com/c81473c7d1440103f9e94f839bfcaa23/CHANGELOG.md) for more information. # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created in the Box Developer Console with `Server Authentication (with JWT)` selected as authentication method. Once created you can edit properties of the application: - In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. - In section `Advanced Features` enable `Make API calls using the as-user header` and `Generate user access tokens`. Now select `Authorization` and submit application to be reviewed by account admin. ### Export configuration Select `Configuration` tab and in the bottom in the section `App Settings` download your app configuration settings as JSON. 1. Encode configuration file to Base64, e.g. using command: `base64 -i path_to_json_file` 2. Set environment variable: `JWT_CONFIG_BASE_64` with base64 encoded jwt configuration file 3. Set environment variable: `BOX_FILE_REQUEST_ID` with ID of file request already created in the user account, `BOX_EXTERNAL_USER_EMAIL` with email of free external user which not belongs to any enterprise. 4. Set environment variable: `WORKFLOW_FOLDER_ID` with the ID of the Relay workflow that deletes the file that triggered the workflow. The workflow should have a manual start to be able to start it from the API. 5. Set environment variable: `APP_ITEM_ASSOCIATION_FILE_ID` to the ID of the file with associated app item and `APP_ITEM_ASSOCIATION_FOLDER_ID` to the ID of the folder with associated app item. 6. Set environment variable: `APP_ITEM_SHARED_LINK` to the shared link associated with app item. 7. Set environment variable: `SLACK_AUTOMATION_USER_ID` to the ID of the user responsible for the Slack automation, `SLACK_ORG_ID` to the ID of the Slack organization and `SLACK_PARTNER_ITEM_ID` to the ID of the Slack partner item. # Questions, Bugs, and Feature Requests? Need to contact us directly? Browse the issues tickets! Or, if that doesn't work, file a new one and we will get back to you. If you have general questions about the Box API, you can post to the [Box Developer Forum](https://forum.box.com/). # Copyright and License Copyright 2023 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Box TypeScript SDK Gen Browser Test Runner A browser-based test runner for Box TypeScript SDK, built with Next.js and Cypress. Features Run… # Box TypeScript SDK Gen Browser Test Runner A browser-based test runner for Box TypeScript SDK, built with Next.js and Cypress. ## Features - Run Box TypeScript SDK Gen tests in the browser in headless mode. ## Prerequisites - Node.js (v18 or higher) - Chrome or Firefox browser ## Installation 1. This project comes together with the Box TypeScript SDK Gen repository. To run the test runner, you need have the Box TypeScript SDK Gen repository checked out in parent directory and build it. 2. Setup the Environment Variables align with `sdkTest.config.mjs` file. 3. Install dependencies: ``` npm install ``` 1. Run the test runner: ``` npm run cypress:run:all ``` ## Configuration Inside `sdkTest.config.mjs` file we have a list of tests that we need to skip as it's not supported in the browser. --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 1.17.1 (2025-0… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### 1.17.1 (2025-08-07) ### Bug Fixes - Fix exports syntax when importing from `lib` ([#700](https://github.com/box/box-typescript-sdk-gen/issues/700)) ([782a287](https://github.com/box/box-typescript-sdk-gen/commit/782a287efd3481fc056effcf83886f05bc9adbf9)) ## 1.17.0 (2025-08-05) ### Bug Fixes - Bump `cypress` to resolve `CVE-2025-7783` in `form-data` (box/box-codegen[#769](https://github.com/box/box-typescript-sdk-gen/issues/769)) ([#677](https://github.com/box/box-typescript-sdk-gen/issues/677)) ([077413e](https://github.com/box/box-typescript-sdk-gen/commit/077413ec525fad4d8ebc4c7209fce20046731295)) ### New Features and Enhancements - Add AI spreadsheet processor (box/box-openapi[#533](https://github.com/box/box-typescript-sdk-gen/issues/533)) ([#649](https://github.com/box/box-typescript-sdk-gen/issues/649)) ([254fb54](https://github.com/box/box-typescript-sdk-gen/commit/254fb54d928ec3a76304674f341be1c67d78a143)) - Add Archive Public API (box/box-openapi[#540](https://github.com/box/box-typescript-sdk-gen/issues/540)) ([#674](https://github.com/box/box-typescript-sdk-gen/issues/674)) ([1cbb124](https://github.com/box/box-typescript-sdk-gen/commit/1cbb12485a417b813df8b6918cf3721ae781a286)) - Add new Hubs APIs and Hubs items API (box/box-openapi[#538](https://github.com/box/box-typescript-sdk-gen/issues/538)) ([#666](https://github.com/box/box-typescript-sdk-gen/issues/666)) ([25c9596](https://github.com/box/box-typescript-sdk-gen/commit/25c9596bc71fe88e0a2b6d5e01c65fa682c2fd38)) - Add new schema for `Metadata Error` (box/box-openapi[#539](https://github.com/box/box-typescript-sdk-gen/issues/539)) ([#667](https://github.com/box/box-typescript-sdk-gen/issues/667)) ([9af46ab](https://github.com/box/box-typescript-sdk-gen/commit/9af46abe837ee0d812bcc15f1edf0d5a6530bfe0)) - Allow injecting private key decryption mechanism for JWT (box/box-codegen[#754](https://github.com/box/box-typescript-sdk-gen/issues/754)) ([#656](https://github.com/box/box-typescript-sdk-gen/issues/656)) ([cb0c35d](https://github.com/box/box-typescript-sdk-gen/commit/cb0c35df4a5b3f9b8c611006dd33d480949a0d36)) - Improve webhook validation checks (box/box-codegen[#745](https://github.com/box/box-typescript-sdk-gen/issues/745)) ([#647](https://github.com/box/box-typescript-sdk-gen/issues/647)) ([98b3b92](https://github.com/box/box-typescript-sdk-gen/commit/98b3b9293ff3f0e5922d0772d87504770bb9303c)) - Retry request on network exception (box/box-codegen[#776](https://github.com/box/box-typescript-sdk-gen/issues/776)) ([#684](https://github.com/box/box-typescript-sdk-gen/issues/684)) ([c0c4dba](https://github.com/box/box-typescript-sdk-gen/commit/c0c4dbac40970d34da4c9e52fc43f029ae2f91a6)) - Support ESM build and tree-shaking (box/box-codegen[#762](https://github.com/box/box-typescript-sdk-gen/issues/762)) ([#663](https://github.com/box/box-typescript-sdk-gen/issues/663)) ([8ca3302](https://github.com/box/box-typescript-sdk-gen/commit/8ca33023d904edd596819c7c6df42022006274ed)) - Support Hubs beta endpoints (box/box-openapi[#531](https://github.com/box/box-typescript-sdk-gen/issues/531)) ([#641](https://github.com/box/box-typescript-sdk-gen/issues/641)) ([d8c7bb6](https://github.com/box/box-typescript-sdk-gen/commit/d8c7bb66736a3c4679b116916c61e2ead824a305)) - Support new tools in AI Studio (box/box-openapi[#534](https://github.com/box/box-typescript-sdk-gen/issues/534)) ([#652](https://github.com/box/box-typescript-sdk-gen/issues/652)) ([db2501b](https://github.com/box/box-typescript-sdk-gen/commit/db2501bb13fc6ecebbb4c535b4a19c9be2cf64c2)) ## 1.16.0 (2025-06-12) ### Bug Fixes - Compute webhook signature with and without escaping the body (box/box-codegen[#737](https://github.com/box/box-typescript-sdk-gen/issues/737)) ([#627](https://github.com/box/box-typescript-sdk-gen/issues/627)) ([6a21b8e](https://github.com/box/box-typescript-sdk-gen/commit/6a21b8ed54ef26041feccaa5481951355965e514)) - Fix circular dependency in `boxNetworkClient` (box/box-codegen[#708](https://github.com/box/box-typescript-sdk-gen/issues/708)) ([#591](https://github.com/box/box-typescript-sdk-gen/issues/591)) ([b383889](https://github.com/box/box-typescript-sdk-gen/commit/b383889b9fdc91c6cfed7169e4d36a22a8c8a0fa)) - Fix downscope token to use `retrieveToken` method for token retrieval (box/box-codegen[#731](https://github.com/box/box-typescript-sdk-gen/issues/731)) ([#618](https://github.com/box/box-typescript-sdk-gen/issues/618)) ([90edb0c](https://github.com/box/box-typescript-sdk-gen/commit/90edb0cc9bddc474c20b8b83770a4d314843edab)) - Fix slash escaping when calculating webhook signature (box/box-codegen[#736](https://github.com/box/box-typescript-sdk-gen/issues/736)) ([#624](https://github.com/box/box-typescript-sdk-gen/issues/624)) ([a0307d0](https://github.com/box/box-typescript-sdk-gen/commit/a0307d0c4c5dfed1a66e395a1dfb4c8ff387561d)) - Handle list of strings in metadata filter (box/box-codegen[#716](https://github.com/box/box-typescript-sdk-gen/issues/716)) ([#597](https://github.com/box/box-typescript-sdk-gen/issues/597)) ([979ff2c](https://github.com/box/box-typescript-sdk-gen/commit/979ff2c82edce9a969444febf1896d866ca154bf)) - Improve file download to avoid storing content in memory (box/box-codegen[#701](https://github.com/box/box-typescript-sdk-gen/issues/701)) ([#589](https://github.com/box/box-typescript-sdk-gen/issues/589)) ([513a15e](https://github.com/box/box-typescript-sdk-gen/commit/513a15eb28736d28d665324949d145dd3387d27d)) - Modify utility functions for browser (box/box-codegen[#686](https://github.com/box/box-typescript-sdk-gen/issues/686)) ([#585](https://github.com/box/box-typescript-sdk-gen/issues/585)) ([7232170](https://github.com/box/box-typescript-sdk-gen/commit/7232170fe7901cb7ba9ebf79ffc6a7c0b376a1c8)) - Use constant-time comparison for HMAC signatures (box/box-codegen[#739](https://github.com/box/box-typescript-sdk-gen/issues/739)) ([#630](https://github.com/box/box-typescript-sdk-gen/issues/630)) ([efdcaaf](https://github.com/box/box-typescript-sdk-gen/commit/efdcaaf605fc6f14bbbf171e2797d73e97302bfe)) ### New Features and Enhancements - Add AI agents warnings; allow for more types of metadata value (box/box-openapi[#520](https://github.com/box/box-typescript-sdk-gen/issues/520)) ([#600](https://github.com/box/box-typescript-sdk-gen/issues/600)) ([a5a555f](https://github.com/box/box-typescript-sdk-gen/commit/a5a555f835df5b550b9839e3e1fcff5d9f2b9f96)) - Add security settings properties on sign template schema (box/box-openapi[#518](https://github.com/box/box-typescript-sdk-gen/issues/518)) ([#588](https://github.com/box/box-typescript-sdk-gen/issues/588)) ([dfd3e5f](https://github.com/box/box-typescript-sdk-gen/commit/dfd3e5f7ecf8a8e49d79ed7df4d7e1f88f3e8537)) - Add Shield Lists APIs (box/box-openapi[#528](https://github.com/box/box-typescript-sdk-gen/issues/528)) ([#622](https://github.com/box/box-typescript-sdk-gen/issues/622)) ([be3af44](https://github.com/box/box-typescript-sdk-gen/commit/be3af441a66da02254d38576bb9ec258142f6d2d)) - Add support of IBM models to AI API (box/box-openapi[#522](https://github.com/box/box-typescript-sdk-gen/issues/522)) ([#601](https://github.com/box/box-typescript-sdk-gen/issues/601)) ([b060b8c](https://github.com/box/box-typescript-sdk-gen/commit/b060b8c21a13abdfb12988f9c6e6beb014fa104f)) - Increase max items for ai extract endpoints (box/box-openapi[#525](https://github.com/box/box-typescript-sdk-gen/issues/525)) ([#602](https://github.com/box/box-typescript-sdk-gen/issues/602)) ([86c5d14](https://github.com/box/box-typescript-sdk-gen/commit/86c5d14bafe8789c306a1688bcf010207c302ca9)) - Update legal holds and AI models (box/box-openapi[#526](https://github.com/box/box-typescript-sdk-gen/issues/526)) ([#620](https://github.com/box/box-typescript-sdk-gen/issues/620)) ([de3df57](https://github.com/box/box-typescript-sdk-gen/commit/de3df57cc90577a49ea40de278bde423d17c4f06)) ### 1.15.1 (2025-04-11) ### Bug Fixes - Fix data sanitizer for TypeScript (box/box-codegen[#702](https://github.com/box/box-typescript-sdk-gen/issues/702)) ([#582](https://github.com/box/box-typescript-sdk-gen/issues/582)) ([eb79c0f](https://github.com/box/box-typescript-sdk-gen/commit/eb79c0faa11f40667289155e71b8893a96eb558a)) ## 1.15.0 (2025-04-10) ### New Features and Enhancements - Support sensitive data sanitization in errors (box/box-codegen[#695](https://github.com/box/box-typescript-sdk-gen/issues/695)) ([#573](https://github.com/box/box-typescript-sdk-gen/issues/573)) ([488e76a](https://github.com/box/box-typescript-sdk-gen/commit/488e76a1e1f66d5d4ac56b16e6a7dae9e7f497a1)) ## 1.14.0 (2025-03-18) ### Bug Fixes - Add `verification_phone_number` property to create sign request (box/box-openapi[#515](https://github.com/box/box-typescript-sdk-gen/issues/515)) ([#546](https://github.com/box/box-typescript-sdk-gen/issues/546)) ([916502c](https://github.com/box/box-typescript-sdk-gen/commit/916502c47cb4936ab93a40b3f1552c1860173a8e)) ### New Features and Enhancements - Add find app item for shared link endpoint (box/box-openapi[#514](https://github.com/box/box-typescript-sdk-gen/issues/514)) ([#545](https://github.com/box/box-typescript-sdk-gen/issues/545)) ([7c32eaf](https://github.com/box/box-typescript-sdk-gen/commit/7c32eaf2af3ef08299d9dd69e744304b20f4309f)) - Add Integration Mappings Teams API (box/box-openapi[#517](https://github.com/box/box-typescript-sdk-gen/issues/517)) ([#548](https://github.com/box/box-typescript-sdk-gen/issues/548)) ([6ce1c7c](https://github.com/box/box-typescript-sdk-gen/commit/6ce1c7c78c9bc5d70383065e95f01bc8133fdd52)) - Support upload with preflight check (box/box-codegen[#676](https://github.com/box/box-typescript-sdk-gen/issues/676)) ([#554](https://github.com/box/box-typescript-sdk-gen/issues/554)) ([e3aa784](https://github.com/box/box-typescript-sdk-gen/commit/e3aa784b73c7b473fdf06c05c7f657a54fc08e4c)) ### 1.13.2 (2025-03-11) ### Bug Fixes - Fix `rollup` plugin output directory in Typescript (box/box-codegen[#678](https://github.com/box/box-typescript-sdk-gen/issues/678)) ([#543](https://github.com/box/box-typescript-sdk-gen/issues/543)) ([f828d5e](https://github.com/box/box-typescript-sdk-gen/commit/f828d5e7e3079c48590e9766f0dccd25ee1af9ca)) ### 1.13.1 (2025-03-07) ### Bug Fixes - Split browser configuration in `package.json` for TypeScript (box/box-codegen[#672](https://github.com/box/box-typescript-sdk-gen/issues/672)) ([#538](https://github.com/box/box-typescript-sdk-gen/issues/538)) ([ca7e291](https://github.com/box/box-typescript-sdk-gen/commit/ca7e29180e450cbb346a76aadfdade1062559b1e)) ## 1.13.0 (2025-02-20) ### New Features and Enhancements - Support AI Studio API (box/box-codegen[#626](https://github.com/box/box-typescript-sdk-gen/issues/626)) ([#520](https://github.com/box/box-typescript-sdk-gen/issues/520)) ([949b856](https://github.com/box/box-typescript-sdk-gen/commit/949b856ce1d77b1aa425b91b46440b46b383438a)) ## 1.12.0 (2025-02-06) ### New Features and Enhancements - Add Box Sign shared requests (box/box-openapi[#504](https://github.com/box/box-typescript-sdk-gen/issues/504)) ([#491](https://github.com/box/box-typescript-sdk-gen/issues/491)) ([e90255c](https://github.com/box/box-typescript-sdk-gen/commit/e90255c5d97a7a1a10dd529b58426142c5c6f0d4)) - feat: Add hubs support to `/ai/ask`. Replace type of `items` property from `AiItemBase[]` to `AiItemAsk[]` in the `AiAsk` interface (box/box-codegen[#656](https://github.com/box/box-typescript-sdk-gen/issues/656)) ([#507](https://github.com/box/box-typescript-sdk-gen/issues/507)) ([9f29d8c](https://github.com/box/box-typescript-sdk-gen/commit/9f29d8cb1f1d3b8c7625da1ddb9f2abd62d133f0)) - Update `/ai/extract_structured` response schema (box/box-codegen[#641](https://github.com/box/box-typescript-sdk-gen/issues/641)) ([#498](https://github.com/box/box-typescript-sdk-gen/issues/498)) ([502ac11](https://github.com/box/box-typescript-sdk-gen/commit/502ac11a2ad4e56fceece0deb6a15dbfc8b429ff)) ## 1.11.0 (2025-01-21) ### Bug Fixes - Add missing field assignments in constructor (box/box-codegen[#646](https://github.com/box/box-typescript-sdk-gen/issues/646)) ([#485](https://github.com/box/box-typescript-sdk-gen/issues/485)) ([0592f7b](https://github.com/box/box-typescript-sdk-gen/commit/0592f7bcde962c50d88ec69f6c359af754200e56)) - Add missing token scope (box/box-openapi[#490](https://github.com/box/box-typescript-sdk-gen/issues/490)) ([#459](https://github.com/box/box-typescript-sdk-gen/issues/459)) ([f0c0d91](https://github.com/box/box-typescript-sdk-gen/commit/f0c0d918c6d1a6466f9c02c760e3cbee18dab940)) - correct parameters types in file representation (box/box-openapi[#503](https://github.com/box/box-typescript-sdk-gen/issues/503)) ([#489](https://github.com/box/box-typescript-sdk-gen/issues/489)) ([d11529a](https://github.com/box/box-typescript-sdk-gen/commit/d11529a2958504e9106996fd475f0d99825b6926)) - Fix invalid variant config for Integration mapping Slack (box/box-openapi[#492](https://github.com/box/box-typescript-sdk-gen/issues/492)) ([#462](https://github.com/box/box-typescript-sdk-gen/issues/462)) ([660dc6e](https://github.com/box/box-typescript-sdk-gen/commit/660dc6ecd0302930ef5ce4d051860bac69a12188)) - order of fields in the `IntegrationMapping` schema (box/box-openapi[#497](https://github.com/box/box-typescript-sdk-gen/issues/497)) ([#476](https://github.com/box/box-typescript-sdk-gen/issues/476)) ([93e2bc3](https://github.com/box/box-typescript-sdk-gen/commit/93e2bc3f878f28d11d66a680c75ef0c06eada991)) - Remove `eval` usage (box/box-codegen[#636](https://github.com/box/box-typescript-sdk-gen/issues/636)) ([#474](https://github.com/box/box-typescript-sdk-gen/issues/474)) ([7c86f34](https://github.com/box/box-typescript-sdk-gen/commit/7c86f345e863efa338ac5808c5ec43cb6c549953)) - Remove auth when cross origin redirect (box/box-codegen[#648](https://github.com/box/box-typescript-sdk-gen/issues/648)) ([#488](https://github.com/box/box-typescript-sdk-gen/issues/488)) ([56fb287](https://github.com/box/box-typescript-sdk-gen/commit/56fb2879ab70ef6d5584b2591ff9c8d3ade2b7d7)) ### New Features and Enhancements - Support Box Doc Gen API (box/box-codegen[#644](https://github.com/box/box-typescript-sdk-gen/issues/644)) ([#486](https://github.com/box/box-typescript-sdk-gen/issues/486)) ([0d3bc18](https://github.com/box/box-typescript-sdk-gen/commit/0d3bc1813e11c1e482794f57c0843823e7e4cbc8)) - Use extensible enums (box/box-codegen[#639](https://github.com/box/box-typescript-sdk-gen/issues/639)) ([#487](https://github.com/box/box-typescript-sdk-gen/issues/487)) ([2a24c7a](https://github.com/box/box-typescript-sdk-gen/commit/2a24c7a0dbc3c946a69c5081939943d9b184d441)) ## 1.10.0 (2024-12-30) ### Bug Fixes - Remove unused parameter from `SignRequest` (box/box-openapi[#489](https://github.com/box/box-typescript-sdk-gen/issues/489)) ([#450](https://github.com/box/box-typescript-sdk-gen/issues/450)) ([f5683b7](https://github.com/box/box-typescript-sdk-gen/commit/f5683b703625dd8d504ca52100f692cb8440a474)) ### New Features and Enhancements - Add support for replacing the network client implementation (box/box-codegen[#629](https://github.com/box/box-typescript-sdk-gen/issues/629)) ([#454](https://github.com/box/box-typescript-sdk-gen/issues/454)) ([1cb7ddb](https://github.com/box/box-typescript-sdk-gen/commit/1cb7ddb3ada79cebc27fbfce9df90cd8ebad353c)) - Allow for customizing retry strategy (box/box-codegen[#635](https://github.com/box/box-typescript-sdk-gen/issues/635)) ([#457](https://github.com/box/box-typescript-sdk-gen/issues/457)) ([530ca33](https://github.com/box/box-typescript-sdk-gen/commit/530ca33ff3635581bd8ee91a82bc9f000b18812b)) - Support webhook message validation (box/box-codegen[#631](https://github.com/box/box-typescript-sdk-gen/issues/631)) ([#455](https://github.com/box/box-typescript-sdk-gen/issues/455)) ([09765a4](https://github.com/box/box-typescript-sdk-gen/commit/09765a42fe25f15095bd1bd0d1377f2da222c9e4)) ## 1.9.0 (2024-12-09) ### Bug Fixes - Fix signature of `beforeRequest` method in `Interceptor` interface (box/box-codegen[#625](https://github.com/box/box-typescript-sdk-gen/issues/625)) ([#446](https://github.com/box/box-typescript-sdk-gen/issues/446)) ([ef2e765](https://github.com/box/box-typescript-sdk-gen/commit/ef2e7658cab705906325e40d6c7c6e96e5703201)) ### New Features and Enhancements - Add `aiAgent` info to `AIResponse` (box/box-codegen[#624](https://github.com/box/box-typescript-sdk-gen/issues/624)) ([#440](https://github.com/box/box-typescript-sdk-gen/issues/440)) ([24c2013](https://github.com/box/box-typescript-sdk-gen/commit/24c20131b8275d43ecb02f3c94ac8e6116de3ea9)) - Support optional `userId` parameter for updating files, folders and web links (box/box-openapi[#488](https://github.com/box/box-typescript-sdk-gen/issues/488)) ([#445](https://github.com/box/box-typescript-sdk-gen/issues/445)) ([874f259](https://github.com/box/box-typescript-sdk-gen/commit/874f259ce12e8440301ffb1b2b65a6765b87803f)) ## 1.8.0 (2024-12-03) ### Bug Fixes - fix `additionalProperties` in `ClientError` (box/box-openapi[#477](https://github.com/box/box-typescript-sdk-gen/issues/477)) ([#385](https://github.com/box/box-typescript-sdk-gen/issues/385)) ([4547148](https://github.com/box/box-typescript-sdk-gen/commit/454714861019998b1fc6b7c44696b0178ffa022b)) - Fix chunked uploads in browser (box/box-codegen[#619](https://github.com/box/box-typescript-sdk-gen/issues/619)) ([#436](https://github.com/box/box-typescript-sdk-gen/issues/436)) ([0af2484](https://github.com/box/box-typescript-sdk-gen/commit/0af2484dd8387cce1a8c235068ac3f834f8ecf42)) - Support status codes with no content (box/box-codegen[#604](https://github.com/box/box-typescript-sdk-gen/issues/604)) ([#415](https://github.com/box/box-typescript-sdk-gen/issues/415)) ([c3f14c6](https://github.com/box/box-typescript-sdk-gen/commit/c3f14c6af55ab78ed5dc981909c67397b0d7219e)) - update client error schema to support schema errors (box/box-openapi[#467](https://github.com/box/box-typescript-sdk-gen/issues/467)) ([#381](https://github.com/box/box-typescript-sdk-gen/issues/381)) ([b845f12](https://github.com/box/box-typescript-sdk-gen/commit/b845f12d194d5f4e0cfd66db1db294e2f9a9bff8)) - update integration mapping response description (box/box-openapi[#463](https://github.com/box/box-typescript-sdk-gen/issues/463)) ([#379](https://github.com/box/box-typescript-sdk-gen/issues/379)) ([e3d71e1](https://github.com/box/box-typescript-sdk-gen/commit/e3d71e100500c5fa9e478b5228fd395f68242cf2)) ### New Features and Enhancements - add AI LLM endpoint AWS `params` (box/box-openapi[#478](https://github.com/box/box-typescript-sdk-gen/issues/478)) ([#388](https://github.com/box/box-typescript-sdk-gen/issues/388)) ([d2fd1ec](https://github.com/box/box-typescript-sdk-gen/commit/d2fd1ec4bddb19b353e286908c99477e08b90457)) - Expose method for making custom HTTP requests, convert `FetchOptions` into a class (box/box-codegen[#610](https://github.com/box/box-typescript-sdk-gen/issues/610)) ([#431](https://github.com/box/box-typescript-sdk-gen/issues/431)) ([9a9ea62](https://github.com/box/box-typescript-sdk-gen/commit/9a9ea628fd21001437d92b32f1760d5ba14cb46b)) - Support get collection by ID endpoint (box/box-codegen[#595](https://github.com/box/box-typescript-sdk-gen/issues/595)) ([#396](https://github.com/box/box-typescript-sdk-gen/issues/396)) ([f1f47be](https://github.com/box/box-typescript-sdk-gen/commit/f1f47bebfc0981a5e67f301b6fc2e3a8568d5845)) - Support getting file download URL and file thumbnail URL (box/box-codegen[#617](https://github.com/box/box-typescript-sdk-gen/issues/617)) ([#435](https://github.com/box/box-typescript-sdk-gen/issues/435)) ([1cb4d5d](https://github.com/box/box-typescript-sdk-gen/commit/1cb4d5d93fbd94b952b876457008973a92d5aa23)) - Support `nullable` fields in TypeScript (box/box-codegen[#612](https://github.com/box/box-typescript-sdk-gen/issues/612)) ([#425](https://github.com/box/box-typescript-sdk-gen/issues/425)) ([991dc29](https://github.com/box/box-typescript-sdk-gen/commit/991dc29bc805bf0c5198277142efb9a85de1dd42)) ## 1.7.0 (2024-10-17) ### New Features and Enhancements - Include raw data in response object (box/box-codegen[#576](https://github.com/box/box-typescript-sdk-gen/issues/576)) ([#375](https://github.com/box/box-typescript-sdk-gen/issues/375)) ([bdb9d0c](https://github.com/box/box-typescript-sdk-gen/commit/bdb9d0caab1a54ca56aef5de4260215d1d3fbd35)) - Support `ai/extract` and `ai/extract_structured` endpoints (box/box-codegen[#566](https://github.com/box/box-typescript-sdk-gen/issues/566)) ([#356](https://github.com/box/box-typescript-sdk-gen/issues/356)) ([4a33562](https://github.com/box/box-typescript-sdk-gen/commit/4a335621c7eaa413162a5daa65d63d8353ba37f5)) ## 1.6.0 (2024-09-11) ### Bug Fixes - Add the missing license to `package.json` (box/box-codegen[#562](https://github.com/box/box-typescript-sdk-gen/issues/562)) ([#343](https://github.com/box/box-typescript-sdk-gen/issues/343)) ([cc9a8b8](https://github.com/box/box-typescript-sdk-gen/commit/cc9a8b8ac628e348d32176f8ba69add649c555bd)) - Fix variants in metadata query results (box/box-openapi[#456](https://github.com/box/box-typescript-sdk-gen/issues/456)) ([#349](https://github.com/box/box-typescript-sdk-gen/issues/349)) ([2131e98](https://github.com/box/box-typescript-sdk-gen/commit/2131e98ff5530c7440ff50ec0da46cc317d0a4ae)) ### New Features and Enhancements - add Hubs Beta (box/box-openapi[#453](https://github.com/box/box-typescript-sdk-gen/issues/453)) ([#333](https://github.com/box/box-typescript-sdk-gen/issues/333)) ([40359c7](https://github.com/box/box-typescript-sdk-gen/commit/40359c71aa25ecfe7ec53bfa19de62b9d83d4ace)) - Add support for proxy (box/box-codegen[#559](https://github.com/box/box-typescript-sdk-gen/issues/559)) ([#337](https://github.com/box/box-typescript-sdk-gen/issues/337)) ([0ffd9c8](https://github.com/box/box-typescript-sdk-gen/commit/0ffd9c8095d1aa742144146383ae94f1f4526af0)) ### 1.5.1 (2024-08-30) ### Bug Fixes - Fix fetch options with interceptor (box/box-codegen[#556](https://github.com/box/box-typescript-sdk-gen/issues/556)) ([#326](https://github.com/box/box-typescript-sdk-gen/issues/326)) ([3751eea](https://github.com/box/box-typescript-sdk-gen/commit/3751eea67047021fe298c841596ae362ed1e47da)) ## 1.5.0 (2024-08-23) ### Bug Fixes - Add missing fields to Sign Template Signer and fix AI schema (box/box-openapi[#451](https://github.com/box/box-typescript-sdk-gen/issues/451)) ([#317](https://github.com/box/box-typescript-sdk-gen/issues/317)) ([340fbd8](https://github.com/box/box-typescript-sdk-gen/commit/340fbd84f6fa408155c6a2a4b9b7b03b88f76f24)) - Fix `IntegrationMapping` schemas (box/box-codegen[#551](https://github.com/box/box-typescript-sdk-gen/issues/551)) ([#315](https://github.com/box/box-typescript-sdk-gen/issues/315)) ([a863b1e](https://github.com/box/box-typescript-sdk-gen/commit/a863b1eb8fcfccd78714e3f52ce96d89ef69ca72)) ### New Features and Enhancements - Add new parameters to Box AI methods and introduce `AiResponseFull` variant (box/box-openapi[#446](https://github.com/box/box-typescript-sdk-gen/issues/446)) ([#313](https://github.com/box/box-typescript-sdk-gen/issues/313)) ([d9664fd](https://github.com/box/box-typescript-sdk-gen/commit/d9664fd7d431685c8e115415085bbe69d17f272d)) - Include URL into `FetchOptions` (box/box-codegen[#549](https://github.com/box/box-typescript-sdk-gen/issues/549)) ([#319](https://github.com/box/box-typescript-sdk-gen/issues/319)) ([30eaa6b](https://github.com/box/box-typescript-sdk-gen/commit/30eaa6ba7aa0fcd5e2f71026d7bf58729d387221)) ## 1.4.0 (2024-08-12) ### Bug Fixes - Add missing token scope (box/box-openapi[#442](https://github.com/box/box-typescript-sdk-gen/issues/442)) ([#281](https://github.com/box/box-typescript-sdk-gen/issues/281)) ([ca77f58](https://github.com/box/box-typescript-sdk-gen/commit/ca77f58b10d3a302748750584730f0fcdd8b4b55)) - Fix fetch method for multipart request (box/box-codegen[#545](https://github.com/box/box-typescript-sdk-gen/issues/545)) ([#303](https://github.com/box/box-typescript-sdk-gen/issues/303)) ([f8ceac0](https://github.com/box/box-typescript-sdk-gen/commit/f8ceac005f043017e7cde310490e79ab9195f8d7)) ### New Features and Enhancements - Parametrise chunked uploads endpoint urls (box/box-openapi[#444](https://github.com/box/box-typescript-sdk-gen/issues/444)) ([#302](https://github.com/box/box-typescript-sdk-gen/issues/302)) ([293a6e9](https://github.com/box/box-typescript-sdk-gen/commit/293a6e9aeabbba37e4c12e2322a79717a10e1775)) - **ts:** Add comments to properties and methods (box/box-codegen[#537](https://github.com/box/box-typescript-sdk-gen/issues/537)) ([#284](https://github.com/box/box-typescript-sdk-gen/issues/284)) ([db3a2b5](https://github.com/box/box-typescript-sdk-gen/commit/db3a2b57fbe0eec17373a2acf8089ff247c98225)) ## 1.3.0 (2024-07-24) ### Bug Fixes - Extract `IntegrationMappingPartnerItemSlack` to union type (box/box-codegen[#530](https://github.com/box/box-typescript-sdk-gen/issues/530)) ([#255](https://github.com/box/box-typescript-sdk-gen/issues/255)) ([fa8952a](https://github.com/box/box-typescript-sdk-gen/commit/fa8952a6582d9965bbb4ab66bbeff057f5c68851)) - Improve chunked upload reliability (box/box-codegen[#529](https://github.com/box/box-typescript-sdk-gen/issues/529)) ([#254](https://github.com/box/box-typescript-sdk-gen/issues/254)) ([12d9288](https://github.com/box/box-typescript-sdk-gen/commit/12d928850e0a1cd60f336a9919474b9aaba33028)) ### New Features and Enhancements - Add `is_active` parameter to user collaboration (box/box-openapi[#437](https://github.com/box/box-typescript-sdk-gen/issues/437)) ([#253](https://github.com/box/box-typescript-sdk-gen/issues/253)) ([4d8d436](https://github.com/box/box-typescript-sdk-gen/commit/4d8d436977b3e487a47e7717626f1c0f2eb43227)) - Support AI Agent API (box/box-codegen[#531](https://github.com/box/box-typescript-sdk-gen/issues/531)) ([#260](https://github.com/box/box-typescript-sdk-gen/issues/260)) ([0ec40d4](https://github.com/box/box-typescript-sdk-gen/commit/0ec40d44c86a8a9cf4fe594966cfad1866be457c)) ## 1.2.0 (2024-07-08) ### Bug Fixes - Fix upload in browser (box/box-codegen[#524](https://github.com/box/box-typescript-sdk-gen/issues/524)) ([#248](https://github.com/box/box-typescript-sdk-gen/issues/248)) ([88d747e](https://github.com/box/box-typescript-sdk-gen/commit/88d747e0f03dfa3c2d6089257c6e8b5b635775e0)) - Update chunked upload (box/box-codegen[#523](https://github.com/box/box-typescript-sdk-gen/issues/523)) ([#247](https://github.com/box/box-typescript-sdk-gen/issues/247)) ([27ceb35](https://github.com/box/box-typescript-sdk-gen/commit/27ceb35e6444843eea9b7ec6923fe958c9a74571)) ### New Features and Enhancements - Retry request with status code `202` (box/box-codegen[#511](https://github.com/box/box-typescript-sdk-gen/issues/511)) ([#235](https://github.com/box/box-typescript-sdk-gen/issues/235)) ([03b8f43](https://github.com/box/box-typescript-sdk-gen/commit/03b8f4314ada5ef5596706b7599cc76565fe96a5)) - Support extensible enum types in Typescript (box/box-codegen[#520](https://github.com/box/box-typescript-sdk-gen/issues/520)) ([#243](https://github.com/box/box-typescript-sdk-gen/issues/243)) ([5237972](https://github.com/box/box-typescript-sdk-gen/commit/523797273bc08e3b22609ef0019432ab3e43c3ba)) ## 1.1.0 (2024-06-12) ### Bug Fixes - Fix CI for auto update pull requests (box/box-codegen[#506](https://github.com/box/box-typescript-sdk-gen/issues/506)) ([#221](https://github.com/box/box-typescript-sdk-gen/issues/221)) ([bbc14f6](https://github.com/box/box-typescript-sdk-gen/commit/bbc14f66e14a9386c8d54a5d0bb36ec2cdc501c1)) - remove quotation mark when date or `datetime` is used in `queryParams` (box/box-codegen[#509](https://github.com/box/box-typescript-sdk-gen/issues/509)) ([#225](https://github.com/box/box-typescript-sdk-gen/issues/225)) ([28d2220](https://github.com/box/box-typescript-sdk-gen/commit/28d22200602cf02d73590189c304109f1c26db17)) ### New Features and Enhancements - add missing marker pagination fields and introduce new event type `AppItemEventSource` `(box/box-openapi[#431](https://github.com/box/box-typescript-sdk-gen/issues/431))` ([#224](https://github.com/box/box-typescript-sdk-gen/issues/224)) ([6c18ca3](https://github.com/box/box-typescript-sdk-gen/commit/6c18ca3b00da0b878d28e142a2361b6386ef0c15)) ## 1.0.0 (2024-05-20) ### Bug Fixes - Change base urls (box/box-codegen[#491](https://github.com/box/box-typescript-sdk-gen/issues/491)) ([#199](https://github.com/box/box-typescript-sdk-gen/issues/199)) ([8a732e9](https://github.com/box/box-typescript-sdk-gen/commit/8a732e9050c2434dddfb62ebd611d0794284165b)) - Fix schemas for updating classification on a file and folder (box/box-openapi[#423](https://github.com/box/box-typescript-sdk-gen/issues/423)) ([#188](https://github.com/box/box-typescript-sdk-gen/issues/188)) ([68ecb04](https://github.com/box/box-typescript-sdk-gen/commit/68ecb0435e14cd8e21e81cbb8763c49d25952a3d)) - Fix union deserialization (box/box-codegen[#493](https://github.com/box/box-typescript-sdk-gen/issues/493)) ([#202](https://github.com/box/box-typescript-sdk-gen/issues/202)) ([23b9016](https://github.com/box/box-typescript-sdk-gen/commit/23b901685dd83e9f94386c5c889ab1b1a7ee75f8)) - Stop exporting `PartAccumulator` class (box/box-codegen[#494](https://github.com/box/box-typescript-sdk-gen/issues/494)) ([#200](https://github.com/box/box-typescript-sdk-gen/issues/200)) ([98a668e](https://github.com/box/box-typescript-sdk-gen/commit/98a668e8dbdce931d5737172db57d61424f8d75a)) ### New Features and Enhancements - Add `suppressNotifications` and `externalSystemName` fields for Box Sign (box/box-openapi[#425](https://github.com/box/box-typescript-sdk-gen/issues/425)) ([#197](https://github.com/box/box-typescript-sdk-gen/issues/197)) ([f4e4d52](https://github.com/box/box-typescript-sdk-gen/commit/f4e4d52822d4f9ef291916c8e7986d4d5201789b)) - Move schemas to separate modules (box/box-codegen[#483](https://github.com/box/box-typescript-sdk-gen/issues/483)) ([#182](https://github.com/box/box-typescript-sdk-gen/issues/182)) ([cf55214](https://github.com/box/box-typescript-sdk-gen/commit/cf5521440a81543dc7ac032221c1778267cef2f4)) - Support excluding endpoints and schemas in parser (box/box-codegen[#487](https://github.com/box/box-typescript-sdk-gen/issues/487)) ([#183](https://github.com/box/box-typescript-sdk-gen/issues/183)) ([3bd6076](https://github.com/box/box-typescript-sdk-gen/commit/3bd6076c45dcae5db2bafbcb49364fa5629ec8ce)) - Strict checks during deserialization (box/box-codegen[#484](https://github.com/box/box-typescript-sdk-gen/issues/484)) ([#185](https://github.com/box/box-typescript-sdk-gen/issues/185)) ([469afb9](https://github.com/box/box-typescript-sdk-gen/commit/469afb951bd4dbbd2ef7af916084b6baf02040f6)) ### 0.5.4 (2024-05-09) ### Bug Fixes - Ensure AuthorizationManager in authentication classes is initialized with NetworkSession object (box/box-codegen[#469](https://github.com/box/box-typescript-sdk-gen/issues/469)) ([#140](https://github.com/box/box-typescript-sdk-gen/issues/140)) ([464bc25](https://github.com/box/box-typescript-sdk-gen/commit/464bc25ddef82f36bd19d0cfb37e4692e343f913)) - Fix Box AI endpoints (box/box-openapi[#418](https://github.com/box/box-typescript-sdk-gen/issues/418)) ([#171](https://github.com/box/box-typescript-sdk-gen/issues/171)) ([6450322](https://github.com/box/box-typescript-sdk-gen/commit/6450322d6868cd2bf26768ca3aafddcf3422b6cf)) - Fix metadata filter resource (box/box-openapi[#419](https://github.com/box/box-typescript-sdk-gen/issues/419)) ([#173](https://github.com/box/box-typescript-sdk-gen/issues/173)) ([38ca06c](https://github.com/box/box-typescript-sdk-gen/commit/38ca06c95627a5795b854ba2c749f7e627284685)) - Remove most of use of any in generated code (box/box-codegen[#475](https://github.com/box/box-typescript-sdk-gen/issues/475)) ([#166](https://github.com/box/box-typescript-sdk-gen/issues/166)) ([9fabddf](https://github.com/box/box-typescript-sdk-gen/commit/9fabddfed89358b309eac2208a5aaa21a441befd)) ### New Features and Enhancements - Define interfaces for headers input (box/box-codegen[#468](https://github.com/box/box-typescript-sdk-gen/issues/468)) ([#134](https://github.com/box/box-typescript-sdk-gen/issues/134)) ([28b266c](https://github.com/box/box-typescript-sdk-gen/commit/28b266c0747f477e226d99893931c259a4ad2262)) - pack optional arguments of API methods into a new record(box/box-codegen[#471](https://github.com/box/box-typescript-sdk-gen/issues/471)) ([#156](https://github.com/box/box-typescript-sdk-gen/issues/156)) ([2f311c9](https://github.com/box/box-typescript-sdk-gen/commit/2f311c919ed2b9bdb104f66e91f0feb6c8798a71)) - Support Box AI endpoints (box/box-openapi[#416](https://github.com/box/box-typescript-sdk-gen/issues/416)) ([#170](https://github.com/box/box-typescript-sdk-gen/issues/170)) ([febd8d0](https://github.com/box/box-typescript-sdk-gen/commit/febd8d026795238218a0246a736433f2b95767ba)) - Support Date and DateTime types (box/box-codegen[#476](https://github.com/box/box-typescript-sdk-gen/issues/476)) ([#152](https://github.com/box/box-typescript-sdk-gen/issues/152)) ([9939ea9](https://github.com/box/box-typescript-sdk-gen/commit/9939ea9a9bb614499def01e6c767c3ed678ba2ba)) - Support revoking and downscoping token for BoxDeveloperTokenAuth ([#147](https://github.com/box/box-typescript-sdk-gen/issues/147)) ([6d09845](https://github.com/box/box-typescript-sdk-gen/commit/6d0984524d82765da925bc2081eadba5a5d03c66)) - Support union of primitives and objects (box/box-codegen[#481](https://github.com/box/box-typescript-sdk-gen/issues/481)) ([#172](https://github.com/box/box-typescript-sdk-gen/issues/172)) ([c3c6457](https://github.com/box/box-typescript-sdk-gen/commit/c3c6457bb069fe04df0c664ad6056a357077d55b)) ### 0.5.3 (2024-04-04) ### Bug Fixes - **docs:** fixes for chunked uploads docs (box/box-codegen[#457](https://github.com/box/box-typescript-sdk-gen/issues/457)) ([#128](https://github.com/box/box-typescript-sdk-gen/issues/128)) ([c94dbf5](https://github.com/box/box-typescript-sdk-gen/commit/c94dbf5926010e2bec8fc54c317999957a2f3eab)) ### New Features and Enhancements - Assign default value to fields and args of type enum with only one value (box/box-codegen[#465](https://github.com/box/box-typescript-sdk-gen/issues/465)) ([#131](https://github.com/box/box-typescript-sdk-gen/issues/131)) ([bf4d58c](https://github.com/box/box-typescript-sdk-gen/commit/bf4d58c4c19c10f0ede27a4e9c4f7b3861bcd6f7)) - Change `asUser` and `asEnterprise` method names (box/box-codegen[#464](https://github.com/box/box-typescript-sdk-gen/issues/464)) ([#125](https://github.com/box/box-typescript-sdk-gen/issues/125)) ([22c1907](https://github.com/box/box-typescript-sdk-gen/commit/22c19071723430498baa6aa5c5846b0249f061ca)) - **transformers:** determineIsType (box/box-codegen[#148](https://github.com/box/box-typescript-sdk-gen/issues/148)) ([#129](https://github.com/box/box-typescript-sdk-gen/issues/129)) ([57ccdac](https://github.com/box/box-typescript-sdk-gen/commit/57ccdaca74f68b7e221a43bce967e983ef4b0fcf)) ### 0.5.2 (2024-03-26) ### New Features and Enhancements - Support `additionalProperties` of type any in Python and TS (box/box-codegen[#453](https://github.com/box/box-typescript-sdk-gen/issues/453)) ([#97](https://github.com/box/box-typescript-sdk-gen/issues/97)) ([d159548](https://github.com/box/box-typescript-sdk-gen/commit/d159548d38b74fbb410ab1cadb16033948efa14b)) - Support custom Agent in Typescript (box/box-codegen[#452](https://github.com/box/box-typescript-sdk-gen/issues/452)) ([#117](https://github.com/box/box-typescript-sdk-gen/issues/117)) ([de06c26](https://github.com/box/box-typescript-sdk-gen/commit/de06c2672f3efb20e1b685e1c5abf92dff659da3)) - use getDiscriminatorsForUnion in generic serialization (box/box-codegen[#448](https://github.com/box/box-typescript-sdk-gen/issues/448)) ([#95](https://github.com/box/box-typescript-sdk-gen/issues/95)) ([06680c0](https://github.com/box/box-typescript-sdk-gen/commit/06680c05a6c7eb2ff2c20886c642901ac618cd83)) ### 0.5.1 (2024-03-11) ### New Features and Enhancements - Replace jsonwebtoken with jose (box/box-codegen[#444](https://github.com/box/box-typescript-sdk-gen/issues/444)) ([#85](https://github.com/box/box-typescript-sdk-gen/issues/85)) ([2ae8658](https://github.com/box/box-typescript-sdk-gen/commit/2ae86589d85764d485383cc0bc1474b611cc4dc2)) --- ## Untitled *Type: page* Documentation High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available… # Documentation ## High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available by topic: - [Ai](https://developer.box.com/a09026b413af100740e2d62f08e338a8/ai.md) - [Ai studio](https://developer.box.com/d2fc436ac21a939f957804200fd51573/ai_studio.md) - [App item associations](https://developer.box.com/3fe11188dfa3635fd55a7aeb7686ea0b/app_item_associations.md) - [Archives](https://developer.box.com/19c490866888a750ea6f3e6c81ca8bbe/archives.md) - [Authorization](https://developer.box.com/59f4e8c23b4987ec1bc1f0e9bd7ab180/authorization.md) - [Avatars](https://developer.box.com/835511e98f383f1cbcf689229c7da2ba/avatars.md) - [Chunked uploads](https://developer.box.com/e28a459d3fa63fb006a342ef28a13b43/chunked_uploads.md) - [Classifications](https://developer.box.com/cdf5e5e0c239360f75fe50b4b657f8d5/classifications.md) - [Collaboration allowlist entries](https://developer.box.com/74a70dbaba7d04ba57e696fe4437068c/collaboration_allowlist_entries.md) - [Collaboration allowlist exempt targets](https://developer.box.com/204645934a033b7eb2c9cef9ea19c614/collaboration_allowlist_exempt_targets.md) - [Collections](https://developer.box.com/3cfdf1ea1b847b61221ada88462f5554/collections.md) - [Comments](https://developer.box.com/668e8f09c4fdeef337b7ac1c262001e1/comments.md) - [Device pinners](https://developer.box.com/b4ed6470194d72582bfe8f541dab93ef/device_pinners.md) - [Docgen](https://developer.box.com/7614dc2c59c23352f407b295008e49fd/docgen.md) - [Docgen template](https://developer.box.com/6a6b103a64e8ff15d5cc2a6b577bc1ab/docgen_template.md) - [Downloads](https://developer.box.com/3e62c42c0330571a33e2b70dde7c00cd/downloads.md) - [Email aliases](https://developer.box.com/3180baa385460a64185c867e53196285/email_aliases.md) - [Events](https://developer.box.com/68e3bc78e5339519a98765b19d0eaedf/events.md) - [File classifications](https://developer.box.com/db6a7e2c5748e968aed6eefb8fb77a0d/file_classifications.md) - [File metadata](https://developer.box.com/95d8e6c29063d06e0476accdd6b06837/file_metadata.md) - [File requests](https://developer.box.com/527311a9e6fc596c5a59ca58625c8e61/file_requests.md) - [File version legal holds](https://developer.box.com/14bbcbe0aba045c5337cc55fbba52303/file_version_legal_holds.md) - [File version retentions](https://developer.box.com/d8b8993ac7b381689e41c53472631f2d/file_version_retentions.md) - [File versions](https://developer.box.com/d4a2db69b4c5df3e1e505ddcced7d987/file_versions.md) - [File watermarks](https://developer.box.com/3a5a549b5e5c0bf4ea5acb108cb922a2/file_watermarks.md) - [Files](https://developer.box.com/1a3895c9c4085feb5a7b424c0b92b72a/files.md) - [Folder classifications](https://developer.box.com/3991b429b08dfd4523d51558600e91e2/folder_classifications.md) - [Folder locks](https://developer.box.com/a7b5efca17c684f1601b9c29827bdf61/folder_locks.md) - [Folder metadata](https://developer.box.com/2a1e36f3381e803dc9adebb737cfd75a/folder_metadata.md) - [Folder watermarks](https://developer.box.com/dad5e85c61ce5e5bb088e1735fcd32cf/folder_watermarks.md) - [Folders](https://developer.box.com/4cea719129f8f7047d01357558228e59/folders.md) - [Groups](https://developer.box.com/19c77e92519e0a377c60c8dda9c7d349/groups.md) - [Hub collaborations](https://developer.box.com/2971b3b1575ebe0e6f2b6de997bec0a5/hub_collaborations.md) - [Hub items](https://developer.box.com/2b9ba0977646a714310ca5ce75681a30/hub_items.md) - [Hubs](https://developer.box.com/345655c51d5496c7fc3068f3ecd1e6e0/hubs.md) - [Integration mappings](https://developer.box.com/7c4cb93f5abbc92622f1d06dc4ff0a48/integration_mappings.md) - [Invites](https://developer.box.com/e8d87e010425e6b27fc254653694500f/invites.md) - [Legal hold policies](https://developer.box.com/cc1ffb63a81826d05ca3a4950e63f8e3/legal_hold_policies.md) - [Legal hold policy assignments](https://developer.box.com/2b6c038eab6a8600f9f6b532ed3532a0/legal_hold_policy_assignments.md) - [List collaborations](https://developer.box.com/bf50c526ea161dafbd5382843fe2617e/list_collaborations.md) - [Memberships](https://developer.box.com/fabf5a724fe1d6758e5433a6fa755617/memberships.md) - [Metadata cascade policies](https://developer.box.com/1e39db6079a70edb0312a95531bf87ec/metadata_cascade_policies.md) - [Metadata templates](https://developer.box.com/af2c8cef2f3d9fa291a686879e21b30b/metadata_templates.md) - [Recent items](https://developer.box.com/5421143128a2076837c5c40e082fff9b/recent_items.md) - [Retention policies](https://developer.box.com/e47f383b8d4d6865c6f3478c1fcb90d4/retention_policies.md) - [Retention policy assignments](https://developer.box.com/883337653a1c49f9bd592ede24cfb143/retention_policy_assignments.md) - [Search](https://developer.box.com/41d1e9a77431b613d308b4b383b2dc75/search.md) - [Session termination](https://developer.box.com/cd389a41a0640c06a4712e408d3e71e1/session_termination.md) - [Shared links app items](https://developer.box.com/d8c2a236b7ef57c5be71032bc6115936/shared_links_app_items.md) - [Shared links files](https://developer.box.com/18e781ff9227033bcd1896624d8f34e0/shared_links_files.md) - [Shared links folders](https://developer.box.com/84c8a671deed018692ed60bf777612a9/shared_links_folders.md) - [Shared links web links](https://developer.box.com/beda87247d3103630705a063809e1308/shared_links_web_links.md) - [Shield information barrier reports](https://developer.box.com/73579b1b9fbb371253789ee5cb2d8d44/shield_information_barrier_reports.md) - [Shield information barrier segment members](https://developer.box.com/14027a92b5496fd7c9db7161f30f6281/shield_information_barrier_segment_members.md) - [Shield information barrier segment restrictions](https://developer.box.com/85adc6b4f11a7d9c2a9a443a0f1d9faa/shield_information_barrier_segment_restrictions.md) - [Shield information barrier segments](https://developer.box.com/d5af9c5729c6ec938df42f5610d2efab/shield_information_barrier_segments.md) - [Shield information barriers](https://developer.box.com/fefd039c6cfecc64c50aa865fdd55057/shield_information_barriers.md) - [Shield lists](https://developer.box.com/6393c29083285fac04053345968dc3e4/shield_lists.md) - [Sign requests](https://developer.box.com/36a68c89098d3ebe8649b5351f685623/sign_requests.md) - [Sign templates](https://developer.box.com/edc3ff97e19ce3ad45500ac5dc86e019/sign_templates.md) - [Skills](https://developer.box.com/792f07c753b36b7648b47547c06a93fd/skills.md) - [Storage policies](https://developer.box.com/62f44b17e16c80a951b00a2c86fd32fa/storage_policies.md) - [Storage policy assignments](https://developer.box.com/8c0281073ae3f81d0cc3dbc537f5ba97/storage_policy_assignments.md) - [Task assignments](https://developer.box.com/7bd13edd15c58703c420934a1cc2ef38/task_assignments.md) - [Tasks](https://developer.box.com/ba79c47e22e68578b3fceba0f1225a5b/tasks.md) - [Terms of service user statuses](https://developer.box.com/2cb30f787d2c3d525188041d80888c19/terms_of_service_user_statuses.md) - [Terms of services](https://developer.box.com/641fd0bf3f5214d946f7633b972e6926/terms_of_services.md) - [Transfer](https://developer.box.com/3705357f8d670d464178ec5dd3049ef4/transfer.md) - [Trashed files](https://developer.box.com/b8081c45623ed15e1cd461c9457f9672/trashed_files.md) - [Trashed folders](https://developer.box.com/5cc3673f450994accbd7ad299d875225/trashed_folders.md) - [Trashed items](https://developer.box.com/cdb3cc83aff70c2d018934fbac244e78/trashed_items.md) - [Trashed web links](https://developer.box.com/8865f15da142222971012311287e3144/trashed_web_links.md) - [Uploads](https://developer.box.com/51c242a5a8f87bae3d50ed4fc2fe098f/uploads.md) - [User collaborations](https://developer.box.com/254eb81c4645ee29e3a254c5cd55bb52/user_collaborations.md) - [Users](https://developer.box.com/ee2eb34588a34363bceeac553216c603/users.md) - [Web links](https://developer.box.com/fd88c2a990d46c5ab5117e733629b658/web_links.md) - [Webhooks](https://developer.box.com/6c982161944f5adb31074ffa72e92e63/webhooks.md) - [Workflows](https://developer.box.com/85c3e34f878e722529594e16e279bcc3/workflows.md) - [Zip downloads](https://developer.box.com/6a6ad1c1ca1ec0808f1f75ab18cb2d55/zip_downloads.md) --- ## Untitled *Type: page* AiStudioManager List AI agents Create AI agent Update AI agent Get AI agent by agent ID Delete AI agent List AI agents Lists AI agents based… # AiStudioManager - [List AI agents](#list-ai-agents) - [Create AI agent](#create-ai-agent) - [Update AI agent](#update-ai-agent) - [Get AI agent by agent ID](#get-ai-agent-by-agent-id) - [Delete AI agent](#delete-ai-agent) ## List AI agents Lists AI agents based on the provided parameters. This operation is performed by calling function `get_ai_agents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents/). ``` client.ai_studio.get_ai_agents() ``` ### Arguments mode `Optional[List[str]]` - The mode to filter the agent config to return. Possible values are: `ask`, `text_gen`, and `extract`. fields `Optional[List[str]]` - The fields to return in the response. agent_state `Optional[List[str]]` - The state of the agents to return. Possible values are: `enabled`, `disabled` and `enabled_for_selected_users`. include_box_default `Optional[bool]` - Whether to include the Box default agents in the response. marker `Optional[str]` - Defines the position marker at which to begin returning results. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AiMultipleAgentResponse`. A successful response including the agents list. ## Create AI agent Creates an AI agent. At least one of the following capabilities must be provided: `ask`, `text_gen`, `extract`. This operation is performed by calling function `create_ai_agent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-agents/). ``` client.ai_studio.create_ai_agent( agent_name, "enabled", ask=AiStudioAgentAsk(access_state="enabled", description="desc1"), ) ``` ### Arguments type `CreateAiAgentType` - The type of agent used to handle queries. name `str` - The name of the AI Agent. access_state `str` - The state of the AI Agent. Possible values are: `enabled`, `disabled`, and `enabled_for_selected_users`. icon_reference `Optional[str]` - The icon reference of the AI Agent. It should have format of the URL `https://cdn01.boxcdn.net/app-assets/aistudio/avatars/<file_name>` where possible values of `file_name` are: `logo_boxAi.png`,`logo_stamp.png`,`logo_legal.png`,`logo_finance.png`,`logo_config.png`,`logo_handshake.png`,`logo_analytics.png`,`logo_classification.png`. allowed_entities `Optional[List[AiAgentAllowedEntity]]` - List of allowed users or groups. ask `Optional[AiStudioAgentAsk]` text_gen `Optional[AiStudioAgentTextGen]` extract `Optional[AiStudioAgentExtract]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Update AI agent Updates an AI agent. This operation is performed by calling function `update_ai_agent_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-ai-agents-id/). ``` client.ai_studio.update_ai_agent_by_id( created_agent.id, agent_name, "enabled", ask=AiStudioAgentAsk(access_state="disabled", description="desc2"), ) ``` ### Arguments agent_id `str` - The ID of the agent to update. Example: "1234" type `UpdateAiAgentByIdType` - The type of agent used to handle queries. name `str` - The name of the AI Agent. access_state `str` - The state of the AI Agent. Possible values are: `enabled`, `disabled`, and `enabled_for_selected_users`. icon_reference `Optional[str]` - The icon reference of the AI Agent. It should have format of the URL `https://cdn01.boxcdn.net/app-assets/aistudio/avatars/<file_name>` where possible values of `file_name` are: `logo_boxAi.png`,`logo_stamp.png`,`logo_legal.png`,`logo_finance.png`,`logo_config.png`,`logo_handshake.png`,`logo_analytics.png`,`logo_classification.png`. allowed_entities `Optional[List[AiAgentAllowedEntity]]` - List of allowed users or groups. ask `Optional[AiStudioAgentAsk]` text_gen `Optional[AiStudioAgentTextGen]` extract `Optional[AiStudioAgentExtract]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Get AI agent by agent ID Gets an AI Agent using the `agent_id` parameter. This operation is performed by calling function `get_ai_agent_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents-id/). ``` client.ai_studio.get_ai_agent_by_id(created_agent.id, fields=["ask"]) ``` ### Arguments agent_id `str` - The agent id to get. Example: "1234" fields `Optional[List[str]]` - The fields to return in the response. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AiSingleAgentResponseFull`. A successful response including the agent. ## Delete AI agent Deletes an AI agent using the provided parameters. This operation is performed by calling function `delete_ai_agent_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-ai-agents-id/). ``` client.ai_studio.delete_ai_agent_by_id(created_agent.id) ``` ### Arguments agent_id `str` - The ID of the agent to delete. Example: "1234" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A successful response with no content. --- ## Untitled *Type: page* AiManager Ask question Generate text Get AI agent default configuration Extract metadata (freeform) Extract metadata (structured) Ask… # AiManager - [Ask question](#ask-question) - [Generate text](#generate-text) - [Get AI agent default configuration](#get-ai-agent-default-configuration) - [Extract metadata (freeform)](#extract-metadata-freeform) - [Extract metadata (structured)](#extract-metadata-structured) ## Ask question Sends an AI request to supported LLMs and returns an answer specifically focused on the user's question given the provided context. This operation is performed by calling function `create_ai_ask`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-ask/). ``` client.ai.create_ai_ask( CreateAiAskMode.SINGLE_ITEM_QA, "which direction sun rises", [ AiItemAsk( id=file_to_ask.id, type=AiItemAskTypeField.FILE, content="Sun rises in the East", ) ], ai_agent=ai_ask_agent_config, ) ``` ### Arguments mode `CreateAiAskMode` - Box AI handles text documents with text representations up to 1MB in size, or a maximum of 25 files, whichever comes first. If the text file size exceeds 1MB, the first 1MB of text representation will be processed. Box AI handles image documents with a resolution of 1024 x 1024 pixels, with a maximum of 5 images or 5 pages for multi-page images. If the number of image or image pages exceeds 5, the first 5 images or pages will be processed. If you set mode parameter to `single_item_qa`, the items array can have one element only. Currently Box AI does not support multi-modal requests. If both images and text are sent Box AI will only process the text. prompt `str` - The prompt provided by the client to be answered by the LLM. The prompt's length is limited to 10000 characters. items `List[AiItemAsk]` - The items to be processed by the LLM, often files. dialogue_history `Optional[List[AiDialogueHistory]]` - The history of prompts and answers previously passed to the LLM. This provides additional context to the LLM in generating the response. include_citations `Optional[bool]` - A flag to indicate whether citations should be returned. ai_agent `Optional[Union[AiAgentAsk, AiAgentReference]]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Optional[AiResponseFull]`. A successful response including the answer from the LLM.No content is available to answer the question. This is returned when the request item is a hub, but content in the hubs is not indexed. To ensure content in the hub is indexed, make sure Box AI for Hubs in the Admin Console was enabled before hub creation. ## Generate text Sends an AI request to supported Large Language Models (LLMs) and returns generated text based on the provided prompt. This operation is performed by calling function `create_ai_text_gen`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-text-gen/). ``` client.ai.create_ai_text_gen( "Parapharse the document.s", [ CreateAiTextGenItems( id=file_to_ask.id, type=CreateAiTextGenItemsTypeField.FILE, content="The Earth goes around the sun. Sun rises in the East in the morning.", ) ], dialogue_history=[ AiDialogueHistory( prompt="What does the earth go around?", answer="The sun", created_at=date_time_from_string("2021-01-01T00:00:00Z"), ), AiDialogueHistory( prompt="On Earth, where does the sun rise?", answer="East", created_at=date_time_from_string("2021-01-01T00:00:00Z"), ), ], ai_agent=ai_text_gen_agent_config, ) ``` ### Arguments prompt `str` - The prompt provided by the client to be answered by the LLM. The prompt's length is limited to 10000 characters. items `List[CreateAiTextGenItems]` - The items to be processed by the LLM, often files. The array can include **exactly one** element. **Note**: Box AI handles documents with text representations up to 1MB in size. If the file size exceeds 1MB, the first 1MB of text representation will be processed. dialogue_history `Optional[List[AiDialogueHistory]]` - The history of prompts and answers previously passed to the LLM. This parameter provides the additional context to the LLM when generating the response. ai_agent `Optional[Union[AiAgentReference, AiAgentTextGen]]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AiResponse`. A successful response including the answer from the LLM. ## Get AI agent default configuration Get the AI agent default config. This operation is performed by calling function `get_ai_agent_default_config`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agent-default/). ``` client.ai.get_ai_agent_default_config(GetAiAgentDefaultConfigMode.ASK, language="en-US") ``` ### Arguments mode `GetAiAgentDefaultConfigMode` - The mode to filter the agent config to return. language `Optional[str]` - The ISO language code to return the agent config for. If the language is not supported the default agent config is returned. model `Optional[str]` - The model to return the default agent config for. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Union[AiAgentAsk, AiAgentTextGen, AiAgentExtract, AiAgentExtractStructured]`. A successful response including the default agent configuration. This response can be one of the following four objects: - AI agent for questions - AI agent for text generation - AI agent for freeform metadata extraction AI agent for structured metadata extraction. The response depends on the agent configuration requested in this endpoint. ## Extract metadata (freeform) Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of key-value pairs. In this request, both the prompt and the output can be freeform. Metadata template setup before sending the request is not required. This operation is performed by calling function `create_ai_extract`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract/). ``` client.ai.create_ai_extract( "firstName, lastName, location, yearOfBirth, company", [AiItemBase(id=file.id)], ai_agent=agent_ignoring_overriding_embeddings_model, ) ``` ### Arguments prompt `str` - The prompt provided to a Large Language Model (LLM) in the request. The prompt can be up to 10000 characters long and it can be an XML or a JSON schema. items `List[AiItemBase]` - The items that LLM will process. Currently, you can use files only. ai_agent `Optional[Union[AiAgentReference, AiAgentExtract]]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AiResponse`. A response including the answer from the LLM. ## Extract metadata (structured) Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. For this request, you either need a metadata template or a list of fields you want to extract. Input is **either** a metadata template or a list of fields to ensure the structure. To learn more about creating templates, see [Creating metadata templates in the Admin Console](https://support.box.com/hc/en-us/articles/360044194033-Customizing-Metadata-Templates) or use the [metadata template API](g://metadata/templates/create). This operation is performed by calling function `create_ai_extract_structured`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract-structured/). ``` client.ai.create_ai_extract_structured( [AiItemBase(id=file.id)], fields=[ CreateAiExtractStructuredFields( key="firstName", display_name="First name", description="Person first name", prompt="What is the your first name?", type="string", ), CreateAiExtractStructuredFields( key="lastName", display_name="Last name", description="Person last name", prompt="What is the your last name?", type="string", ), CreateAiExtractStructuredFields( key="dateOfBirth", display_name="Birth date", description="Person date of birth", prompt="What is the date of your birth?", type="date", ), CreateAiExtractStructuredFields( key="age", display_name="Age", description="Person age", prompt="How old are you?", type="float", ), CreateAiExtractStructuredFields( key="hobby", display_name="Hobby", description="Person hobby", prompt="What is your hobby?", type="multiSelect", options=[ CreateAiExtractStructuredFieldsOptionsField(key="guitar"), CreateAiExtractStructuredFieldsOptionsField(key="books"), ], ), ], ai_agent=agent_ignoring_overriding_embeddings_model, ) ``` ### Arguments items `List[AiItemBase]` - The items to be processed by the LLM. Currently you can use files only. metadata_template `Optional[CreateAiExtractStructuredMetadataTemplate]` - The metadata template containing the fields to extract. For your request to work, you must provide either `metadata_template` or `fields`, but not both. fields `Optional[List[CreateAiExtractStructuredFields]]` - The fields to be extracted from the provided items. For your request to work, you must provide either `metadata_template` or `fields`, but not both. ai_agent `Optional[Union[AiAgentReference, AiAgentExtractStructured]]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AiExtractStructuredResponse`. A successful response including the answer from the LLM. --- ## Untitled *Type: page* ArchivesManager List archives Create archive Delete archive List archives Retrieves archives for an enterprise. This operation is performed… # ArchivesManager - [List archives](#list-archives) - [Create archive](#create-archive) - [Delete archive](#delete-archive) ## List archives Retrieves archives for an enterprise. This operation is performed by calling function `get_archives_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-archives/). ``` client.archives.get_archives_v2025_r0(limit=100) ``` ### Arguments limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ArchivesV2025R0`. Returns a list of archives in the enterprise. ## Create archive Creates an archive. This operation is performed by calling function `create_archive_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-archives/). ``` client.archives.create_archive_v2025_r0(archive_name) ``` ### Arguments name `str` - The name of the archive. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ArchiveV2025R0`. Returns a new archive object. ## Delete archive Permanently deletes an archive. This operation is performed by calling function `delete_archive_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-archives-id/). ``` client.archives.delete_archive_by_id_v2025_r0(archive.id) ``` ### Arguments archive_id `str` - The ID of the archive. Example: "982312" box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the archive has been deleted. --- ## Untitled *Type: page* AppItemAssociationsManager List file app item associations List folder app item associations List file app item associations This is a beta… # AppItemAssociationsManager - [List file app item associations](#list-file-app-item-associations) - [List folder app item associations](#list-folder-app-item-associations) ## List file app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the file is associated with. This includes app items associated with ancestors of the file. Assuming the context user has access to the file, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `get_file_app_item_associations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-app-item-associations/). ``` client.app_item_associations.get_file_app_item_associations(file_id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. application_type `Optional[str]` - If given, only return app items for this application type. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this file, an empty collection will be returned. This list includes app items on ancestors of this File. ## List folder app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the folder is associated with. This includes app items associated with ancestors of the folder. Assuming the context user has access to the folder, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `get_folder_app_item_associations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-app-item-associations/). ``` client.app_item_associations.get_folder_app_item_associations(folder_id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. application_type `Optional[str]` - If given, returns only app items for this application type. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this folder an empty collection will be returned. This list includes app items on ancestors of this folder. --- ## Untitled *Type: page* Authentication Authentication Authentication methods Developer Token JWT Auth Authenticate Enterprise Authenticate user Client Credentials… # Authentication - [Authentication](#authentication) [Authentication methods](#authentication-methods) - [Developer Token](#developer-token) [JWT Auth](#jwt-auth) - [Authenticate Enterprise](#authenticate-enterprise) - [Authenticate user](#authenticate-user) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) - [Switching between Service Account and User](#switching-between-service-account-and-user) [OAuth 2.0 Auth](#oauth-20-auth) - [Authentication with OAuth2](#authentication-with-oauth2) - [Injecting existing token into BoxOAuth](#injecting-existing-token-into-boxoauth) [Retrieve current access token](#retrieve-current-access-token) [Refresh access token](#refresh-access-token) [Revoke token](#revoke-token) [Downscope token](#downscope-token) [Token storage](#token-storage) - [In-memory token storage](#in-memory-token-storage) - [File token storage](#file-token-storage) - [File with in-memory token storage](#file-with-in-memory-token-storage) - [Custom storage](#custom-storage) # Authentication methods ## Developer Token The fastest way to get started using the API is with developer token. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. To create a `BoxClient` with a developer token, construct an `BoxDeveloperTokenAuth` object with the `token` set to the developer token and construct the client with that. ``` from box_sdk_gen import BoxClient, BoxDeveloperTokenAuth auth = BoxDeveloperTokenAuth(token="DEVELOPER_TOKEN_GOES_HERE") client = BoxClient(auth=auth) me = client.users.get_user_me() print(f"My user ID is {me.id}") ``` ## JWT Auth Authenticating with a JWT requires some extra dependencies. To get them, use ``` pip install "box-sdk-gen[jwt]" ``` Before using JWT Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with JWT](https://developer.box.com/guides/authentication/jwt/jwt-setup/) ### Authenticate Enterprise JWT auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. If you generated your public and private keys automatically through the [Box Developer Console](https://app.box.com/developers/console), you can use the JSON file created there to configure your SDK instance and create a client to make calls as the Service Account. Call one of static `BoxJWTAuth` method: `JWTConfig.from_config_file(config_file_path='/path/to/settings.json')` and pass JSON file local path or `JWTConfig.from_config_json_string(config_json_string)` and pass JSON config file content as string. ``` from box_sdk_gen import BoxClient, BoxJWTAuth, JWTConfig jwt_config = JWTConfig.from_config_file(config_file_path="/path/to/settings.json") auth = BoxJWTAuth(config=jwt_config) client = BoxClient(auth=auth) service_account = client.users.get_user_me() print(f"Service Account user ID is {service_account.id}") ``` Otherwise, you'll need to provide the necessary configuration fields directly to the `JWTConfig` constructor: ``` from box_sdk_gen import BoxClient, BoxJWTAuth, JWTConfig jwt_config = JWTConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", jwt_key_id="YOUR_JWT_KEY_ID", private_key="YOUR_PRIVATE_KEY", private_key_passphrase="PASSPHRASE", enterprise_id="YOUR_ENTERPRISE_ID", ) auth = BoxJWTAuth(config=jwt_config) service_account_client = BoxClient(auth=auth) ``` ### Authenticate user App auth applications also often have associated [App Users](https://developer.box.com/guides/getting-started/user-types/app-users/), which are created and managed directly by the application — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user to make calls as that user. See the [API documentation](https://developer.box.com/) for detailed instructions on how to use app auth. Clients for making calls as an App User can be created with the same JSON JWT config file generated through the [Box Developer Console](https://app.box.com/developers/console). Calling `auth.with_user_subject('USER_ID')` method will return a new auth object, which is authenticated as the user with provided id, leaving the original object unchanged. ``` from box_sdk_gen import BoxClient, BoxJWTAuth, JWTConfig jwt_config = JWTConfig.from_config_file(config_file_path="/path/to/settings.json") auth = BoxJWTAuth(config=jwt_config) user_auth = auth.with_user_subject("USER_ID") user_client = BoxClient(auth=user_auth) ``` Alternatively, clients for making calls as an App User can be created with the same `JWTConfig` constructor as in the above examples, similarly to creating a Service Account client. Simply pass the `user_id` instead of `enterprise_id` when constructing the auth config instance: ``` from box_sdk_gen import BoxClient, BoxJWTAuth, JWTConfig jwt_config = JWTConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", jwt_key_id="YOUR_JWT_KEY_ID", private_key="YOUR_PRIVATE_KEY", private_key_passphrase="PASSPHRASE", user_id="USER_ID", ) auth = BoxJWTAuth(config=jwt_config) user_client = BoxClient(auth=auth) ``` ## Client Credentials Grant Before using Client Credentials Grant Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with Client Credentials Grant](https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/) Client Credentials Grant Auth method allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account. You can use `BoxCCGAuth` to initialize a client object the same way as for other authentication types: ``` from box_sdk_gen import BoxClient, BoxCCGAuth, CCGConfig ccg_config = CCGConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user_id="YOUR_USER_ID", ) auth = BoxCCGAuth(config=ccg_config) client = BoxClient(auth=auth) print(f"Id of the authenticated user is: {client.users.get_user_me().id}") ``` Obtained token is valid for specified amount of time, it will be refreshed automatically by default. ### Obtaining Service Account token The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID with client id and secret: ``` from box_sdk_gen import BoxClient, BoxCCGAuth, CCGConfig ccg_config = CCGConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", enterprise_id="YOUR_ENTERPRISE_ID", ) auth = BoxCCGAuth(config=ccg_config) client = BoxClient(auth=auth) ``` ### Obtaining User token In order to enable obtaining user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/console). In `Configuration` tab, in section `Advanced Features` select `Generate user access tokens`. Do not forget to re-authorize application if it was already authorized. To obtain user account you will have to provide user ID with client id and secret. ``` from box_sdk_gen import BoxClient, BoxCCGAuth, CCGConfig ccg_config = CCGConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user_id="YOUR_USER_ID", ) auth = BoxCCGAuth(config=ccg_config) client = BoxClient(auth=auth) ``` ### Switching between Service Account and User You can easily switch to be authenticated as a Service Account or as a User. To create a new auth object authenticated as Service Account you can call: ``` enterprise_auth = auth.with_enterprise_subject(enterprise_id="YOUR_ENTERPRISE_ID") enterprise_client = BoxClient(auth=enterprise_auth) ``` To authenticate with user subject call: ``` user_auth = auth.with_user_subject(user_id="YOUR_USER_ID") user_client = BoxClient(auth=user_auth) ``` The new token will be automatically fetched with a next API call. ## OAuth 2.0 Auth ### Authentication with OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/en/guides/authentication/oauth2/). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code. ``` from box_sdk_gen import BoxOAuth, OAuthConfig auth = BoxOAuth( OAuthConfig(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") ) auth_url = auth.get_authorize_url() ``` After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirect_uri` which will contain an auth code. This auth code can then be used along with your client ID and client secret to establish an API connection. You need to provide the auth code to the SDK to obtain an access token. Calling `auth.get_tokens_authorization_code_grant('YOUR_ACCESS_CODE')` will exchange the auth code for an access token and save it in the `BoxOAuth` token storage. The SDK will automatically refresh the token when needed. All you need to do is create a client object with the `BoxOAuth` object and start making API calls. ``` auth.retrieve_token() ``` # Refresh access token Access tokens are short-lived and need to be refreshed periodically. The SDK will automatically refresh the token when needed. If you want to manually refresh the token, you can use the following code: ``` auth.refresh_token() ``` # Revoke token Access tokens for a client can be revoked when needed. This call invalidates old token. For BoxCCGAuth and BoxJWTAuth you can still reuse the `auth` object to retrieve a new token. If you make any new call after revoking the token, a new token will be automatically retrieved. For BoxOAuth it would be necessary to manually go through the authentication process again. For BoxDeveloperTokenAuth, it is necessary to provide a DeveloperTokenConfig during initialization, containing the client ID and client secret. To revoke current client's tokens in the storage use the following code: ``` client.auth.revoke_token() ``` # Downscope token You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). A downscoped token does not include a refresh token. In such a scenario, to obtain a new downscoped token, refresh the original token and utilize the newly acquired token to obtain the downscoped token. More information about downscoping tokens can be found [here](https://developer.box.com/guides/authentication/tokens/downscope/). If you want to learn more about available scopes please go [here](https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/#scopes-for-downscoping). For example to get a new token with only `item_preview` scope, restricted to a single file, suitable for the [Content Preview UI Element](https://developer.box.com/en/guides/embed/ui-elements/preview/) you can use the following code. You can also initialize `BoxDeveloperTokenAuth` with the retrieved access token and use it to create a new Client. ``` from box_sdk_gen import BoxDeveloperTokenAuth, AccessToken, BoxClient resource = "https://api.box.com/2.0/files/123456789" downscoped_token: AccessToken = auth.downscope_token( scopes=["item_preview"], resource=resource, ) downscoped_auth = BoxDeveloperTokenAuth(token=downscoped_token.access_token) client = BoxClient(auth=downscoped_auth) ``` # Token storage ## In-memory token storage By default, the SDK stores the access token in volatile memory. When rerunning your application, the access token won't be reused from the previous run; a new token has to be obtained again. To use in-memory token storage, you don't need to do anything more than create an Auth class using AuthConfig, for example, for BoxOAuth: ``` from box_sdk_gen import BoxOAuth, OAuthConfig auth = BoxOAuth( OAuthConfig(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") ) ``` ## File token storage If you want to keep an up-to-date access token in a file, allowing it to be reused after rerunning your application, you can use the `FileTokenStorage` class. To enable storing the token in a file, you need to pass an object of type `FileTokenStorage` to the AuthConfig class. For example, for BoxOAuth: ``` from box_sdk_gen import BoxOAuth, OAuthConfig, FileTokenStorage auth = BoxOAuth( OAuthConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", token_storage=FileTokenStorage(), ) ) ``` ## File with in-memory token storage If you want to keep an up-to-date access token in a file and also maintain a valid access token in in-memory cache, allowing you to reuse the token after rerunning your application while maintaining fast access times to the token, you can use the `FileWithInMemoryCacheTokenStorage` class. To enable storing the token in a file, you need to pass an object of type `FileWithInMemoryCacheTokenStorage` to the AuthConfig class. For example, for BoxOAuth: ``` from box_sdk_gen import BoxOAuth, OAuthConfig, FileWithInMemoryCacheTokenStorage auth = BoxOAuth( OAuthConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", token_storage=FileWithInMemoryCacheTokenStorage(), ) ) ``` ## Custom storage You can also provide a custom token storage class. All you need to do is create a class that inherits from `TokenStorage` and implements all of its abstract methods. Then, pass an instance of your class to the AuthConfig constructor. ``` from typing import Optional from box_sdk_gen import BoxOAuth, OAuthConfig, TokenStorage, AccessToken class MyCustomTokenStorage(TokenStorage): def store(self, token: AccessToken) -> None: # store token in your custom storage pass def get(self) -> Optional[AccessToken]: # retrieve token from your custom storage pass def clear(self) -> None: # clear token from your custom storage pass auth = BoxOAuth( OAuthConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", token_storage=MyCustomTokenStorage(), ) ) ``` --- ## Untitled *Type: page* AuthorizationManager Authorize user Request access token Refresh access token Revoke access token Authorize user Authorize a user by sending… # AuthorizationManager - [Authorize user](#authorize-user) - [Request access token](#request-access-token) - [Refresh access token](#refresh-access-token) - [Revoke access token](#revoke-access-token) ## Authorize user Authorize a user by sending them through the [Box](https://box.com) website and request their permission to act on their behalf. This is the first step when authenticating a user using OAuth 2.0. To request a user's authorization to use the Box APIs on their behalf you will need to send a user to the URL with this format. This operation is performed by calling function `authorize_user`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-authorize/). *Currently we don't have an example for calling `authorize_user` in integration tests* ### Arguments response_type `AuthorizeUserResponseType` - The type of response we'd like to receive. client_id `str` - The Client ID of the application that is requesting to authenticate the user. To get the Client ID for your application, log in to your Box developer console and click the **Edit Application** link for the application you're working with. In the OAuth 2.0 Parameters section of the configuration page, find the item labelled `client_id`. The text of that item is your application's Client ID. redirect_uri `Optional[str]` - The URI to which Box redirects the browser after the user has granted or denied the application permission. This URI match one of the redirect URIs in the configuration of your application. It must be a valid HTTPS URI and it needs to be able to handle the redirection to complete the next step in the OAuth 2.0 flow. Although this parameter is optional, it must be a part of the authorization URL if you configured multiple redirect URIs for the application in the developer console. A missing parameter causes a `redirect_uri_missing` error after the user grants application access. state `Optional[str]` - A custom string of your choice. Box will pass the same string to the redirect URL when authentication is complete. This parameter can be used to identify a user on redirect, as well as protect against hijacked sessions and other exploits. scope `Optional[str]` - A space-separated list of application scopes you'd like to authenticate the user for. This defaults to all the scopes configured for the application in its configuration page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Does not return any data, but rather should be used in the browser. ## Request access token Request an Access Token using either a client-side obtained OAuth 2.0 authorization code or a server-side JWT assertion. An Access Token is a string that enables Box to verify that a request belongs to an authorized session. In the normal order of operations you will begin by requesting authentication from the [authorize](#get-authorize) endpoint and Box will send you an authorization code. You will then send this code to this endpoint to exchange it for an Access Token. The returned Access Token can then be used to to make Box API calls. This operation is performed by calling function `request_access_token`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token/). *Currently we don't have an example for calling `request_access_token` in integration tests* ### Arguments grant_type `RequestAccessTokenGrantType` - The type of request being made, either using a client-side obtained authorization code, a refresh token, a JWT assertion, client credentials grant or another access token for the purpose of downscoping a token. client_id `Optional[str]` - The Client ID of the application requesting an access token. Used in combination with `authorization_code`, `client_credentials`, or `urn:ietf:params:oauth:grant-type:jwt-bearer` as the `grant_type`. client_secret `Optional[str]` - The client secret of the application requesting an access token. Used in combination with `authorization_code`, `client_credentials`, or `urn:ietf:params:oauth:grant-type:jwt-bearer` as the `grant_type`. code `Optional[str]` - The client-side authorization code passed to your application by Box in the browser redirect after the user has successfully granted your application permission to make API calls on their behalf. Used in combination with `authorization_code` as the `grant_type`. refresh_token `Optional[str]` - A refresh token used to get a new access token with. Used in combination with `refresh_token` as the `grant_type`. assertion `Optional[str]` - A JWT assertion for which to request a new access token. Used in combination with `urn:ietf:params:oauth:grant-type:jwt-bearer` as the `grant_type`. subject_token `Optional[str]` - The token to exchange for a downscoped token. This can be a regular access token, a JWT assertion, or an app token. Used in combination with `urn:ietf:params:oauth:grant-type:token-exchange` as the `grant_type`. subject_token_type `Optional[RequestAccessTokenSubjectTokenType]` - The type of `subject_token` passed in. Used in combination with `urn:ietf:params:oauth:grant-type:token-exchange` as the `grant_type`. actor_token `Optional[str]` - The token used to create an annotator token. This is a JWT assertion. Used in combination with `urn:ietf:params:oauth:grant-type:token-exchange` as the `grant_type`. actor_token_type `Optional[RequestAccessTokenActorTokenType]` - The type of `actor_token` passed in. Used in combination with `urn:ietf:params:oauth:grant-type:token-exchange` as the `grant_type`. scope `Optional[str]` - The space-delimited list of scopes that you want apply to the new access token. The `subject_token` will need to have all of these scopes or the call will error with **401 Unauthorized**.. resource `Optional[str]` - Full URL for the file that the token should be generated for. box_subject_type `Optional[RequestAccessTokenBoxSubjectType]` - Used in combination with `client_credentials` as the `grant_type`. box_subject_id `Optional[str]` - Used in combination with `client_credentials` as the `grant_type`. Value is determined by `box_subject_type`. If `user` use user ID and if `enterprise` use enterprise ID. box_shared_link `Optional[str]` - Full URL of the shared link on the file or folder that the token should be generated for. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Refresh access token Refresh an Access Token using its client ID, secret, and refresh token. This operation is performed by calling function `refresh_access_token`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token--refresh/). *Currently we don't have an example for calling `refresh_access_token` in integration tests* ### Arguments grant_type `RefreshAccessTokenGrantType` - The type of request being made, in this case a refresh request. client_id `str` - The client ID of the application requesting to refresh the token. client_secret `str` - The client secret of the application requesting to refresh the token. refresh_token `str` - The refresh token to refresh. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Revoke access token Revoke an active Access Token, effectively logging a user out that has been previously authenticated. This operation is performed by calling function `revoke_access_token`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-revoke/). *Currently we don't have an example for calling `revoke_access_token` in integration tests* ### Arguments client_id `Optional[str]` - The Client ID of the application requesting to revoke the access token. client_secret `Optional[str]` - The client secret of the application requesting to revoke an access token. token `Optional[str]` - The access token to revoke. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the token was successfully revoked. --- ## Untitled *Type: page* AvatarsManager Get user avatar Add or update user avatar Delete user avatar Get user avatar Retrieves an image of a the user's avatar. This… # AvatarsManager - [Get user avatar](#get-user-avatar) - [Add or update user avatar](#add-or-update-user-avatar) - [Delete user avatar](#delete-user-avatar) ## Get user avatar Retrieves an image of a the user's avatar. This operation is performed by calling function `get_user_avatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-avatar/). ``` client.avatars.get_user_avatar(user.id) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ByteStream`. When an avatar can be found for the user the image data will be returned in the body of the response. ## Add or update user avatar Adds or updates a user avatar. This operation is performed by calling function `create_user_avatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-avatar/). ``` client.avatars.create_user_avatar( user.id, decode_base_64_byte_stream( "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg==" ), pic_file_name="avatar.png", pic_content_type="image/png", ) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" pic `ByteStream` - The image file to be uploaded to Box. Accepted file extensions are `.jpg` or `.png`. The maximum file size is 1MB. pic_file_name `Optional[str]` pic_content_type `Optional[str]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UserAvatar`. `ok`: Returns the `pic_urls` object with URLs to existing user avatars that were updated.`created`: Returns the `pic_urls` object with URLS to user avatars uploaded to Box with the request. ## Delete user avatar Removes an existing user avatar. You cannot reverse this operation. This operation is performed by calling function `delete_user_avatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-avatar/). ``` client.avatars.delete_user_avatar(user.id) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. `no_content`: Removes the avatar and returns an empty response. --- ## Untitled *Type: page* ClassificationsManager List all classifications Add classification Update classification Add initial classifications List all… # ClassificationsManager - [List all classifications](#list-all-classifications) - [Add classification](#add-classification) - [Update classification](#update-classification) - [Add initial classifications](#add-initial-classifications) ## List all classifications Retrieves the classification metadata template and lists all the classifications available to this enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `get_classification_template`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema/). ``` client.classifications.get_classification_template() ``` ### Arguments extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ClassificationTemplate`. Returns the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification Adds one or more new classifications to the list of classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `add_classification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--add/). ``` client.classifications.add_classification( [ AddClassificationRequestBody( data=AddClassificationRequestBodyDataField( key=get_uuid(), static_config=AddClassificationRequestBodyDataStaticConfigField( classification=AddClassificationRequestBodyDataStaticConfigClassificationField( color_id=4, classification_definition="Other description" ) ), ) ) ] ) ``` ### Arguments request_body `List[AddClassificationRequestBody]` - Request body of addClassification method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Update classification Updates the labels and descriptions of one or more classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `update_classification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--update/). ``` client.classifications.update_classification( [ UpdateClassificationRequestBody( enum_option_key=classification.key, data=UpdateClassificationRequestBodyDataField( key=updated_classification_name, static_config=UpdateClassificationRequestBodyDataStaticConfigField( classification=UpdateClassificationRequestBodyDataStaticConfigClassificationField( color_id=2, classification_definition=updated_classification_description, ) ), ), ) ] ) ``` ### Arguments request_body `List[UpdateClassificationRequestBody]` - Request body of updateClassification method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add initial classifications When an enterprise does not yet have any classifications, this API call initializes the classification template with an initial set of classifications. If an enterprise already has a classification, the template will already exist and instead an API call should be made to add additional classifications. This operation is performed by calling function `create_classification_template`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema--classifications/). *Currently we don't have an example for calling `create_classification_template` in integration tests* ### Arguments scope `CreateClassificationTemplateScope` - The scope in which to create the classifications. This should be `enterprise` or `enterprise_{id}` where `id` is the unique ID of the enterprise. template_key `CreateClassificationTemplateTemplateKey` - Defines the list of metadata templates. display_name `CreateClassificationTemplateDisplayName` - The name of the template as shown in web and mobile interfaces. hidden `Optional[bool]` - Determines if the classification template is hidden or available on web and mobile devices. copy_instance_on_item_copy `Optional[bool]` - Determines if classifications are copied along when the file or folder is copied. fields `List[CreateClassificationTemplateFields]` - The classification template requires exactly one field, which holds all the valid classification values. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ClassificationTemplate`. Returns a new `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. --- ## Untitled *Type: page* ChunkedUploadsManager This is a manager for chunked uploads (allowed for files at least 20MB). Create upload session Create upload session… # ChunkedUploadsManager This is a manager for chunked uploads (allowed for files at least 20MB). - [Create upload session](#create-upload-session) - [Create upload session for existing file](#create-upload-session-for-existing-file) - [Get upload session by URL](#get-upload-session-by-url) - [Get upload session](#get-upload-session) - [Upload part of file by URL](#upload-part-of-file-by-url) - [Upload part of file](#upload-part-of-file) - [Remove upload session by URL](#remove-upload-session-by-url) - [Remove upload session](#remove-upload-session) - [List parts by URL](#list-parts-by-url) - [List parts](#list-parts) - [Commit upload session by URL](#commit-upload-session-by-url) - [Commit upload session](#commit-upload-session) - [Upload big file](#upload-big-file) ## Create upload session Creates an upload session for a new file. This operation is performed by calling function `create_file_upload_session`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions/). ``` client.chunked_uploads.create_file_upload_session( parent_folder_id, file_size, file_name ) ``` ### Arguments folder_id `str` - The ID of the folder to upload the new file to. file_size `int` - The total number of bytes of the file to be uploaded. file_name `str` - The name of new file. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Create upload session for existing file Creates an upload session for an existing file. This operation is performed by calling function `create_file_upload_session_for_existing_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-upload-sessions/). *Currently we don't have an example for calling `create_file_upload_session_for_existing_file` in integration tests* ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" file_size `int` - The total number of bytes of the file to be uploaded. file_name `Optional[str]` - The optional new name of new file. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Get upload session by URL Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `get_file_upload_session_by_url`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` client.chunked_uploads.get_file_upload_session_by_url(status_url) ``` ### Arguments url `str` - URL of getFileUploadSessionById method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Get upload session Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `get_file_upload_session_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` client.chunked_uploads.get_file_upload_session_by_id(upload_session_id) ``` ### Arguments upload_session_id `str` - The ID of the upload session. Example: "D5E3F7A" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Upload part of file by URL Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `upload_file_part_by_url`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` client.chunked_uploads.upload_file_part_by_url( acc.upload_part_url, generate_byte_stream_from_buffer(chunk_buffer), digest, content_range, ) ``` ### Arguments url `str` - URL of uploadFilePart method request_body `ByteStream` - Request body of uploadFilePart method digest `str` - The [RFC3230][1] message digest of the chunk uploaded. Only SHA1 is supported. The SHA1 digest must be base64 encoded. The format of this header is as `sha=BASE64_ENCODED_DIGEST`. To get the value for the `SHA` digest, use the openSSL command to encode the file part: `openssl sha1 -binary <FILE_PART_NAME> | base64`. [1]: [https://tools.ietf.org/html/rfc3230](https://tools.ietf.org/html/rfc3230) content_range `str` - The byte range of the chunk. Must not overlap with the range of a part already uploaded this session. Each part’s size must be exactly equal in size to the part size specified in the upload session that you created. One exception is the last part of the file, as this can be smaller. When providing the value for `content-range`, remember that: _ The lower bound of each part's byte range must be a multiple of the part size. _ The higher bound must be a multiple of the part size - 1. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Upload part of file Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `upload_file_part`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` client.chunked_uploads.upload_file_part( acc.upload_session_id, generate_byte_stream_from_buffer(chunk_buffer), digest, content_range, ) ``` ### Arguments upload_session_id `str` - The ID of the upload session. Example: "D5E3F7A" request_body `ByteStream` - Request body of uploadFilePart method digest `str` - The [RFC3230][1] message digest of the chunk uploaded. Only SHA1 is supported. The SHA1 digest must be base64 encoded. The format of this header is as `sha=BASE64_ENCODED_DIGEST`. To get the value for the `SHA` digest, use the openSSL command to encode the file part: `openssl sha1 -binary <FILE_PART_NAME> | base64`. [1]: [https://tools.ietf.org/html/rfc3230](https://tools.ietf.org/html/rfc3230) content_range `str` - The byte range of the chunk. Must not overlap with the range of a part already uploaded this session. Each part’s size must be exactly equal in size to the part size specified in the upload session that you created. One exception is the last part of the file, as this can be smaller. When providing the value for `content-range`, remember that: _ The lower bound of each part's byte range must be a multiple of the part size. _ The higher bound must be a multiple of the part size - 1. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Remove upload session by URL Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `delete_file_upload_session_by_url`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` client.chunked_uploads.delete_file_upload_session_by_url(abort_url) ``` ### Arguments url `str` - URL of deleteFileUploadSessionById method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the session was successfully aborted. ## Remove upload session Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `delete_file_upload_session_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` client.chunked_uploads.delete_file_upload_session_by_id(upload_session_id) ``` ### Arguments upload_session_id `str` - The ID of the upload session. Example: "D5E3F7A" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the session was successfully aborted. ## List parts by URL Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `get_file_upload_session_parts_by_url`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` client.chunked_uploads.get_file_upload_session_parts_by_url(list_parts_url) ``` ### Arguments url `str` - URL of getFileUploadSessionParts method offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## List parts Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `get_file_upload_session_parts`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` client.chunked_uploads.get_file_upload_session_parts(upload_session_id) ``` ### Arguments upload_session_id `str` - The ID of the upload session. Example: "D5E3F7A" offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## Commit upload session by URL Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `create_file_upload_session_commit_by_url`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` client.chunked_uploads.create_file_upload_session_commit_by_url( commit_url, parts, digest ) ``` ### Arguments url `str` - URL of createFileUploadSessionCommit method parts `List[UploadPart]` - The list details for the uploaded parts. digest `str` - The [RFC3230][1] message digest of the whole file. Only SHA1 is supported. The SHA1 digest must be Base64 encoded. The format of this header is as `sha=BASE64_ENCODED_DIGEST`. [1]: [https://tools.ietf.org/html/rfc3230](https://tools.ietf.org/html/rfc3230) if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. if_none_match `Optional[str]` - Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Optional[Files]`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Commit upload session Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `create_file_upload_session_commit`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` client.chunked_uploads.create_file_upload_session_commit( upload_session_id, parts, digest ) ``` ### Arguments upload_session_id `str` - The ID of the upload session. Example: "D5E3F7A" parts `List[UploadPart]` - The list details for the uploaded parts. digest `str` - The [RFC3230][1] message digest of the whole file. Only SHA1 is supported. The SHA1 digest must be Base64 encoded. The format of this header is as `sha=BASE64_ENCODED_DIGEST`. [1]: [https://tools.ietf.org/html/rfc3230](https://tools.ietf.org/html/rfc3230) if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. if_none_match `Optional[str]` - Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Optional[Files]`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Upload big file Starts the process of chunk uploading a big file. Should return a File object representing uploaded file. This operation is performed by calling function `upload_big_file`. ``` client.chunked_uploads.upload_big_file( file_byte_stream, file_name, file_size, parent_folder_id ) ``` ### Arguments file `ByteStream` - The stream of the file to upload. file_name `str` - The name of the file, which will be used for storage in Box. file_size `int` - The total size of the file for the chunked upload in bytes. parent_folder_id `str` - The ID of the folder where the file should be uploaded. ### Returns This function returns a value of type `FileFull`. --- ## Untitled *Type: page* CollaborationAllowlistEntriesManager List allowed collaboration domains Add domain to list of allowed collaboration domains Get allowed… # CollaborationAllowlistEntriesManager - [List allowed collaboration domains](#list-allowed-collaboration-domains) - [Add domain to list of allowed collaboration domains](#add-domain-to-list-of-allowed-collaboration-domains) - [Get allowed collaboration domain](#get-allowed-collaboration-domain) - [Remove domain from list of allowed collaboration domains](#remove-domain-from-list-of-allowed-collaboration-domains) ## List allowed collaboration domains Returns the list domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `get_collaboration_whitelist_entries`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries/). ``` client.collaboration_allowlist_entries.get_collaboration_whitelist_entries() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CollaborationAllowlistEntries`. Returns a collection of domains that are allowed for collaboration. ## Add domain to list of allowed collaboration domains Creates a new entry in the list of allowed domains to allow collaboration for. This operation is performed by calling function `create_collaboration_whitelist_entry`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-entries/). ``` client.collaboration_allowlist_entries.create_collaboration_whitelist_entry( domain, CreateCollaborationWhitelistEntryDirection.INBOUND ) ``` ### Arguments domain `str` - The domain to add to the list of allowed domains. direction `CreateCollaborationWhitelistEntryDirection` - The direction in which to allow collaborations. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns a new entry on the list of allowed domains. ## Get allowed collaboration domain Returns a domain that has been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `get_collaboration_whitelist_entry_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries-id/). ``` client.collaboration_allowlist_entries.get_collaboration_whitelist_entry_by_id( new_entry.id ) ``` ### Arguments collaboration_whitelist_entry_id `str` - The ID of the entry in the list. Example: "213123" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns an entry on the list of allowed domains. ## Remove domain from list of allowed collaboration domains Removes a domain from the list of domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `delete_collaboration_whitelist_entry_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-entries-id/). ``` client.collaboration_allowlist_entries.delete_collaboration_whitelist_entry_by_id( entry.id ) ``` ### Arguments collaboration_whitelist_entry_id `str` - The ID of the entry in the list. Example: "213123" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the entry was successfully deleted. --- ## Untitled *Type: page* CollaborationAllowlistExemptTargetsManager List users exempt from collaboration domain restrictions Create user exemption from collaboration… # CollaborationAllowlistExemptTargetsManager - [List users exempt from collaboration domain restrictions](#list-users-exempt-from-collaboration-domain-restrictions) - [Create user exemption from collaboration domain restrictions](#create-user-exemption-from-collaboration-domain-restrictions) - [Get user exempt from collaboration domain restrictions](#get-user-exempt-from-collaboration-domain-restrictions) - [Remove user from list of users exempt from domain restrictions](#remove-user-from-list-of-users-exempt-from-domain-restrictions) ## List users exempt from collaboration domain restrictions Returns a list of users who have been exempt from the collaboration domain restrictions. This operation is performed by calling function `get_collaboration_whitelist_exempt_targets`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets/). ``` client.collaboration_allowlist_exempt_targets.get_collaboration_whitelist_exempt_targets() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CollaborationAllowlistExemptTargets`. Returns a collection of user exemptions. ## Create user exemption from collaboration domain restrictions Exempts a user from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `create_collaboration_whitelist_exempt_target`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-exempt-targets/). ``` client.collaboration_allowlist_exempt_targets.create_collaboration_whitelist_exempt_target( CreateCollaborationWhitelistExemptTargetUser(id=user.id) ) ``` ### Arguments user `CreateCollaborationWhitelistExemptTargetUser` - The user to exempt. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns a new exemption entry. ## Get user exempt from collaboration domain restrictions Returns a users who has been exempt from the collaboration domain restrictions. This operation is performed by calling function `get_collaboration_whitelist_exempt_target_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets-id/). ``` client.collaboration_allowlist_exempt_targets.get_collaboration_whitelist_exempt_target_by_id( new_exempt_target.id ) ``` ### Arguments collaboration_whitelist_exempt_target_id `str` - The ID of the exemption to the list. Example: "984923" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns the user's exempted from the list of collaboration domains. ## Remove user from list of users exempt from domain restrictions Removes a user's exemption from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `delete_collaboration_whitelist_exempt_target_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-exempt-targets-id/). ``` client.collaboration_allowlist_exempt_targets.delete_collaboration_whitelist_exempt_target_by_id( exempt_target.id ) ``` ### Arguments collaboration_whitelist_exempt_target_id `str` - The ID of the exemption to the list. Example: "984923" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the exemption was successfully deleted. --- ## Untitled *Type: page* Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers… # Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers. [Make custom HTTP request](#make-custom-http-request) - [JSON request](#json-request) - [Multi-part request](#multi-part-request) - [Binary response](#binary-response) [Additional headers](#additional-headers) - [As-User header](#as-user-header) - [Suppress notifications](#suppress-notifications) - [Custom headers](#custom-headers) [Custom Base URLs](#custom-base-urls) [Use Proxy for API calls](#use-proxy-for-api-calls) # Make custom HTTP request You can make custom HTTP requests using the `client.make_request()` method. This method allows you to make any HTTP request to the Box API. It will automatically use authentication and network configuration settings from the client. The method accepts a `FetchOptions` object as an argument and returns a `FetchResponse` object. ## JSON request The following example demonstrates how to make a custom POST request to create a new folder in the root folder. ``` from box_sdk_gen import FetchResponse, FetchOptions response: FetchResponse = client.make_request( FetchOptions( method="POST", url="https://api.box.com/2.0/folders", data={"name": "new_folder_name", "parent": {"id": "0"}}, ) ) print("Received status code: ", response.status) print("Created folder name: ", response.data["name"]) ``` ## Multi-part request The following example demonstrates how to make a custom multipart request that uploads a file to a folder. ``` from box_sdk_gen import FetchResponse, FetchOptions, MultipartItem response: FetchResponse = client.make_request( FetchOptions( method="POST", url="https://upload.box.com/api/2.0/files/content", content_type="multipart/form-data", multipart_data=[ MultipartItem( part_name="attributes", data={"name": "new_folder_name", "parent": {"id": "0"}}, ), MultipartItem(part_name="file", file_stream=open("file.txt", "rb")), ], ) ) print("Received status code: ", response.status) ``` ## Binary response The following example demonstrates how to make a custom request that expects a binary response. It is required to specify the `response_format` parameter in the `FetchOptions` object to `ResponseFormat.BINARY`. ``` from box_sdk_gen import FetchResponse, FetchOptions, ResponseFormat file_id = "1234567" response: FetchResponse = client.make_request( FetchOptions( method="GET", url="".join(["https://api.box.com/2.0/files/", file_id, "/content"]), response_format=ResponseFormat.BINARY, ) ) print("Received status code: ", response.status) with open("file.txt", "wb") as file: file.write(response.content) ``` # Additional headers BoxClient provides a convenient methods, which allow passing additional headers, which will be included in every API call made by the client. ## As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an As-User: USER-ID header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). The following example assume that the client has been instantiated with an access token belonging to an admin-level user or Service Account with appropriate privileges to make As-User calls. Calling the `client.with_as_user_header()` method creates a new client to impersonate user with the provided ID. All calls made with the new client will be made in context of the impersonated user, leaving the original client unmodified. ``` user_client = client.with_as_user_header(user_id="1234567") ``` ## Suppress notifications If you are making administrative API calls (that is, your application has “Manage an Enterprise” scope, and the user signing in is a co-admin with the correct "Edit settings for your company" permission) then you can suppress both email and webhook notifications. This can be used, for example, for a virus-scanning tool to download copies of everyone’s files in an enterprise, without every collaborator on the file getting an email. All actions will still appear in users' updates feed and audit logs. **Note:** This functionality is only available for approved applications. Calling the `client.with_suppressed_notifications()` method creates a new client. For all calls made with the new client the notifications will be suppressed. ``` new_client = client.with_suppressed_notifications() ``` ## Custom headers You can also specify the custom set of headers, which will be included in every API call made by client. Calling the `client.with_extra_headers()` method creates a new client, leaving the original client unmodified. ``` new_client = client.with_extra_headers(extra_headers={"customHeader": "customValue"}) ``` # Custom Base URLs You can also specify the custom base URLs, which will be used for API calls made by client. Calling the `client.with_custom_base_urls()` method creates a new client, leaving the original client unmodified. ``` new_client = client.with_custom_base_urls( base_urls=BaseUrls( base_url="https://api.box.com", upload_url="https://upload.box.com/api", oauth_2_url="https://account.box.com/api/oauth2", ) ) ``` # Use Proxy for API calls In order to use a proxy for API calls, calling the `client.with_proxy(proxyConfig)` method creates a new client, leaving the original client unmodified, with the username and password being optional. **Note:** We are only supporting http/s proxies with basic authentication. NTLM and other authentication methods are not supported. ``` new_client = client.with_proxy( ProxyConfig(url="http://proxy.com", username="username", password="password") ) ``` --- ## Untitled *Type: page* CollectionsManager List all collections List collection items Get collection by ID List all collections Retrieves all collections for a… # CollectionsManager - [List all collections](#list-all-collections) - [List collection items](#list-collection-items) - [Get collection by ID](#get-collection-by-id) ## List all collections Retrieves all collections for a given user. Currently, only the `favorites` collection is supported. This operation is performed by calling function `get_collections`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections/). ``` client.collections.get_collections() ``` ### Arguments fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Collections`. Returns all collections for the given user. ## List collection items Retrieves the files and/or folders contained within this collection. This operation is performed by calling function `get_collection_items`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id-items/). ``` client.collections.get_collection_items(favourite_collection.id) ``` ### Arguments collection_id `str` - The ID of the collection. Example: "926489" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ItemsOffsetPaginated`. Returns an array of items in the collection. ## Get collection by ID Retrieves a collection by its ID. This operation is performed by calling function `get_collection_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id/). ``` client.collections.get_collection_by_id(collections.entries[0].id) ``` ### Arguments collection_id `str` - The ID of the collection. Example: "926489" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Collection`. Returns an array of items in the collection. --- ## Untitled *Type: page* CommentsManager List file comments Get comment Update comment Remove comment Create comment List file comments Retrieves a list of comments… # CommentsManager - [List file comments](#list-file-comments) - [Get comment](#get-comment) - [Update comment](#update-comment) - [Remove comment](#remove-comment) - [Create comment](#create-comment) ## List file comments Retrieves a list of comments for a file. This operation is performed by calling function `get_file_comments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-comments/). ``` client.comments.get_file_comments(file_id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. limit `Optional[int]` - The maximum number of items to return per page. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Comments`. Returns a collection of comment objects. If there are no comments on this file an empty collection will be returned. ## Get comment Retrieves the message and metadata for a specific comment, as well as information on the user who created the comment. This operation is performed by calling function `get_comment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-comments-id/). ``` client.comments.get_comment_by_id(new_comment.id) ``` ### Arguments comment_id `str` - The ID of the comment. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CommentFull`. Returns a full comment object. ## Update comment Update the message of a comment. This operation is performed by calling function `update_comment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-comments-id/). ``` client.comments.update_comment_by_id(new_reply_comment.id, message=new_message) ``` ### Arguments comment_id `str` - The ID of the comment. Example: "12345" message `Optional[str]` - The text of the comment to update. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CommentFull`. Returns the updated comment object. ## Remove comment Permanently deletes a comment. This operation is performed by calling function `delete_comment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-comments-id/). ``` client.comments.delete_comment_by_id(new_comment.id) ``` ### Arguments comment_id `str` - The ID of the comment. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the comment has been deleted. ## Create comment Adds a comment by the user to a specific file, or as a reply to an other comment. This operation is performed by calling function `create_comment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-comments/). ``` client.comments.create_comment( message, CreateCommentItem(id=file_id, type=CreateCommentItemTypeField.FILE) ) ``` ### Arguments message `str` - The text of the comment. To mention a user, use the `tagged_message` parameter instead. tagged_message `Optional[str]` - The text of the comment, including `@[user_id:name]` somewhere in the message to mention another user, which will send them an email notification, letting them know they have been mentioned. The `user_id` is the target user's ID, where the `name` can be any custom phrase. In the Box UI this name will link to the user's profile. If you are not mentioning another user, use `message` instead. item `CreateCommentItem` - The item to attach the comment to. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CommentFull`. Returns the newly created comment object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* Configuration Max retry attempts Custom retry strategy Max retry attempts The default maximum number of retries in case of failed API call… # Configuration - [Max retry attempts](#max-retry-attempts) - [Custom retry strategy](#custom-retry-strategy) ## Max retry attempts The default maximum number of retries in case of failed API call is 5. To change this number you should initialize `BoxRetryStrategy` with the new value and pass it to `NetworkSession`. ``` from box_sdk_gen import ( BoxClient, BoxDeveloperTokenAuth, NetworkSession, BoxRetryStrategy, ) auth = BoxDeveloperTokenAuth(token="DEVELOPER_TOKEN_GOES_HERE") network_session = NetworkSession(retry_strategy=BoxRetryStrategy(max_attempts=6)) client = BoxClient(auth=auth, network_session=network_session) ``` ## Custom retry strategy You can also implement your own retry strategy by subclassing `RetryStrategy` and overriding `should_retry` and `retry_after` methods. This example shows how to set custom strategy that retries on 5xx status codes and waits 1 second between retries. ``` from box_sdk_gen import ( BoxClient, BoxDeveloperTokenAuth, NetworkSession, RetryStrategy, FetchOptions, FetchResponse, ) class CustomRetryStrategy(RetryStrategy): def should_retry( self, fetch_options: FetchOptions, fetch_response: FetchResponse, attempt_number: int, ) -> bool: return fetch_response.status_code >= 500 def retry_after( self, fetch_options: FetchOptions, fetch_response: FetchResponse, attempt_number: int, ) -> float: return 1.0 auth = BoxDeveloperTokenAuth(token="DEVELOPER_TOKEN_GOES_HERE") network_session = NetworkSession(retry_strategy=CustomRetryStrategy()) client = BoxClient(auth=auth, network_session=network_session) ``` --- ## Untitled *Type: page* DevicePinnersManager Get device pin Remove device pin List enterprise device pins Get device pin Retrieves information about an individual… # DevicePinnersManager - [Get device pin](#get-device-pin) - [Remove device pin](#remove-device-pin) - [List enterprise device pins](#list-enterprise-device-pins) ## Get device pin Retrieves information about an individual device pin. This operation is performed by calling function `get_device_pinner_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-device-pinners-id/). ``` client.device_pinners.get_device_pinner_by_id(device_pinner_id) ``` ### Arguments device_pinner_id `str` - The ID of the device pin. Example: "2324234" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DevicePinner`. Returns information about a single device pin. ## Remove device pin Deletes an individual device pin. This operation is performed by calling function `delete_device_pinner_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-device-pinners-id/). ``` client.device_pinners.delete_device_pinner_by_id(device_pinner_id) ``` ### Arguments device_pinner_id `str` - The ID of the device pin. Example: "2324234" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the pin has been deleted. ## List enterprise device pins Retrieves all the device pins within an enterprise. The user must have admin privileges, and the application needs the "manage enterprise" scope to make this call. This operation is performed by calling function `get_enterprise_device_pinners`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-enterprises-id-device-pinners/). ``` client.device_pinners.get_enterprise_device_pinners(enterprise_id) ``` ### Arguments enterprise_id `str` - The ID of the enterprise. Example: "3442311" marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. direction `Optional[GetEnterpriseDevicePinnersDirection]` - The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DevicePinners`. Returns a list of device pins for a given enterprise. --- ## Untitled *Type: page* DocgenManager Get Box Doc Gen job by ID List all Box Doc Gen jobs Get Box Doc Gen jobs by batch ID Generate document using Box Doc Gen… # DocgenManager - [Get Box Doc Gen job by ID](#get-box-doc-gen-job-by-id) - [List all Box Doc Gen jobs](#list-all-box-doc-gen-jobs) - [Get Box Doc Gen jobs by batch ID](#get-box-doc-gen-jobs-by-batch-id) - [Generate document using Box Doc Gen template](#generate-document-using-box-doc-gen-template) ## Get Box Doc Gen job by ID Get details of the Box Doc Gen job. This operation is performed by calling function `get_docgen_job_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs-id/). ``` client.docgen.get_docgen_job_by_id_v2025_r0(docgen_job_item_from_list.id) ``` ### Arguments job_id `str` - Box Doc Gen job ID. Example: 123 box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenJobV2025R0`. Details of the Box Doc Gen job. ## List all Box Doc Gen jobs Lists all Box Doc Gen jobs for a user. This operation is performed by calling function `get_docgen_jobs_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs/). ``` client.docgen.get_docgen_jobs_v2025_r0(limit=500) ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenJobsFullV2025R0`. A list of Box Doc Gen jobs. ## Get Box Doc Gen jobs by batch ID Lists Box Doc Gen jobs in a batch. This operation is performed by calling function `get_docgen_batch_job_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-batch-jobs-id/). ``` client.docgen.get_docgen_batch_job_by_id_v2025_r0(docgen_batch.id) ``` ### Arguments batch_id `str` - Box Doc Gen batch ID. Example: 123 marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenJobsV2025R0`. Returns a list of Box Doc Gen jobs in a Box Doc Gen batch. ## Generate document using Box Doc Gen template Generates a document using a Box Doc Gen template. This operation is performed by calling function `create_docgen_batch_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-batches/). ``` client.docgen.create_docgen_batch_v2025_r0( FileReferenceV2025R0(id=uploaded_file.id), "api", CreateDocgenBatchV2025R0DestinationFolder(id=folder.id), "pdf", [ DocGenDocumentGenerationDataV2025R0( generated_file_name="test", user_input={"abc": "xyz"} ) ], ) ``` ### Arguments - file `FileReferenceV2025R0` - file_version `Optional[FileVersionBaseV2025R0]` input_source `str` - Source of input. The value has to be `api` for all the API-based document generation requests. destination_folder `CreateDocgenBatchV2025R0DestinationFolder` output_type `str` - Type of the output file. document_generation_data `List[DocGenDocumentGenerationDataV2025R0]` box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenBatchBaseV2025R0`. The created Batch ID. --- ## Untitled *Type: page* DocgenTemplateManager Create Box Doc Gen template List Box Doc Gen templates Delete Box Doc Gen template Get Box Doc Gen template by ID List… # DocgenTemplateManager - [Create Box Doc Gen template](#create-box-doc-gen-template) - [List Box Doc Gen templates](#list-box-doc-gen-templates) - [Delete Box Doc Gen template](#delete-box-doc-gen-template) - [Get Box Doc Gen template by ID](#get-box-doc-gen-template-by-id) - [List all Box Doc Gen template tags in template](#list-all-box-doc-gen-template-tags-in-template) - [Get list of all Box Doc Gen jobs for template](#get-list-of-all-box-doc-gen-jobs-for-template) ## Create Box Doc Gen template Marks a file as a Box Doc Gen template. This operation is performed by calling function `create_docgen_template_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-templates/). ``` client.docgen_template.create_docgen_template_v2025_r0(FileReferenceV2025R0(id=file.id)) ``` ### Arguments - file `FileReferenceV2025R0` box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenTemplateBaseV2025R0`. The file which has now been marked as a Box Doc Gen template. ## List Box Doc Gen templates Lists Box Doc Gen templates on which the user is a collaborator. This operation is performed by calling function `get_docgen_templates_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates/). ``` client.docgen_template.get_docgen_templates_v2025_r0() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenTemplatesV2025R0`. Returns a collection of templates. ## Delete Box Doc Gen template Unmarks file as Box Doc Gen template. This operation is performed by calling function `delete_docgen_template_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-docgen-templates-id/). ``` client.docgen_template.delete_docgen_template_by_id_v2025_r0( created_docgen_template.file.id ) ``` ### Arguments template_id `str` - ID of the file which will no longer be marked as a Box Doc Gen template. Example: "123" box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when a file is no longer marked as a Box Doc Gen template. ## Get Box Doc Gen template by ID Lists details of a specific Box Doc Gen template. This operation is performed by calling function `get_docgen_template_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id/). ``` client.docgen_template.get_docgen_template_by_id_v2025_r0( created_docgen_template.file.id ) ``` ### Arguments template_id `str` - The ID of a Box Doc Gen template. Example: 123 box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenTemplateV2025R0`. Returns a template. ## List all Box Doc Gen template tags in template Lists all tags in a Box Doc Gen template. This operation is performed by calling function `get_docgen_template_tags_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id-tags/). ``` client.docgen_template.get_docgen_template_tags_v2025_r0( fetched_docgen_template.file.id ) ``` ### Arguments template_id `str` - ID of template. Example: 123 template_version_id `Optional[str]` - Id of template version. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenTagsV2025R0`. A list of document generation template tags.Processing tags for the file. ## Get list of all Box Doc Gen jobs for template Lists the users jobs which use this template. This operation is performed by calling function `get_docgen_template_job_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-template-jobs-id/). ``` client.docgen_template.get_docgen_template_job_by_id_v2025_r0( fetched_docgen_template.file.id ) ``` ### Arguments template_id `str` - Id of template to fetch jobs for. Example: 123 marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `DocGenJobsV2025R0`. A single Box Doc Gen template. --- ## Untitled *Type: page* EventsManager Get events long poll endpoint List user and enterprise events Get events long poll endpoint Returns a list of real-time… # EventsManager - [Get events long poll endpoint](#get-events-long-poll-endpoint) - [List user and enterprise events](#list-user-and-enterprise-events) ## Get events long poll endpoint Returns a list of real-time servers that can be used for long-polling updates to the [event stream](#get-events). Long polling is the concept where a HTTP request is kept open until the server sends a response, then repeating the process over and over to receive updated responses. Long polling the event stream can only be used for user events, not for enterprise events. To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next, make a long poll request to any of the provided URLs. When an event occurs in monitored account a response with the value `new_change` will be sent. The response contains no other details as it only serves as a prompt to take further action such as sending a request to the [events endpoint](#get-events) with the last known `stream_position`. After the server sends this response it closes the connection. You must now repeat the long poll process to begin listening for events again. If no events occur for a while and the connection times out you will receive a response with the value `reconnect`. When you receive this response you’ll make another call to this endpoint to restart the process. If you receive no events in `retry_timeout` seconds then you will need to make another request to the real-time server (one of the URLs in the response for this endpoint). This might be necessary due to network errors. Finally, if you receive a `max_retries` error when making a request to the real-time server, you should start over by making a call to this endpoint first. This operation is performed by calling function `get_events_with_long_polling`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-events/). ``` client.events.get_events_with_long_polling() ``` ### Arguments extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RealtimeServers`. Returns a paginated array of servers that can be used instead of the regular endpoints for long-polling events. ## List user and enterprise events Returns up to a year of past events for a given user or for the entire enterprise. By default this returns events for the authenticated user. To retrieve events for the entire enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events, or `admin_logs` for querying across historical events. The user making the API call will need to have admin privileges, and the application will need to have the scope `manage enterprise properties` checked. This operation is performed by calling function `get_events`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-events/). ``` client.events.get_events() ``` ### Arguments stream_type `Optional[GetEventsStreamType]` - Defines the type of events that are returned _ `all` returns everything for a user and is the default _ `changes` returns events that may cause file tree changes such as file updates or collaborations. _ `sync` is similar to `changes` but only applies to synced folders _ `admin_logs` returns all events for an entire enterprise and requires the user making the API call to have admin permissions. This stream type is for programmatically pulling from a 1 year history of events across all users within the enterprise and within a `created_after` and `created_before` time frame. The complete history of events will be returned in chronological order based on the event time, but latency will be much higher than `admin_logs_streaming`. * `admin_logs_streaming` returns all events for an entire enterprise and requires the user making the API call to have admin permissions. This stream type is for polling for recent events across all users within the enterprise. Latency will be much lower than `admin_logs`, but events will not be returned in chronological order and may contain duplicates. stream_position `Optional[str]` - The location in the event stream to start receiving events from. _ `now` will return an empty list events and the latest stream position for initialization. _ `0` or `null` will return all events. limit `Optional[int]` - Limits the number of events returned. Note: Sometimes, the events less than the limit requested can be returned even when there may be more events remaining. This is primarily done in the case where a number of events have already been retrieved and these retrieved events are returned rather than delaying for an unknown amount of time to see if there are any more results. event_type `Optional[List[GetEventsEventType]]` - A comma-separated list of events to filter by. This can only be used when requesting the events with a `stream_type` of `admin_logs` or `adming_logs_streaming`. For any other `stream_type` this value will be ignored. created_after `Optional[DateTime]` - The lower bound date and time to return events for. This can only be used when requesting the events with a `stream_type` of `admin_logs`. For any other `stream_type` this value will be ignored. created_before `Optional[DateTime]` - The upper bound date and time to return events for. This can only be used when requesting the events with a `stream_type` of `admin_logs`. For any other `stream_type` this value will be ignored. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Events`. Returns a list of event objects. Events objects are returned in pages, with each page (chunk) including a list of event objects. The response includes a `chunk_size` parameter indicating how many events were returned in this chunk, as well as the next `stream_position` that can be queried. --- ## Untitled *Type: page* EmailAliasesManager List user's email aliases Create email alias Remove email alias List user's email aliases Retrieves all email aliases… # EmailAliasesManager - [List user's email aliases](#list-users-email-aliases) - [Create email alias](#create-email-alias) - [Remove email alias](#remove-email-alias) ## List user's email aliases Retrieves all email aliases for a user. The collection does not include the primary login for the user. This operation is performed by calling function `get_user_email_aliases`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-email-aliases/). ``` client.email_aliases.get_user_email_aliases(new_user.id) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `EmailAliases`. Returns a collection of email aliases. ## Create email alias Adds a new email alias to a user account.. This operation is performed by calling function `create_user_email_alias`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-email-aliases/). ``` client.email_aliases.create_user_email_alias(new_user.id, new_alias_email) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" email `str` - The email address to add to the account as an alias. Note: The domain of the email alias needs to be registered to your enterprise. See the [domain verification guide](https://support.box.com/hc/en-us/articles/4408619650579-Domain-Verification) for steps to add a new domain. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `EmailAlias`. Returns the newly created email alias object. ## Remove email alias Removes an email alias from a user. This operation is performed by calling function `delete_user_email_alias_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-email-aliases-id/). ``` client.email_aliases.delete_user_email_alias_by_id(new_user.id, new_alias.id) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" email_alias_id `str` - The ID of the email alias. Example: "23432" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Removes the alias and returns an empty response. --- ## Untitled *Type: page* FileMetadataManager List metadata instances on file Get metadata instance on file Create metadata instance on file Update metadata instance… # FileMetadataManager - [List metadata instances on file](#list-metadata-instances-on-file) - [Get metadata instance on file](#get-metadata-instance-on-file) - [Create metadata instance on file](#create-metadata-instance-on-file) - [Update metadata instance on file](#update-metadata-instance-on-file) - [Remove metadata instance from file](#remove-metadata-instance-from-file) ## List metadata instances on file Retrieves all metadata for a given file. This operation is performed by calling function `get_file_metadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata/). ``` client.file_metadata.get_file_metadata(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Get metadata instance on file Retrieves the instance of a metadata template that has been applied to a file. This operation is performed by calling function `get_file_metadata_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-id-id/). ``` client.file_metadata.get_file_metadata_by_id( file.id, GetFileMetadataByIdScope.GLOBAL, "properties" ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `GetFileMetadataByIdScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on file Applies an instance of a metadata template to a file. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. This operation is performed by calling function `create_file_metadata_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-id-id/). ``` client.file_metadata.create_file_metadata_by_id( file.id, CreateFileMetadataByIdScope.ENTERPRISE, template_key, { "name": "John", "age": 23, "birthDate": "2001-01-03T02:20:50.520Z", "countryCode": "US", "sports": ["basketball", "tennis"], }, ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `CreateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" request_body `Dict` - Request body of createFileMetadataById method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update metadata instance on file Updates a piece of metadata on a file. The metadata instance can only be updated if the template has already been applied to the file before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `update_file_metadata_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-id-id/). ``` client.file_metadata.update_file_metadata_by_id( file.id, UpdateFileMetadataByIdScope.ENTERPRISE, template_key, [ UpdateFileMetadataByIdRequestBody( op=UpdateFileMetadataByIdRequestBodyOpField.REPLACE, path="/name", value="Jack", ), UpdateFileMetadataByIdRequestBody( op=UpdateFileMetadataByIdRequestBodyOpField.REPLACE, path="/age", value=24 ), UpdateFileMetadataByIdRequestBody( op=UpdateFileMetadataByIdRequestBodyOpField.REPLACE, path="/birthDate", value="2000-01-03T02:20:50.520Z", ), UpdateFileMetadataByIdRequestBody( op=UpdateFileMetadataByIdRequestBodyOpField.REPLACE, path="/countryCode", value="CA", ), UpdateFileMetadataByIdRequestBody( op=UpdateFileMetadataByIdRequestBodyOpField.REPLACE, path="/sports", value=["football"], ), ], ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `UpdateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" request_body `List[UpdateFileMetadataByIdRequestBody]` - Request body of updateFileMetadataById method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from file Deletes a piece of file metadata. This operation is performed by calling function `delete_file_metadata_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-id-id/). ``` client.file_metadata.delete_file_metadata_by_id( file.id, DeleteFileMetadataByIdScope.ENTERPRISE, template_key ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `DeleteFileMetadataByIdScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* FileRequestsManager Get file request Update file request Delete file request Copy file request Get file request Retrieves the information… # FileRequestsManager - [Get file request](#get-file-request) - [Update file request](#update-file-request) - [Delete file request](#delete-file-request) - [Copy file request](#copy-file-request) ## Get file request Retrieves the information about a file request. This operation is performed by calling function `get_file_request_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-requests-id/). ``` client.file_requests.get_file_request_by_id(file_request_id) ``` ### Arguments file_request_id `str` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileRequest`. Returns a file request object. ## Update file request Updates a file request. This can be used to activate or deactivate a file request. This operation is performed by calling function `update_file_request_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-file-requests-id/). ``` client.file_requests.update_file_request_by_id( copied_file_request.id, title="updated title", description="updated description" ) ``` ### Arguments file_request_id `str` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" title `Optional[str]` - An optional new title for the file request. This can be used to change the title of the file request. This will default to the value on the existing file request. description `Optional[str]` - An optional new description for the file request. This can be used to change the description of the file request. This will default to the value on the existing file request. status `Optional[UpdateFileRequestByIdStatus]` - An optional new status of the file request. When the status is set to `inactive`, the file request will no longer accept new submissions, and any visitor to the file request URL will receive a `HTTP 404` status code. This will default to the value on the existing file request. is_email_required `Optional[bool]` - Whether a file request submitter is required to provide their email address. When this setting is set to true, the Box UI will show an email field on the file request form. This will default to the value on the existing file request. is_description_required `Optional[bool]` - Whether a file request submitter is required to provide a description of the files they are submitting. When this setting is set to true, the Box UI will show a description field on the file request form. This will default to the value on the existing file request. expires_at `Optional[DateTime]` - The date after which a file request will no longer accept new submissions. After this date, the `status` will automatically be set to `inactive`. This will default to the value on the existing file request. if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileRequest`. Returns the updated file request object. ## Delete file request Deletes a file request permanently. This operation is performed by calling function `delete_file_request_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-file-requests-id/). ``` client.file_requests.delete_file_request_by_id(updated_file_request.id) ``` ### Arguments file_request_id `str` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the file request has been successfully deleted. ## Copy file request Copies an existing file request that is already present on one folder, and applies it to another folder. This operation is performed by calling function `create_file_request_copy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-file-requests-id-copy/). ``` client.file_requests.create_file_request_copy( file_request_id, CreateFileRequestCopyFolder( id=file_request.folder.id, type=CreateFileRequestCopyFolderTypeField.FOLDER ), ) ``` ### Arguments file_request_id `str` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" folder `CreateFileRequestCopyFolder` - The folder to associate the new file request to. title `Optional[str]` - An optional new title for the file request. This can be used to change the title of the file request. This will default to the value on the existing file request. description `Optional[str]` - An optional new description for the file request. This can be used to change the description of the file request. This will default to the value on the existing file request. status `Optional[CreateFileRequestCopyStatus]` - An optional new status of the file request. When the status is set to `inactive`, the file request will no longer accept new submissions, and any visitor to the file request URL will receive a `HTTP 404` status code. This will default to the value on the existing file request. is_email_required `Optional[bool]` - Whether a file request submitter is required to provide their email address. When this setting is set to true, the Box UI will show an email field on the file request form. This will default to the value on the existing file request. is_description_required `Optional[bool]` - Whether a file request submitter is required to provide a description of the files they are submitting. When this setting is set to true, the Box UI will show a description field on the file request form. This will default to the value on the existing file request. expires_at `Optional[DateTime]` - The date after which a file request will no longer accept new submissions. After this date, the `status` will automatically be set to `inactive`. This will default to the value on the existing file request. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileRequest`. Returns updated file request object. --- ## Untitled *Type: page* FileVersionLegalHoldsManager Get file version legal hold List file version legal holds Get file version legal hold Retrieves information… # FileVersionLegalHoldsManager - [Get file version legal hold](#get-file-version-legal-hold) - [List file version legal holds](#list-file-version-legal-holds) ## Get file version legal hold Retrieves information about the legal hold policies assigned to a file version. This operation is performed by calling function `get_file_version_legal_hold_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds-id/). ``` client.file_version_legal_holds.get_file_version_legal_hold_by_id( file_version_legal_hold_id ) ``` ### Arguments file_version_legal_hold_id `str` - The ID of the file version legal hold. Example: "2348213" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileVersionLegalHold`. Returns the legal hold policy assignments for the file version. ## List file version legal holds Get a list of file versions on legal hold for a legal hold assignment. Due to ongoing re-architecture efforts this API might not return all file versions for this policy ID. Instead, this API will only return file versions held in the legacy architecture. Two new endpoints will available to request any file versions held in the new architecture. For file versions held in the new architecture, the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API can be used to return all past file versions available for this policy assignment, and the `GET /legal_hold_policy_assignments/:id/files_on_hold` API can be used to return any current (latest) versions of a file under legal hold. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. Once the re-architecture is completed this API will be deprecated. This operation is performed by calling function `get_file_version_legal_holds`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds/). ``` client.file_version_legal_holds.get_file_version_legal_holds(policy_id) ``` ### Arguments policy_id `str` - The ID of the legal hold policy to get the file version legal holds for. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileVersionLegalHolds`. Returns the list of file version legal holds for a specific legal hold policy. --- ## Untitled *Type: page* FileClassificationsManager Get classification on file Add classification to file Update classification on file Remove classification from… # FileClassificationsManager - [Get classification on file](#get-classification-on-file) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Remove classification from file](#remove-classification-from-file) ## Get classification on file Retrieves the classification metadata instance that has been applied to a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `get_classification_on_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.file_classifications.get_classification_on_file(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to file Adds a classification to a file by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `add_classification_to_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.file_classifications.add_classification_to_file( file.id, box_security_classification_key=classification.key ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" box_security_classification_key `Optional[str]` - The name of the classification to apply to this file. To list the available classifications in an enterprise, use the classification API to retrieve the [classification template](e://get_metadata_templates_enterprise_securityClassification-6VMVochwUWo_schema) which lists all available classification keys. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the file. ## Update classification on file Updates a classification on a file. The classification can only be updated if a classification has already been applied to the file before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `update_classification_on_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.file_classifications.update_classification_on_file( file.id, [UpdateClassificationOnFileRequestBody(value=second_classification.key)] ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" request_body `List[UpdateClassificationOnFileRequestBody]` - Request body of updateClassificationOnFile method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from file Removes any classifications from a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `delete_classification_from_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.file_classifications.delete_classification_from_file(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* DownloadsManager Download file URL Download file Download file Download file URL Get the download URL without downloading the content. This… # DownloadsManager - [Download file URL](#download-file-url) - [Download file](#download-file) - [Download file](#download-file) ## Download file URL Get the download URL without downloading the content. This operation is performed by calling function `get_download_file_url`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-content/). ``` client.downloads.get_download_file_url(uploaded_file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" version `Optional[str]` - The file version to download. access_token `Optional[str]` - An optional access token that can be used to pre-authenticate this request, which means that a download link can be shared with a browser or a third party service without them needing to know how to handle the authentication. When using this parameter, please make sure that the access token is sufficiently scoped down to only allow read access to that file and no other files or folders. range `Optional[str]` - The byte range of the content to download. The format `bytes={start_byte}-{end_byte}` can be used to specify what section of the file to download. boxapi `Optional[str]` - The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `str`. Returns the requested file if the client has the follow redirects setting enabled to automatically follow HTTP `3xx` responses as redirects. If not, the request will return `302` instead. For details, see the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. ## Download file Returns the contents of a file in binary format. This operation is performed by calling function `download_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-content/). ``` client.downloads.download_file(uploaded_file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" version `Optional[str]` - The file version to download. access_token `Optional[str]` - An optional access token that can be used to pre-authenticate this request, which means that a download link can be shared with a browser or a third party service without them needing to know how to handle the authentication. When using this parameter, please make sure that the access token is sufficiently scoped down to only allow read access to that file and no other files or folders. range `Optional[str]` - The byte range of the content to download. The format `bytes={start_byte}-{end_byte}` can be used to specify what section of the file to download. boxapi `Optional[str]` - The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Optional[ByteStream]`. Returns the requested file if the client has the follow redirects setting enabled to automatically follow HTTP `3xx` responses as redirects. If not, the request will return `302` instead. For details, see the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. ## Download file Download file to a given output stream This operation is performed by calling function `download_file_to_output_stream`. ``` client.downloads.download_file_to_output_stream(uploaded_file.id, file_output_stream) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" output_stream `OutputStream` - Download file to a given output stream version `Optional[str]` - The file version to download. access_token `Optional[str]` - An optional access token that can be used to pre-authenticate this request, which means that a download link can be shared with a browser or a third party service without them needing to know how to handle the authentication. When using this parameter, please make sure that the access token is sufficiently scoped down to only allow read access to that file and no other files or folders. range `Optional[str]` - The byte range of the content to download. The format `bytes={start_byte}-{end_byte}` can be used to specify what section of the file to download. boxapi `Optional[str]` - The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. --- ## Untitled *Type: page* FileVersionRetentionsManager List file version retentions Get retention on file List file version retentions Retrieves all file version… # FileVersionRetentionsManager - [List file version retentions](#list-file-version-retentions) - [Get retention on file](#get-retention-on-file) ## List file version retentions Retrieves all file version retentions for the given enterprise. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `get_file_version_retentions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions/). ``` client.file_version_retentions.get_file_version_retentions() ``` ### Arguments file_id `Optional[str]` - Filters results by files with this ID. file_version_id `Optional[str]` - Filters results by file versions with this ID. policy_id `Optional[str]` - Filters results by the retention policy with this ID. disposition_action `Optional[GetFileVersionRetentionsDispositionAction]` - Filters results by the retention policy with this disposition action. disposition_before `Optional[str]` - Filters results by files that will have their disposition come into effect before this date. disposition_after `Optional[str]` - Filters results by files that will have their disposition come into effect after this date. limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileVersionRetentions`. Returns a list of all file version retentions for the enterprise. ## Get retention on file Returns information about a file version retention. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `get_file_version_retention_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions-id/). ``` client.file_version_retentions.get_file_version_retention_by_id( file_version_retention.id ) ``` ### Arguments file_version_retention_id `str` - The ID of the file version retention. Example: "3424234" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileVersionRetention`. Returns a file version retention object. --- ## Untitled *Type: page* FileVersionsManager List all file versions Get file version Remove file version Restore file version Promote file version List all file… # FileVersionsManager - [List all file versions](#list-all-file-versions) - [Get file version](#get-file-version) - [Remove file version](#remove-file-version) - [Restore file version](#restore-file-version) - [Promote file version](#promote-file-version) ## List all file versions Retrieve a list of the past versions for a file. Versions are only tracked by Box users with premium accounts. To fetch the ID of the current version of a file, use the `GET /file/:id` API. This operation is performed by calling function `get_file_versions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions/). ``` client.file_versions.get_file_versions(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. limit `Optional[int]` - The maximum number of items to return per page. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileVersions`. Returns an array of past versions for this file. ## Get file version Retrieve a specific version of a file. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `get_file_version_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions-id/). ``` client.file_versions.get_file_version_by_id(file.id, file_versions.entries[0].id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" file_version_id `str` - The ID of the file version. Example: "1234" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileVersionFull`. Returns a specific version of a file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Remove file version Move a file version to the trash. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `delete_file_version_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-versions-id/). ``` client.file_versions.delete_file_version_by_id(file.id, file_version.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" file_version_id `str` - The ID of the file version. Example: "1234" if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the file has been successfully deleted. ## Restore file version Restores a specific version of a file after it was deleted. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `update_file_version_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-versions-id/). ``` client.file_versions.update_file_version_by_id( file.id, file_version.id, trashed_at=create_null() ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" file_version_id `str` - The ID of the file version. Example: "1234" trashed_at `Optional[str]` - Set this to `null` to clear the date and restore the file. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileVersionFull`. Returns a restored file version object. ## Promote file version Promote a specific version of a file. If previous versions exist, this method can be used to promote one of the older versions to the top of the version history. This creates a new copy of the old version and puts it at the top of the versions history. The file will have the exact same contents as the older version, with the the same hash digest, `etag`, and name as the original. Other properties such as comments do not get updated to their former values. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `promote_file_version`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-versions-current/). ``` client.file_versions.promote_file_version( file.id, id=file_versions.entries[0].id, type=PromoteFileVersionType.FILE_VERSION ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" id `Optional[str]` - The file version ID. type `Optional[PromoteFileVersionType]` - The type to promote. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileVersionFull`. Returns a newly created file version object. --- ## Untitled *Type: page* FileWatermarksManager Get watermark on file Apply watermark to file Remove watermark from file Get watermark on file Retrieve the watermark… # FileWatermarksManager - [Get watermark on file](#get-watermark-on-file) - [Apply watermark to file](#apply-watermark-to-file) - [Remove watermark from file](#remove-watermark-from-file) ## Get watermark on file Retrieve the watermark for a file. This operation is performed by calling function `get_file_watermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-watermark/). ``` client.file_watermarks.get_file_watermark(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this file. ## Apply watermark to file Applies or update a watermark on a file. This operation is performed by calling function `update_file_watermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-watermark/). ``` client.file_watermarks.update_file_watermark( file.id, UpdateFileWatermarkWatermark( imprint=UpdateFileWatermarkWatermarkImprintField.DEFAULT ), ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" watermark `UpdateFileWatermarkWatermark` - The watermark to imprint on the file. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this file.Returns a new watermark if no watermark existed on this file yet. ## Remove watermark from file Removes the watermark from a file. This operation is performed by calling function `delete_file_watermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-watermark/). ``` client.file_watermarks.delete_file_watermark(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Removes the watermark and returns an empty response. --- ## Untitled *Type: page* FolderClassificationsManager Get classification on folder Add classification to folder Update classification on folder Remove classification… # FolderClassificationsManager - [Get classification on folder](#get-classification-on-folder) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Get classification on folder Retrieves the classification metadata instance that has been applied to a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `get_classification_on_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.folder_classifications.get_classification_on_folder(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to folder Adds a classification to a folder by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `add_classification_to_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.folder_classifications.add_classification_to_folder( folder.id, box_security_classification_key=classification.key ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" box_security_classification_key `Optional[str]` - The name of the classification to apply to this folder. To list the available classifications in an enterprise, use the classification API to retrieve the [classification template](e://get_metadata_templates_enterprise_securityClassification-6VMVochwUWo_schema) which lists all available classification keys. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the folder. ## Update classification on folder Updates a classification on a folder. The classification can only be updated if a classification has already been applied to the folder before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `update_classification_on_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.folder_classifications.update_classification_on_folder( folder.id, [UpdateClassificationOnFolderRequestBody(value=second_classification.key)], ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" request_body `List[UpdateClassificationOnFolderRequestBody]` - Request body of updateClassificationOnFolder method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from folder Removes any classifications from a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `delete_classification_from_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.folder_classifications.delete_classification_from_folder(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* FilesManager Get file information Update file Delete file Copy file Get file thumbnail URL Get file thumbnail Get file information Retrieves… # FilesManager - [Get file information](#get-file-information) - [Update file](#update-file) - [Delete file](#delete-file) - [Copy file](#copy-file) - [Get file thumbnail URL](#get-file-thumbnail-url) - [Get file thumbnail](#get-file-thumbnail) ## Get file information Retrieves the details about a file. This operation is performed by calling function `get_file_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id/). ``` client.files.get_file_by_id( uploaded_file.id, fields=["is_externally_owned", "has_collaborations"] ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. Additionally this field can be used to query any metadata applied to the file by specifying the `metadata` field as well as the scope and key of the template to retrieve, for example `?fields=metadata.enterprise_12345.contractTemplate`. if_none_match `Optional[str]` - Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. boxapi `Optional[str]` - The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item. x_rep_hints `Optional[str]` - A header required to request specific `representations` of a file. Use this in combination with the `fields` query parameter to request a specific file representation. The general format for these representations is `X-Rep-Hints: [...]` where `[...]` is one or many hints in the format `[fileType?query]`. For example, to request a `png` representation in `32x32` as well as `64x64` pixel dimensions provide the following hints. `x-rep-hints: [jpg?dimensions=32x32][jpg?dimensions=64x64]` Additionally, a `text` representation is available for all document file types in Box using the `[extracted_text]` representation. `x-rep-hints: [extracted_text]`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update file Updates a file. This can be used to rename or move a file, create a shared link, or lock a file. This operation is performed by calling function `update_file_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id/). ``` client.files.update_file_by_id( file_to_update.id, name=updated_name, description="Updated description" ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" name `Optional[str]` - An optional different name for the file. This can be used to rename the file. File names must be unique within their parent folder. The name check is case-insensitive, so a file named `New File` cannot be created in a parent folder that already contains a folder named `new file`. description `Optional[str]` - The description for a file. This can be seen in the right-hand sidebar panel when viewing a file in the Box web app. Additionally, this index is used in the search index of the file, allowing users to find the file by the content in the description. parent `Optional[UpdateFileByIdParent]` shared_link `Optional[UpdateFileByIdSharedLink]` lock `Optional[UpdateFileByIdLock]` - Defines a lock on an item. This prevents the item from being moved, renamed, or otherwise changed by anyone other than the user who created the lock. Set this to `null` to remove the lock. disposition_at `Optional[DateTime]` - The retention expiration timestamp for the given file. This date cannot be shortened once set on a file. permissions `Optional[UpdateFileByIdPermissions]` - Defines who can download a file. collections `Optional[List[UpdateFileByIdCollections]]` - An array of collections to make this file a member of. Currently we only support the `favorites` collection. To get the ID for a collection, use the [List all collections](https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327) endpoint. Passing an empty array `[]` or `null` will remove the file from all collections. [1](https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327): e://get-collections tags `Optional[List[str]]` - The tags for this item. These tags are shown in the Box web app and mobile apps next to an item. To add or remove a tag, retrieve the item's current tags, modify them, and then update this field. There is a limit of 100 tags per item, and 10,000 unique tags per enterprise. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Delete file Deletes a file, either permanently or by moving it to the trash. The the enterprise settings determine whether the item will be permanently deleted from Box or moved to the trash. This operation is performed by calling function `delete_file_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id/). ``` client.files.delete_file_by_id(thumbnail_file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the file has been successfully deleted. ## Copy file Creates a copy of a file. This operation is performed by calling function `copy_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-copy/). ``` client.files.copy_file(file_origin.id, CopyFileParent(id="0"), name=copied_file_name) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" name `Optional[str]` - An optional new name for the copied file. There are some restrictions to the file name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), and protected names like `.` and `..` are automatically sanitized by removing the non-allowed characters. version `Optional[str]` - An optional ID of the specific file version to copy. parent `CopyFileParent` - The destination folder to copy the file to. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileFull`. Returns a new file object representing the copied file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Get file thumbnail URL Get the download URL without downloading the content. This operation is performed by calling function `get_file_thumbnail_url`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` client.files.get_file_thumbnail_url(thumbnail_file.id, GetFileThumbnailUrlExtension.PNG) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension `GetFileThumbnailUrlExtension` - The file format for the thumbnail. Example: "png" min_height `Optional[int]` - The minimum height of the thumbnail. min_width `Optional[int]` - The minimum width of the thumbnail. max_height `Optional[int]` - The maximum height of the thumbnail. max_width `Optional[int]` - The maximum width of the thumbnail. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `str`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. ## Get file thumbnail Retrieves a thumbnail, or smaller image representation, of a file. Sizes of `32x32`,`64x64`, `128x128`, and `256x256` can be returned in the `.png` format and sizes of `32x32`, `160x160`, and `320x320` can be returned in the `.jpg` format. Thumbnails can be generated for the image and video file formats listed [found on our community site](https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327). This operation is performed by calling function `get_file_thumbnail_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` client.files.get_file_thumbnail_by_id( thumbnail_file.id, GetFileThumbnailByIdExtension.PNG ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension `GetFileThumbnailByIdExtension` - The file format for the thumbnail. Example: "png" min_height `Optional[int]` - The minimum height of the thumbnail. min_width `Optional[int]` - The minimum width of the thumbnail. max_height `Optional[int]` - The maximum height of the thumbnail. max_width `Optional[int]` - The maximum width of the thumbnail. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Optional[ByteStream]`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. --- ## Untitled *Type: page* FolderLocksManager List folder locks Create folder lock Delete folder lock List folder locks Retrieves folder lock details for a given… # FolderLocksManager - [List folder locks](#list-folder-locks) - [Create folder lock](#create-folder-lock) - [Delete folder lock](#delete-folder-lock) ## List folder locks Retrieves folder lock details for a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `get_folder_locks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folder-locks/). ``` client.folder_locks.get_folder_locks(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderLocks`. Returns details for all folder locks applied to the folder, including the lock type and user that applied the lock. ## Create folder lock Creates a folder lock on a folder, preventing it from being moved and/or deleted. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `create_folder_lock`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folder-locks/). ``` client.folder_locks.create_folder_lock( CreateFolderLockFolder(id=folder.id, type="folder"), locked_operations=CreateFolderLockLockedOperations(move=True, delete=True), ) ``` ### Arguments locked_operations `Optional[CreateFolderLockLockedOperations]` - The operations to lock for the folder. If `locked_operations` is included in the request, both `move` and `delete` must also be included and both set to `true`. folder `CreateFolderLockFolder` - The folder to apply the lock to. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderLock`. Returns the instance of the folder lock that was applied to the folder, including the user that applied the lock and the operations set. ## Delete folder lock Deletes a folder lock on a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `delete_folder_lock_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folder-locks-id/). ``` client.folder_locks.delete_folder_lock_by_id(folder_lock.id) ``` ### Arguments folder_lock_id `str` - The ID of the folder lock. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the folder lock is successfully deleted. --- ## Untitled *Type: page* FolderMetadataManager List metadata instances on folder Get metadata instance on folder Create metadata instance on folder Update metadata… # FolderMetadataManager - [List metadata instances on folder](#list-metadata-instances-on-folder) - [Get metadata instance on folder](#get-metadata-instance-on-folder) - [Create metadata instance on folder](#create-metadata-instance-on-folder) - [Update metadata instance on folder](#update-metadata-instance-on-folder) - [Remove metadata instance from folder](#remove-metadata-instance-from-folder) ## List metadata instances on folder Retrieves all metadata for a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `get_folder_metadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata/). ``` client.folder_metadata.get_folder_metadata(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a folder. This API does not support pagination and will therefore always return all of the metadata associated to the folder. ## Get metadata instance on folder Retrieves the instance of a metadata template that has been applied to a folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `get_folder_metadata_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-id-id/). ``` client.folder_metadata.get_folder_metadata_by_id( folder.id, GetFolderMetadataByIdScope.GLOBAL, "properties" ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `GetFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on folder Applies an instance of a metadata template to a folder. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. To display the metadata template in the Box web app the enterprise needs to be configured to enable **Cascading Folder Level Metadata** for the user in the admin console. This operation is performed by calling function `create_folder_metadata_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-id-id/). ``` client.folder_metadata.create_folder_metadata_by_id( folder.id, CreateFolderMetadataByIdScope.ENTERPRISE, template_key, { "name": "John", "age": 23, "birthDate": "2001-01-03T02:20:50.520Z", "countryCode": "US", "sports": ["basketball", "tennis"], }, ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `CreateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" request_body `Dict` - Request body of createFolderMetadataById method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the folder, including the data that was applied to the template. ## Update metadata instance on folder Updates a piece of metadata on a folder. The metadata instance can only be updated if the template has already been applied to the folder before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `update_folder_metadata_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-id-id/). ``` client.folder_metadata.update_folder_metadata_by_id( folder.id, UpdateFolderMetadataByIdScope.ENTERPRISE, template_key, [ UpdateFolderMetadataByIdRequestBody( op=UpdateFolderMetadataByIdRequestBodyOpField.REPLACE, path="/name", value="Jack", ), UpdateFolderMetadataByIdRequestBody( op=UpdateFolderMetadataByIdRequestBodyOpField.REPLACE, path="/age", value=24 ), UpdateFolderMetadataByIdRequestBody( op=UpdateFolderMetadataByIdRequestBodyOpField.REPLACE, path="/birthDate", value="2000-01-03T02:20:50.520Z", ), UpdateFolderMetadataByIdRequestBody( op=UpdateFolderMetadataByIdRequestBodyOpField.REPLACE, path="/countryCode", value="CA", ), UpdateFolderMetadataByIdRequestBody( op=UpdateFolderMetadataByIdRequestBodyOpField.REPLACE, path="/sports", value=["football"], ), ], ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `UpdateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" request_body `List[UpdateFolderMetadataByIdRequestBody]` - Request body of updateFolderMetadataById method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from folder Deletes a piece of folder metadata. This operation is performed by calling function `delete_folder_metadata_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-id-id/). ``` client.folder_metadata.delete_folder_metadata_by_id( folder.id, DeleteFolderMetadataByIdScope.ENTERPRISE, template_key ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `DeleteFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* FolderWatermarksManager Get watermark for folder Apply watermark to folder Remove watermark from folder Get watermark for folder Retrieve… # FolderWatermarksManager - [Get watermark for folder](#get-watermark-for-folder) - [Apply watermark to folder](#apply-watermark-to-folder) - [Remove watermark from folder](#remove-watermark-from-folder) ## Get watermark for folder Retrieve the watermark for a folder. This operation is performed by calling function `get_folder_watermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-watermark/). ``` client.folder_watermarks.get_folder_watermark(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this folder. ## Apply watermark to folder Applies or update a watermark on a folder. This operation is performed by calling function `update_folder_watermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-watermark/). ``` client.folder_watermarks.update_folder_watermark( folder.id, UpdateFolderWatermarkWatermark( imprint=UpdateFolderWatermarkWatermarkImprintField.DEFAULT ), ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" watermark `UpdateFolderWatermarkWatermark` - The watermark to imprint on the folder. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this folder.Returns a new watermark if no watermark existed on this folder yet. ## Remove watermark from folder Removes the watermark from a folder. This operation is performed by calling function `delete_folder_watermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-watermark/). ``` client.folder_watermarks.delete_folder_watermark(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. An empty response will be returned when the watermark was successfully deleted. --- ## Untitled *Type: page* FoldersManager Get folder information Update folder Delete folder List items in folder Create folder Copy folder Get folder information… # FoldersManager - [Get folder information](#get-folder-information) - [Update folder](#update-folder) - [Delete folder](#delete-folder) - [List items in folder](#list-items-in-folder) - [Create folder](#create-folder) - [Copy folder](#copy-folder) ## Get folder information Retrieves details for a folder, including the first 100 entries in the folder. Passing `sort`, `direction`, `offset`, and `limit` parameters in query allows you to manage the list of returned [folder items](r://folder--full#param-item-collection). To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items) endpoint. This operation is performed by calling function `get_folder_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id/). ``` client.folders.get_folder_by_id("0") ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. Additionally this field can be used to query any metadata applied to the file by specifying the `metadata` field as well as the scope and key of the template to retrieve, for example `?fields=metadata.enterprise_12345.contractTemplate`. sort `Optional[GetFolderByIdSort]` - Defines the **second** attribute by which items are sorted. The folder type affects the way the items are sorted: _ **Standard folder**: Items are always sorted by their `type` first, with folders listed before files, and files listed before web links. _ **Root folder**: This parameter is not supported for marker-based pagination on the root folder (the folder with an `id` of `0`). * **Shared folder with parent path to the associated folder visible to the collaborator**: Items are always sorted by their `type` first, with folders listed before files, and files listed before web links. direction `Optional[GetFolderByIdDirection]` - The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. limit `Optional[int]` - The maximum number of items to return per page. if_none_match `Optional[str]` - Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. boxapi `Optional[str]` - The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns a folder, including the first 100 entries in the folder. If you used query parameters like `sort`, `direction`, `offset`, or `limit` the *folder items list* will be affected accordingly. To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items)) endpoint. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update folder Updates a folder. This can be also be used to move the folder, create shared links, update collaborations, and more. This operation is performed by calling function `update_folder_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id/). ``` client.folders.update_folder_by_id( folder_to_update.id, name=updated_name, description="Updated description" ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" name `Optional[str]` - The optional new name for this folder. The following restrictions to folder names apply: names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), names with trailing spaces, and names `.` and `..` are not allowed. Folder names must be unique within their parent folder. The name check is case-insensitive, so a folder named `New Folder` cannot be created in a parent folder that already contains a folder named `new folder`. description `Optional[str]` - The optional description of this folder. sync_state `Optional[UpdateFolderByIdSyncState]` - Specifies whether a folder should be synced to a user's device or not. This is used by Box Sync (discontinued) and is not used by Box Drive. can_non_owners_invite `Optional[bool]` - Specifies if users who are not the owner of the folder can invite new collaborators to the folder. parent `Optional[UpdateFolderByIdParent]` shared_link `Optional[UpdateFolderByIdSharedLink]` folder_upload_email `Optional[UpdateFolderByIdFolderUploadEmail]` tags `Optional[List[str]]` - The tags for this item. These tags are shown in the Box web app and mobile apps next to an item. To add or remove a tag, retrieve the item's current tags, modify them, and then update this field. There is a limit of 100 tags per item, and 10,000 unique tags per enterprise. is_collaboration_restricted_to_enterprise `Optional[bool]` - Specifies if new invites to this folder are restricted to users within the enterprise. This does not affect existing collaborations. collections `Optional[List[UpdateFolderByIdCollections]]` - An array of collections to make this folder a member of. Currently we only support the `favorites` collection. To get the ID for a collection, use the [List all collections][1] endpoint. Passing an empty array `[]` or `null` will remove the folder from all collections. [1]: e://get-collections can_non_owners_view_collaborators `Optional[bool]` - Restricts collaborators who are not the owner of this folder from viewing other collaborations on this folder. It also restricts non-owners from inviting new collaborators. When setting this field to `false`, it is required to also set `can_non_owners_invite_collaborators` to `false` if it has not already been set. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns a folder object for the updated folder Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. If the user is moving folders with a large number of items in all of their descendants, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. ## Delete folder Deletes a folder, either permanently or by moving it to the trash. This operation is performed by calling function `delete_folder_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id/). ``` client.folders.delete_folder_by_id(new_folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" recursive `Optional[bool]` - Delete a folder that is not empty by recursively deleting the folder and all of its content. if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the folder is successfully deleted or moved to the trash. ## List items in folder Retrieves a page of items in a folder. These items can be files, folders, and web links. To request more information about the folder itself, like its size, use the [Get a folder](#get-folders-id) endpoint instead. This operation is performed by calling function `get_folder_items`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-items/). ``` client.folders.get_folder_items(folder_origin.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. Additionally this field can be used to query any metadata applied to the file by specifying the `metadata` field as well as the scope and key of the template to retrieve, for example `?fields=metadata.enterprise_12345.contractTemplate`. usemarker `Optional[bool]` - Specifies whether to use marker-based pagination instead of offset-based pagination. Only one pagination method can be used at a time. By setting this value to true, the API will return a `marker` field that can be passed as a parameter to this endpoint to get the next page of the response. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. limit `Optional[int]` - The maximum number of items to return per page. sort `Optional[GetFolderItemsSort]` - Defines the **second** attribute by which items are sorted. The folder type affects the way the items are sorted: _ **Standard folder**: Items are always sorted by their `type` first, with folders listed before files, and files listed before web links. _ **Root folder**: This parameter is not supported for marker-based pagination on the root folder (the folder with an `id` of `0`). * **Shared folder with parent path to the associated folder visible to the collaborator**: Items are always sorted by their `type` first, with folders listed before files, and files listed before web links. direction `Optional[GetFolderItemsDirection]` - The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. boxapi `Optional[str]` - The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Items`. Returns a collection of files, folders, and web links contained in a folder. ## Create folder Creates a new empty folder within the specified parent folder. This operation is performed by calling function `create_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders/). ``` client.folders.create_folder(new_folder_name, CreateFolderParent(id="0")) ``` ### Arguments name `str` - The name for the new folder. The following restrictions to folder names apply: names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), names with trailing spaces, and names `.` and `..` are not allowed. Folder names must be unique within their parent folder. The name check is case-insensitive, so a folder named `New Folder` cannot be created in a parent folder that already contains a folder named `new folder`. parent `CreateFolderParent` - The parent folder to create the new folder within. folder_upload_email `Optional[CreateFolderFolderUploadEmail]` sync_state `Optional[CreateFolderSyncState]` - Specifies whether a folder should be synced to a user's device or not. This is used by Box Sync (discontinued) and is not used by Box Drive. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns a folder object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Copy folder Creates a copy of a folder within a destination folder. The original folder will not be changed. This operation is performed by calling function `copy_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-copy/). ``` client.folders.copy_folder( folder_origin.id, CopyFolderParent(id="0"), name=copied_folder_name ) ``` ### Arguments folder_id `str` - The unique identifier of the folder to copy. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder with the ID `0` can not be copied. Example: "0" name `Optional[str]` - An optional new name for the copied folder. There are some restrictions to the file name. Names containing non-printable ASCII characters, forward and backward slashes (`/`, `\`), as well as names with trailing spaces are prohibited. Additionally, the names `.` and `..` are not allowed either. parent `CopyFolderParent` - The destination folder to copy the folder to. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns a new folder object representing the copied folder. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* GroupsManager List groups for enterprise Create group Get group Update group Remove group List groups for enterprise Retrieves all of the… # GroupsManager - [List groups for enterprise](#list-groups-for-enterprise) - [Create group](#create-group) - [Get group](#get-group) - [Update group](#update-group) - [Remove group](#remove-group) ## List groups for enterprise Retrieves all of the groups for a given enterprise. The user must have admin permissions to inspect enterprise's groups. This operation is performed by calling function `get_groups`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups/). ``` client.groups.get_groups() ``` ### Arguments filter_term `Optional[str]` - Limits the results to only groups whose `name` starts with the search term. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. limit `Optional[int]` - The maximum number of items to return per page. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Groups`. Returns a collection of group objects. If there are no groups, an empty collection will be returned. ## Create group Creates a new group of users in an enterprise. Only users with admin permissions can create new groups. This operation is performed by calling function `create_group`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups/). ``` client.groups.create_group(group_name, description=group_description) ``` ### Arguments name `str` - The name of the new group to be created. This name must be unique within the enterprise. provenance `Optional[str]` - Keeps track of which external source this group is coming, for example `Active Directory`, or `Okta`. Setting this will also prevent Box admins from editing the group name and its members directly via the Box web application. This is desirable for one-way syncing of groups. external_sync_identifier `Optional[str]` - An arbitrary identifier that can be used by external group sync tools to link this Box Group to an external group. Example values of this field could be an **Active Directory Object ID** or a **Google Group ID**. We recommend you use of this field in order to avoid issues when group names are updated in either Box or external systems. description `Optional[str]` - A human readable description of the group. invitability_level `Optional[CreateGroupInvitabilityLevel]` - Specifies who can invite the group to collaborate on folders. When set to `admins_only` the enterprise admin, co-admins, and the group's admin can invite the group. When set to `admins_and_members` all the admins listed above and group members can invite the group. When set to `all_managed_users` all managed users in the enterprise can invite the group. member_viewability_level `Optional[CreateGroupMemberViewabilityLevel]` - Specifies who can see the members of the group. _ `admins_only` - the enterprise admin, co-admins, group's group admin. _ `admins_and_members` - all admins and group members. * `all_managed_users` - all managed users in the enterprise. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `GroupFull`. Returns the new group object. ## Get group Retrieves information about a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `get_group_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id/). ``` client.groups.get_group_by_id( group.id, fields=["id", "name", "description", "group_type"] ) ``` ### Arguments group_id `str` - The ID of the group. Example: "57645" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `GroupFull`. Returns the group object. ## Update group Updates a specific group. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `update_group_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-groups-id/). ``` client.groups.update_group_by_id(group.id, name=updated_group_name) ``` ### Arguments group_id `str` - The ID of the group. Example: "57645" name `Optional[str]` - The name of the new group to be created. Must be unique within the enterprise. provenance `Optional[str]` - Keeps track of which external source this group is coming, for example `Active Directory`, or `Okta`. Setting this will also prevent Box admins from editing the group name and its members directly via the Box web application. This is desirable for one-way syncing of groups. external_sync_identifier `Optional[str]` - An arbitrary identifier that can be used by external group sync tools to link this Box Group to an external group. Example values of this field could be an **Active Directory Object ID** or a **Google Group ID**. We recommend you use of this field in order to avoid issues when group names are updated in either Box or external systems. description `Optional[str]` - A human readable description of the group. invitability_level `Optional[UpdateGroupByIdInvitabilityLevel]` - Specifies who can invite the group to collaborate on folders. When set to `admins_only` the enterprise admin, co-admins, and the group's admin can invite the group. When set to `admins_and_members` all the admins listed above and group members can invite the group. When set to `all_managed_users` all managed users in the enterprise can invite the group. member_viewability_level `Optional[UpdateGroupByIdMemberViewabilityLevel]` - Specifies who can see the members of the group. _ `admins_only` - the enterprise admin, co-admins, group's group admin. _ `admins_and_members` - all admins and group members. * `all_managed_users` - all managed users in the enterprise. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `GroupFull`. Returns the updated group object. ## Remove group Permanently deletes a group. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `delete_group_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-groups-id/). ``` client.groups.delete_group_by_id(group.id) ``` ### Arguments group_id `str` - The ID of the group. Example: "57645" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the group was successfully deleted. --- ## Untitled *Type: page* HubCollaborationsManager Get hub collaborations Create hub collaboration Get hub collaboration by collaboration ID Update hub collaboration… # HubCollaborationsManager - [Get hub collaborations](#get-hub-collaborations) - [Create hub collaboration](#create-hub-collaboration) - [Get hub collaboration by collaboration ID](#get-hub-collaboration-by-collaboration-id) - [Update hub collaboration](#update-hub-collaboration) - [Remove hub collaboration](#remove-hub-collaboration) ## Get hub collaborations Retrieves all collaborations for a hub. This operation is performed by calling function `get_hub_collaborations_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations/). ``` client.hub_collaborations.get_hub_collaborations_v2025_r0(hub.id) ``` ### Arguments hub_id `str` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubCollaborationsV2025R0`. Retrieves the collaborations associated with the specified hub. ## Create hub collaboration Adds a collaboration for a single user or a single group to a hub. Collaborations can be created using email address, user IDs, or group IDs. This operation is performed by calling function `create_hub_collaboration_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hub-collaborations/). ``` client.hub_collaborations.create_hub_collaboration_v2025_r0( CreateHubCollaborationV2025R0Hub(id=hub.id), CreateHubCollaborationV2025R0AccessibleBy(type="user", id=user.id), "viewer", ) ``` ### Arguments hub `CreateHubCollaborationV2025R0Hub` - Hubs reference. accessible_by `CreateHubCollaborationV2025R0AccessibleBy` - The user or group who gets access to the item. role `str` - The level of access granted to hub. Possible values are `editor`, `viewer`, and `co-owner`. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a new hub collaboration object. ## Get hub collaboration by collaboration ID Retrieves details for a hub collaboration by collaboration ID. This operation is performed by calling function `get_hub_collaboration_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations-id/). ``` client.hub_collaborations.get_hub_collaboration_by_id_v2025_r0(created_collaboration.id) ``` ### Arguments hub_collaboration_id `str` - The ID of the hub collaboration. Example: "1234" box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a hub collaboration object. ## Update hub collaboration Updates a hub collaboration. Can be used to change the hub role. This operation is performed by calling function `update_hub_collaboration_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hub-collaborations-id/). ``` client.hub_collaborations.update_hub_collaboration_by_id_v2025_r0( created_collaboration.id, role="editor" ) ``` ### Arguments hub_collaboration_id `str` - The ID of the hub collaboration. Example: "1234" role `Optional[str]` - The level of access granted to hub. Possible values are `editor`, `viewer`, and `co-owner`. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns an updated hub collaboration object. ## Remove hub collaboration Deletes a single hub collaboration. This operation is performed by calling function `delete_hub_collaboration_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hub-collaborations-id/). ``` client.hub_collaborations.delete_hub_collaboration_by_id_v2025_r0( created_collaboration.id ) ``` ### Arguments hub_collaboration_id `str` - The ID of the hub collaboration. Example: "1234" box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the hub collaboration was successfully deleted. --- ## Untitled *Type: page* HubsManager List all hubs Create hub List all hubs for requesting enterprise Get hub information by ID Update hub information by ID Delete… # HubsManager - [List all hubs](#list-all-hubs) - [Create hub](#create-hub) - [List all hubs for requesting enterprise](#list-all-hubs-for-requesting-enterprise) - [Get hub information by ID](#get-hub-information-by-id) - [Update hub information by ID](#update-hub-information-by-id) - [Delete hub](#delete-hub) - [Copy hub](#copy-hub) ## List all hubs Retrieves all hubs for requesting user. This operation is performed by calling function `get_hubs_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs/). ``` client.hubs.get_hubs_v2025_r0( scope="all", sort="name", direction=GetHubsV2025R0Direction.ASC ) ``` ### Arguments query `Optional[str]` - The query string to search for hubs. scope `Optional[str]` - The scope of the hubs to retrieve. Possible values include `editable`, `view_only`, and `all`. Default is `all`. sort `Optional[str]` - The field to sort results by. Possible values include `name`, `updated_at`, `last_accessed_at`, `view_count`, and `relevance`. Default is `relevance`. direction `Optional[GetHubsV2025R0Direction]` - The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Create hub Creates a new Hub. This operation is performed by calling function `create_hub_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs/). ``` client.hubs.create_hub_v2025_r0(hub_title, description=hub_description) ``` ### Arguments title `str` - Title of the Hub. It cannot be empty and should be less than 50 characters. description `Optional[str]` - Description of the Hub. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. ## List all hubs for requesting enterprise Retrieves all hubs for a given enterprise. Admins or Hub Co-admins of an enterprise with GCM scope can make this call. This operation is performed by calling function `get_enterprise_hubs_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-enterprise-hubs/). ``` client.hubs.get_enterprise_hubs_v2025_r0( sort="name", direction=GetEnterpriseHubsV2025R0Direction.ASC ) ``` ### Arguments query `Optional[str]` - The query string to search for hubs. sort `Optional[str]` - The field to sort results by. Possible values include `name`, `updated_at`, `last_accessed_at`, `view_count`, and `relevance`. Default is `relevance`. direction `Optional[GetEnterpriseHubsV2025R0Direction]` - The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Get hub information by ID Retrieves details for a hub by its ID. This operation is performed by calling function `get_hub_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs-id/). ``` client.hubs.get_hub_by_id_v2025_r0(hub_id) ``` ### Arguments hub_id `str` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubV2025R0`. Returns a hub object. ## Update hub information by ID Updates a Hub. Can be used to change title, description, or Hub settings. This operation is performed by calling function `update_hub_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hubs-id/). ``` client.hubs.update_hub_by_id_v2025_r0( hub_id, title=new_hub_title, description=new_hub_description ) ``` ### Arguments hub_id `str` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" title `Optional[str]` - Title of the Hub. It cannot be empty and should be less than 50 characters. description `Optional[str]` - Description of the Hub. is_ai_enabled `Optional[bool]` - Indicates if AI features are enabled for the Hub. is_collaboration_restricted_to_enterprise `Optional[bool]` - Indicates if collaboration is restricted to the enterprise. can_non_owners_invite `Optional[bool]` - Indicates if non-owners can invite others to the Hub. can_shared_link_be_created `Optional[bool]` - Indicates if a shared link can be created for the Hub. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubV2025R0`. Returns a Hub object. ## Delete hub Deletes a single hub. This operation is performed by calling function `delete_hub_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hubs-id/). ``` client.hubs.delete_hub_by_id_v2025_r0(hub_id) ``` ### Arguments hub_id `str` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the hub was successfully deleted. ## Copy hub Creates a copy of a Hub. The original Hub will not be modified. This operation is performed by calling function `copy_hub_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-copy/). ``` client.hubs.copy_hub_v2025_r0( created_hub.id, title=copied_hub_title, description=copied_hub_description ) ``` ### Arguments hub_id `str` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" title `Optional[str]` - Title of the Hub. It cannot be empty and should be less than 50 characters. description `Optional[str]` - Description of the Hub. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. --- ## Untitled *Type: page* HubItemsManager Get hub items Manage hub items Get hub items Retrieves all items associated with a Hub. This operation is performed by… # HubItemsManager - [Get hub items](#get-hub-items) - [Manage hub items](#manage-hub-items) ## Get hub items Retrieves all items associated with a Hub. This operation is performed by calling function `get_hub_items_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-items/). ``` client.hub_items.get_hub_items_v2025_r0(created_hub.id) ``` ### Arguments hub_id `str` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubItemsV2025R0`. Retrieves the items associated with the specified Hub. ## Manage hub items Adds and/or removes Hub items from a Hub. This operation is performed by calling function `manage_hub_items_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-manage-items/). ``` client.hub_items.manage_hub_items_v2025_r0( created_hub.id, operations=[ HubItemOperationV2025R0( action=HubItemOperationV2025R0ActionField.ADD, item=FolderReferenceV2025R0(id=folder.id), ) ], ) ``` ### Arguments hub_id `str` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" operations `Optional[List[HubItemOperationV2025R0]]` - List of operations to perform on Hub items. box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `HubItemsManageResponseV2025R0`. --- ## Untitled *Type: page* IntegrationMappingsManager List Slack integration mappings Create Slack integration mapping Update Slack integration mapping Delete Slack… # IntegrationMappingsManager - [List Slack integration mappings](#list-slack-integration-mappings) - [Create Slack integration mapping](#create-slack-integration-mapping) - [Update Slack integration mapping](#update-slack-integration-mapping) - [Delete Slack integration mapping](#delete-slack-integration-mapping) - [List Teams integration mappings](#list-teams-integration-mappings) - [Create Teams integration mapping](#create-teams-integration-mapping) - [Update Teams integration mapping](#update-teams-integration-mapping) - [Delete Teams integration mapping](#delete-teams-integration-mapping) ## List Slack integration mappings Lists [Slack integration mappings](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `get_slack_integration_mapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-slack/). ``` user_client.integration_mappings.get_slack_integration_mapping() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. partner_item_type `Optional[GetSlackIntegrationMappingPartnerItemType]` - Mapped item type, for which the mapping should be returned. partner_item_id `Optional[str]` - ID of the mapped item, for which the mapping should be returned. box_item_id `Optional[str]` - Box item ID, for which the mappings should be returned. box_item_type `Optional[GetSlackIntegrationMappingBoxItemType]` - Box item type, for which the mappings should be returned. is_manually_created `Optional[bool]` - Whether the mapping has been manually created. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `IntegrationMappings`. Returns a collection of integration mappings. ## Create Slack integration mapping Creates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) by mapping a Slack channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `create_slack_integration_mapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-slack/). ``` user_client.integration_mappings.create_slack_integration_mapping( IntegrationMappingPartnerItemSlack( id=slack_partner_item_id, slack_org_id=slack_org_id ), IntegrationMappingBoxItemSlack(id=folder.id), ) ``` ### Arguments - partner_item `IntegrationMappingPartnerItemSlack` - box_item `IntegrationMappingBoxItemSlack` - options `Optional[IntegrationMappingSlackOptions]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `IntegrationMapping`. Returns the created integration mapping. ## Update Slack integration mapping Updates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `update_slack_integration_mapping_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-slack-id/). ``` user_client.integration_mappings.update_slack_integration_mapping_by_id( slack_integration_mapping.id, box_item=IntegrationMappingBoxItemSlack(id=folder.id) ) ``` ### Arguments integration_mapping_id `str` - An ID of an integration mapping. Example: "11235432" box_item `Optional[IntegrationMappingBoxItemSlack]` options `Optional[IntegrationMappingSlackOptions]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `IntegrationMapping`. Returns the updated integration mapping object. ## Delete Slack integration mapping Deletes a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `delete_slack_integration_mapping_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-slack-id/). ``` user_client.integration_mappings.delete_slack_integration_mapping_by_id( slack_integration_mapping.id ) ``` ### Arguments integration_mapping_id `str` - An ID of an integration mapping. Example: "11235432" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Empty body in response. ## List Teams integration mappings Lists [Teams integration mappings](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `get_teams_integration_mapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-teams/). ``` user_client.integration_mappings.get_teams_integration_mapping() ``` ### Arguments partner_item_type `Optional[GetTeamsIntegrationMappingPartnerItemType]` - Mapped item type, for which the mapping should be returned. partner_item_id `Optional[str]` - ID of the mapped item, for which the mapping should be returned. box_item_id `Optional[str]` - Box item ID, for which the mappings should be returned. box_item_type `Optional[GetTeamsIntegrationMappingBoxItemType]` - Box item type, for which the mappings should be returned. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `IntegrationMappingsTeams`. Returns a collection of integration mappings. ## Create Teams integration mapping Creates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) by mapping a Teams channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `create_teams_integration_mapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-teams/). ``` user_client.integration_mappings.create_teams_integration_mapping( IntegrationMappingPartnerItemTeamsCreateRequest( type=IntegrationMappingPartnerItemTeamsCreateRequestTypeField.CHANNEL, id=partner_item_id, tenant_id=tenant_id, team_id=team_id, ), FolderReference(id=folder.id), ) ``` ### Arguments - partner_item `IntegrationMappingPartnerItemTeamsCreateRequest` - box_item `FolderReference` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the created integration mapping. ## Update Teams integration mapping Updates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `update_teams_integration_mapping_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-teams-id/). ``` user_client.integration_mappings.update_teams_integration_mapping_by_id( integration_mapping_id, box_item=FolderReference(id="1234567") ) ``` ### Arguments integration_mapping_id `str` - An ID of an integration mapping. Example: "11235432" box_item `Optional[FolderReference]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the updated integration mapping object. ## Delete Teams integration mapping Deletes a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `delete_teams_integration_mapping_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-teams-id/). ``` user_client.integration_mappings.delete_teams_integration_mapping_by_id( integration_mapping_id ) ``` ### Arguments integration_mapping_id `str` - An ID of an integration mapping. Example: "11235432" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Empty body in response. --- ## Untitled *Type: page* InvitesManager Create user invite Get user invite status Create user invite Invites an existing external user to join an enterprise. The… # InvitesManager - [Create user invite](#create-user-invite) - [Get user invite status](#get-user-invite-status) ## Create user invite Invites an existing external user to join an enterprise. The existing user can not be part of another enterprise and must already have a Box account. Once invited, the user will receive an email and are prompted to accept the invitation within the Box web application. This method requires the "Manage An Enterprise" scope enabled for the application, which can be enabled within the developer console. This operation is performed by calling function `create_invite`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-invites/). ``` client.invites.create_invite( CreateInviteEnterprise(id=current_user.enterprise.id), CreateInviteActionableBy(login=email), ) ``` ### Arguments enterprise `CreateInviteEnterprise` - The enterprise to invite the user to. actionable_by `CreateInviteActionableBy` - The user to invite. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Invite`. Returns a new invite object. ## Get user invite status Returns the status of a user invite. This operation is performed by calling function `get_invite_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-invites-id/). ``` client.invites.get_invite_by_id(invitation.id) ``` ### Arguments invite_id `str` - The ID of an invite. Example: "213723" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Invite`. Returns an invite object. --- ## Untitled *Type: page* LegalHoldPoliciesManager List all legal hold policies Create legal hold policy Get legal hold policy Update legal hold policy Remove legal… # LegalHoldPoliciesManager - [List all legal hold policies](#list-all-legal-hold-policies) - [Create legal hold policy](#create-legal-hold-policy) - [Get legal hold policy](#get-legal-hold-policy) - [Update legal hold policy](#update-legal-hold-policy) - [Remove legal hold policy](#remove-legal-hold-policy) ## List all legal hold policies Retrieves a list of legal hold policies that belong to an enterprise. This operation is performed by calling function `get_legal_hold_policies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies/). ``` client.legal_hold_policies.get_legal_hold_policies() ``` ### Arguments policy_name `Optional[str]` - Limits results to policies for which the names start with this search term. This is a case-insensitive prefix. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `LegalHoldPolicies`. Returns a list of legal hold policies. ## Create legal hold policy Create a new legal hold policy. This operation is performed by calling function `create_legal_hold_policy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policies/). ``` client.legal_hold_policies.create_legal_hold_policy( legal_hold_policy_name, description=legal_hold_description, filter_started_at=filter_started_at, filter_ended_at=filter_ended_at, is_ongoing=False, ) ``` ### Arguments policy_name `str` - The name of the policy. description `Optional[str]` - A description for the policy. filter_started_at `Optional[DateTime]` - The filter start date. When this policy is applied using a `custodian` legal hold assignments, it will only apply to file versions created or uploaded inside of the date range. Other assignment types, such as folders and files, will ignore the date filter. Required if `is_ongoing` is set to `false`. filter_ended_at `Optional[DateTime]` - The filter end date. When this policy is applied using a `custodian` legal hold assignments, it will only apply to file versions created or uploaded inside of the date range. Other assignment types, such as folders and files, will ignore the date filter. Required if `is_ongoing` is set to `false`. is_ongoing `Optional[bool]` - Whether new assignments under this policy should continue applying to files even after initialization. When this policy is applied using a legal hold assignment, it will continue applying the policy to any new file versions even after it has been applied. For example, if a legal hold assignment is placed on a user today, and that user uploads a file tomorrow, that file will get held. This will continue until the policy is retired. Required if no filter dates are set. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Get legal hold policy Retrieve a legal hold policy. This operation is performed by calling function `get_legal_hold_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies-id/). ``` client.legal_hold_policies.get_legal_hold_policy_by_id(legal_hold_policy_id) ``` ### Arguments legal_hold_policy_id `str` - The ID of the legal hold policy. Example: "324432" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a legal hold policy object. ## Update legal hold policy Update legal hold policy. This operation is performed by calling function `update_legal_hold_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-legal-hold-policies-id/). ``` client.legal_hold_policies.update_legal_hold_policy_by_id( legal_hold_policy_id, policy_name=updated_legal_hold_policy_name ) ``` ### Arguments legal_hold_policy_id `str` - The ID of the legal hold policy. Example: "324432" policy_name `Optional[str]` - The name of the policy. description `Optional[str]` - A description for the policy. release_notes `Optional[str]` - Notes around why the policy was released. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Remove legal hold policy Delete an existing legal hold policy. This is an asynchronous process. The policy will not be fully deleted yet when the response returns. This operation is performed by calling function `delete_legal_hold_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policies-id/). ``` client.legal_hold_policies.delete_legal_hold_policy_by_id(legal_hold_policy.id) ``` ### Arguments legal_hold_policy_id `str` - The ID of the legal hold policy. Example: "324432" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the policy was successfully deleted. --- ## Untitled *Type: page* MembershipsManager List user's groups List members of group Add user to group Get group membership Update group membership Remove user from… # MembershipsManager - [List user's groups](#list-users-groups) - [List members of group](#list-members-of-group) - [Add user to group](#add-user-to-group) - [Get group membership](#get-group-membership) - [Update group membership](#update-group-membership) - [Remove user from group](#remove-user-from-group) ## List user's groups Retrieves all the groups for a user. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `get_user_memberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-memberships/). ``` client.memberships.get_user_memberships(user.id) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" limit `Optional[int]` - The maximum number of items to return per page. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## List members of group Retrieves all the members for a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `get_group_memberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-memberships/). ``` client.memberships.get_group_memberships(group.id) ``` ### Arguments group_id `str` - The ID of the group. Example: "57645" limit `Optional[int]` - The maximum number of items to return per page. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## Add user to group Creates a group membership. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `create_group_membership`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-group-memberships/). ``` client.memberships.create_group_membership( CreateGroupMembershipUser(id=user.id), CreateGroupMembershipGroup(id=group.id) ) ``` ### Arguments user `CreateGroupMembershipUser` - The user to add to the group. group `CreateGroupMembershipGroup` - The group to add the user to. role `Optional[CreateGroupMembershipRole]` - The role of the user in the group. configurable_permissions `Optional[Dict[str, bool]]` - Custom configuration for the permissions an admin if a group will receive. This option has no effect on members with a role of `member`. Setting these permissions overwrites the default access levels of an admin. Specifying a value of `null` for this object will disable all configurable permissions. Specifying permissions will set them accordingly, omitted permissions will be enabled by default. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Get group membership Retrieves a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `get_group_membership_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-group-memberships-id/). ``` client.memberships.get_group_membership_by_id(group_membership.id) ``` ### Arguments group_membership_id `str` - The ID of the group membership. Example: "434534" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `GroupMembership`. Returns the group membership object. ## Update group membership Updates a user's group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `update_group_membership_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-group-memberships-id/). ``` client.memberships.update_group_membership_by_id( group_membership.id, role=UpdateGroupMembershipByIdRole.ADMIN ) ``` ### Arguments group_membership_id `str` - The ID of the group membership. Example: "434534" role `Optional[UpdateGroupMembershipByIdRole]` - The role of the user in the group. configurable_permissions `Optional[Dict[str, bool]]` - Custom configuration for the permissions an admin if a group will receive. This option has no effect on members with a role of `member`. Setting these permissions overwrites the default access levels of an admin. Specifying a value of `null` for this object will disable all configurable permissions. Specifying permissions will set them accordingly, omitted permissions will be enabled by default. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Remove user from group Deletes a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `delete_group_membership_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-group-memberships-id/). ``` client.memberships.delete_group_membership_by_id(group_membership.id) ``` ### Arguments group_membership_id `str` - The ID of the group membership. Example: "434534" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the membership was successfully deleted. --- ## Untitled *Type: page* LegalHoldPolicyAssignmentsManager List legal hold policy assignments Assign legal hold policy Get legal hold policy assignment Unassign… # LegalHoldPolicyAssignmentsManager - [List legal hold policy assignments](#list-legal-hold-policy-assignments) - [Assign legal hold policy](#assign-legal-hold-policy) - [Get legal hold policy assignment](#get-legal-hold-policy-assignment) - [Unassign legal hold policy](#unassign-legal-hold-policy) - [List files with current file versions for legal hold policy assignment](#list-files-with-current-file-versions-for-legal-hold-policy-assignment) ## List legal hold policy assignments Retrieves a list of items a legal hold policy has been assigned to. This operation is performed by calling function `get_legal_hold_policy_assignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments/). ``` client.legal_hold_policy_assignments.get_legal_hold_policy_assignments( legal_hold_policy_id ) ``` ### Arguments policy_id `str` - The ID of the legal hold policy. assign_to_type `Optional[GetLegalHoldPolicyAssignmentsAssignToType]` - Filters the results by the type of item the policy was applied to. assign_to_id `Optional[str]` - Filters the results by the ID of item the policy was applied to. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `LegalHoldPolicyAssignments`. Returns a list of legal hold policy assignments. ## Assign legal hold policy Assign a legal hold to a file, file version, folder, or user. This operation is performed by calling function `create_legal_hold_policy_assignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policy-assignments/). ``` client.legal_hold_policy_assignments.create_legal_hold_policy_assignment( legal_hold_policy_id, CreateLegalHoldPolicyAssignmentAssignTo( type=CreateLegalHoldPolicyAssignmentAssignToTypeField.FILE, id=file_id ), ) ``` ### Arguments policy_id `str` - The ID of the policy to assign. assign_to `CreateLegalHoldPolicyAssignmentAssignTo` - The item to assign the policy to. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a new legal hold policy assignment. ## Get legal hold policy assignment Retrieve a legal hold policy assignment. This operation is performed by calling function `get_legal_hold_policy_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id/). ``` client.legal_hold_policy_assignments.get_legal_hold_policy_assignment_by_id( legal_hold_policy_assignment_id ) ``` ### Arguments legal_hold_policy_assignment_id `str` - The ID of the legal hold policy assignment. Example: "753465" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a legal hold policy object. ## Unassign legal hold policy Remove a legal hold from an item. This is an asynchronous process. The policy will not be fully removed yet when the response returns. This operation is performed by calling function `delete_legal_hold_policy_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policy-assignments-id/). ``` client.legal_hold_policy_assignments.delete_legal_hold_policy_assignment_by_id( legal_hold_policy_assignment_id ) ``` ### Arguments legal_hold_policy_assignment_id `str` - The ID of the legal hold policy assignment. Example: "753465" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the assignment was successfully deleted. ## List files with current file versions for legal hold policy assignment Get a list of files with current file versions for a legal hold assignment. In some cases you may want to get previous file versions instead. In these cases, use the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API instead to return any previous versions of a file for this legal hold policy assignment. Due to ongoing re-architecture efforts this API might not return all file versions held for this policy ID. Instead, this API will only return the latest file version held in the newly developed architecture. The `GET /file_version_legal_holds` API can be used to fetch current and past versions of files held within the legacy architecture. This endpoint does not support returning any content that is on hold due to a Custodian collaborating on a Hub. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. This operation is performed by calling function `get_legal_hold_policy_assignment_file_on_hold`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id-files-on-hold/). ``` client.legal_hold_policy_assignments.get_legal_hold_policy_assignment_file_on_hold( legal_hold_policy_assignment_id ) ``` ### Arguments legal_hold_policy_assignment_id `str` - The ID of the legal hold policy assignment. Example: "753465" marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FilesOnHold`. Returns the list of current file versions held under legal hold for a specific legal hold policy assignment. --- ## Untitled *Type: page* MetadataCascadePoliciesManager List metadata cascade policies Create metadata cascade policy Get metadata cascade policy Remove metadata… # MetadataCascadePoliciesManager - [List metadata cascade policies](#list-metadata-cascade-policies) - [Create metadata cascade policy](#create-metadata-cascade-policy) - [Get metadata cascade policy](#get-metadata-cascade-policy) - [Remove metadata cascade policy](#remove-metadata-cascade-policy) - [Force-apply metadata cascade policy to folder](#force-apply-metadata-cascade-policy-to-folder) ## List metadata cascade policies Retrieves a list of all the metadata cascade policies that are applied to a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `get_metadata_cascade_policies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies/). ``` client.metadata_cascade_policies.get_metadata_cascade_policies(folder.id) ``` ### Arguments folder_id `str` - Specifies which folder to return policies for. This can not be used on the root folder with ID `0`. owner_enterprise_id `Optional[str]` - The ID of the enterprise ID for which to find metadata cascade policies. If not specified, it defaults to the current enterprise. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataCascadePolicies`. Returns a list of metadata cascade policies. ## Create metadata cascade policy Creates a new metadata cascade policy that applies a given metadata template to a given folder and automatically cascades it down to any files within that folder. In order for the policy to be applied a metadata instance must first be applied to the folder the policy is to be applied to. This operation is performed by calling function `create_metadata_cascade_policy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies/). ``` client.metadata_cascade_policies.create_metadata_cascade_policy( folder.id, CreateMetadataCascadePolicyScope.ENTERPRISE, template_key ) ``` ### Arguments folder_id `str` - The ID of the folder to apply the policy to. This folder will need to already have an instance of the targeted metadata template applied to it. scope `CreateMetadataCascadePolicyScope` - The scope of the targeted metadata template. This template will need to already have an instance applied to the targeted folder. template_key `str` - The key of the targeted metadata template. This template will need to already have an instance applied to the targeted folder. In many cases the template key is automatically derived of its display name, for example `Contract Template` would become `contractTemplate`. In some cases the creator of the template will have provided its own template key. Please [list the templates for an enterprise][list], or get all instances on a [file][file] or [folder][folder] to inspect a template's key. [list]: e://get-metadata-templates-enterprise [file]: e://get-files-id-metadata [folder]: e://get-folders-id-metadata extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a new of metadata cascade policy. ## Get metadata cascade policy Retrieve a specific metadata cascade policy assigned to a folder. This operation is performed by calling function `get_metadata_cascade_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies-id/). ``` client.metadata_cascade_policies.get_metadata_cascade_policy_by_id(cascade_policy_id) ``` ### Arguments metadata_cascade_policy_id `str` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a metadata cascade policy. ## Remove metadata cascade policy Deletes a metadata cascade policy. This operation is performed by calling function `delete_metadata_cascade_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-cascade-policies-id/). ``` client.metadata_cascade_policies.delete_metadata_cascade_policy_by_id(cascade_policy_id) ``` ### Arguments metadata_cascade_policy_id `str` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the policy is successfully deleted. ## Force-apply metadata cascade policy to folder Force the metadata on a folder with a metadata cascade policy to be applied to all of its children. This can be used after creating a new cascade policy to enforce the metadata to be cascaded down to all existing files within that folder. This operation is performed by calling function `apply_metadata_cascade_policy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies-id-apply/). ``` client.metadata_cascade_policies.apply_metadata_cascade_policy( cascade_policy_id, ApplyMetadataCascadePolicyConflictResolution.OVERWRITE ) ``` ### Arguments metadata_cascade_policy_id `str` - The ID of the cascade policy to force-apply. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" conflict_resolution `ApplyMetadataCascadePolicyConflictResolution` - Describes the desired behavior when dealing with the conflict where a metadata template already has an instance applied to a child. _ `none` will preserve the existing value on the file _ `overwrite` will force-apply the templates values over any existing values. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the API call was successful. The metadata cascade operation will be performed asynchronously. The API call will return directly, before the cascade operation is complete. There is currently no API to check for the status of this operation. --- ## Untitled *Type: page* ListCollaborationsManager List file collaborations List folder collaborations List pending collaborations List group collaborations List… # ListCollaborationsManager - [List file collaborations](#list-file-collaborations) - [List folder collaborations](#list-folder-collaborations) - [List pending collaborations](#list-pending-collaborations) - [List group collaborations](#list-group-collaborations) ## List file collaborations Retrieves a list of pending and active collaborations for a file. This returns all the users that have access to the file or have been invited to the file. This operation is performed by calling function `get_file_collaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-collaborations/). ``` client.list_collaborations.get_file_collaborations(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this file an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List folder collaborations Retrieves a list of pending and active collaborations for a folder. This returns all the users that have access to the folder or have been invited to the folder. This operation is performed by calling function `get_folder_collaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-collaborations/). ``` client.list_collaborations.get_folder_collaborations(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this folder an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List pending collaborations Retrieves all pending collaboration invites for this user. This operation is performed by calling function `get_collaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations/). ``` client.list_collaborations.get_collaborations(GetCollaborationsStatus.PENDING) ``` ### Arguments status `GetCollaborationsStatus` - The status of the collaborations to retrieve. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of pending collaboration objects. If the user has no pending collaborations, the collection will be empty. ## List group collaborations Retrieves all the collaborations for a group. The user must have admin permissions to inspect enterprise's groups. Each collaboration object has details on which files or folders the group has access to and with what role. This operation is performed by calling function `get_group_collaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-collaborations/). ``` client.list_collaborations.get_group_collaborations(group.id) ``` ### Arguments group_id `str` - The ID of the group. Example: "57645" limit `Optional[int]` - The maximum number of items to return per page. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of collaboration objects. If there are no collaborations, an empty collection will be returned. --- ## Untitled *Type: page* MetadataTemplatesManager Find metadata template by instance ID Get metadata template by name Update metadata template Remove metadata… # MetadataTemplatesManager - [Find metadata template by instance ID](#find-metadata-template-by-instance-id) - [Get metadata template by name](#get-metadata-template-by-name) - [Update metadata template](#update-metadata-template) - [Remove metadata template](#remove-metadata-template) - [Get metadata template by ID](#get-metadata-template-by-id) - [List all global metadata templates](#list-all-global-metadata-templates) - [List all metadata templates for enterprise](#list-all-metadata-templates-for-enterprise) - [Create metadata template](#create-metadata-template) ## Find metadata template by instance ID Finds a metadata template by searching for the ID of an instance of the template. This operation is performed by calling function `get_metadata_templates_by_instance_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates/). ``` client.metadata_templates.get_metadata_templates_by_instance_id( created_metadata_instance.id ) ``` ### Arguments metadata_instance_id `str` - The ID of an instance of the metadata template to find. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataTemplates`. Returns a list containing the 1 metadata template that matches the instance ID. ## Get metadata template by name Retrieves a metadata template by its `scope` and `templateKey` values. To find the `scope` and `templateKey` for a template, list all templates for an enterprise or globally, or list all templates applied to a file or folder. This operation is performed by calling function `get_metadata_template`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id-id-schema/). ``` client.metadata_templates.get_metadata_template( GetMetadataTemplateScope.ENTERPRISE, template.template_key ) ``` ### Arguments scope `GetMetadataTemplateScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template matching the `scope` and `template` name. ## Update metadata template Updates a metadata template. The metadata template can only be updated if the template already exists. The update is applied atomically. If any errors occur during the application of the operations, the metadata template will not be changed. This operation is performed by calling function `update_metadata_template`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-id-id-schema/). ``` client.metadata_templates.update_metadata_template( UpdateMetadataTemplateScope.ENTERPRISE, template_key, [ UpdateMetadataTemplateRequestBody( op=UpdateMetadataTemplateRequestBodyOpField.ADDFIELD, field_key="newfieldname", data={"type": "string", "displayName": "newFieldName"}, ) ], ) ``` ### Arguments scope `UpdateMetadataTemplateScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" request_body `List[UpdateMetadataTemplateRequestBody]` - Request body of updateMetadataTemplate method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataTemplate`. Returns the updated metadata template, with the custom template data included. ## Remove metadata template Delete a metadata template and its instances. This deletion is permanent and can not be reversed. This operation is performed by calling function `delete_metadata_template`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-templates-id-id-schema/). ``` client.metadata_templates.delete_metadata_template( DeleteMetadataTemplateScope.ENTERPRISE, template.template_key ) ``` ### Arguments scope `DeleteMetadataTemplateScope` - The scope of the metadata template. Example: "global" template_key `str` - The name of the metadata template. Example: "properties" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the metadata template is successfully deleted. ## Get metadata template by ID Retrieves a metadata template by its ID. This operation is performed by calling function `get_metadata_template_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id/). ``` client.metadata_templates.get_metadata_template_by_id(template.id) ``` ### Arguments template_id `str` - The ID of the template. Example: "f7a9891f" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template that matches the ID. ## List all global metadata templates Used to retrieve all generic, global metadata templates available to all enterprises using Box. This operation is performed by calling function `get_global_metadata_templates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-global/). ``` client.metadata_templates.get_global_metadata_templates() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates available to all enterprises and their corresponding schema. ## List all metadata templates for enterprise Used to retrieve all metadata templates created to be used specifically within the user's enterprise. This operation is performed by calling function `get_enterprise_metadata_templates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise/). ``` client.metadata_templates.get_enterprise_metadata_templates() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates within an enterprise and their corresponding schema. ## Create metadata template Creates a new metadata template that can be applied to files and folders. This operation is performed by calling function `create_metadata_template`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema/). ``` client.metadata_templates.create_metadata_template( "enterprise", template_key, template_key=template_key, fields=[ CreateMetadataTemplateFields( type=CreateMetadataTemplateFieldsTypeField.STRING, key="testName", display_name="testName", ), CreateMetadataTemplateFields( type=CreateMetadataTemplateFieldsTypeField.FLOAT, key="age", display_name="age", ), CreateMetadataTemplateFields( type=CreateMetadataTemplateFieldsTypeField.DATE, key="birthDate", display_name="birthDate", ), CreateMetadataTemplateFields( type=CreateMetadataTemplateFieldsTypeField.ENUM, key="countryCode", display_name="countryCode", options=[ CreateMetadataTemplateFieldsOptionsField(key="US"), CreateMetadataTemplateFieldsOptionsField(key="CA"), ], ), CreateMetadataTemplateFields( type=CreateMetadataTemplateFieldsTypeField.MULTISELECT, key="sports", display_name="sports", options=[ CreateMetadataTemplateFieldsOptionsField(key="basketball"), CreateMetadataTemplateFieldsOptionsField(key="football"), CreateMetadataTemplateFieldsOptionsField(key="tennis"), ], ), ], ) ``` ### Arguments scope `str` - The scope of the metadata template to create. Applications can only create templates for use within the authenticated user's enterprise. This value needs to be set to `enterprise`, as `global` scopes can not be created by applications. template_key `Optional[str]` - A unique identifier for the template. This identifier needs to be unique across the enterprise for which the metadata template is being created. When not provided, the API will create a unique `templateKey` based on the value of the `displayName`. display_name `str` - The display name of the template. hidden `Optional[bool]` - Defines if this template is visible in the Box web app UI, or if it is purely intended for usage through the API. fields `Optional[List[CreateMetadataTemplateFields]]` - An ordered list of template fields which are part of the template. Each field can be a regular text field, date field, number field, as well as a single or multi-select list. copy_instance_on_item_copy `Optional[bool]` - Whether or not to copy any metadata attached to a file or folder when it is copied. By default, metadata is not copied along with a file or folder when it is copied. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataTemplate`. The schema representing the metadata template created. --- ## Untitled *Type: page* RecentItemsManager List recently accessed items List recently accessed items Returns information about the recent items accessed by a user… # RecentItemsManager - [List recently accessed items](#list-recently-accessed-items) ## List recently accessed items Returns information about the recent items accessed by a user, either in the last 90 days or up to the last 1000 items accessed. This operation is performed by calling function `get_recent_items`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-recent-items/). ``` client.recent_items.get_recent_items() ``` ### Arguments fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RecentItems`. Returns a list recent items access by a user. --- ## Untitled *Type: page* RetentionPolicyAssignmentsManager List retention policy assignments Assign retention policy Get retention policy assignment Remove retention… # RetentionPolicyAssignmentsManager - [List retention policy assignments](#list-retention-policy-assignments) - [Assign retention policy](#assign-retention-policy) - [Get retention policy assignment](#get-retention-policy-assignment) - [Remove retention policy assignment](#remove-retention-policy-assignment) - [Get files under retention](#get-files-under-retention) ## List retention policy assignments Returns a list of all retention policy assignments associated with a specified retention policy. This operation is performed by calling function `get_retention_policy_assignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id-assignments/). ``` client.retention_policy_assignments.get_retention_policy_assignments( retention_policy.id ) ``` ### Arguments retention_policy_id `str` - The ID of the retention policy. Example: "982312" type `Optional[GetRetentionPolicyAssignmentsType]` - The type of the retention policy assignment to retrieve. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RetentionPolicyAssignments`. Returns a list of the retention policy assignments associated with the specified retention policy. ## Assign retention policy Assigns a retention policy to an item. This operation is performed by calling function `create_retention_policy_assignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policy-assignments/). ``` client.retention_policy_assignments.create_retention_policy_assignment( retention_policy.id, CreateRetentionPolicyAssignmentAssignTo( type=CreateRetentionPolicyAssignmentAssignToTypeField.FOLDER, id=folder.id ), ) ``` ### Arguments policy_id `str` - The ID of the retention policy to assign. assign_to `CreateRetentionPolicyAssignmentAssignTo` - The item to assign the policy to. filter_fields `Optional[List[CreateRetentionPolicyAssignmentFilterFields]]` - If the `assign_to` type is `metadata_template`, then optionally add the `filter_fields` parameter which will require an array of objects with a field entry and a value entry. Currently only one object of `field` and `value` is supported. start_date_field `Optional[str]` - The date the retention policy assignment begins. If the `assigned_to` type is `metadata_template`, this field can be a date field's metadata attribute key id. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns a new retention policy assignment object. ## Get retention policy assignment Retrieves a retention policy assignment. This operation is performed by calling function `get_retention_policy_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id/). ``` client.retention_policy_assignments.get_retention_policy_assignment_by_id( retention_policy_assignment.id ) ``` ### Arguments retention_policy_assignment_id `str` - The ID of the retention policy assignment. Example: "1233123" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns the retention policy assignment object. ## Remove retention policy assignment Removes a retention policy assignment applied to content. This operation is performed by calling function `delete_retention_policy_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policy-assignments-id/). ``` client.retention_policy_assignments.delete_retention_policy_assignment_by_id( retention_policy_assignment.id ) ``` ### Arguments retention_policy_assignment_id `str` - The ID of the retention policy assignment. Example: "1233123" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the policy assignment is successfully deleted. ## Get files under retention Returns a list of files under retention for a retention policy assignment. This operation is performed by calling function `get_files_under_retention_policy_assignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention/). ``` client.retention_policy_assignments.get_files_under_retention_policy_assignment( retention_policy_assignment.id ) ``` ### Arguments retention_policy_assignment_id `str` - The ID of the retention policy assignment. Example: "1233123" marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FilesUnderRetention`. Returns a list of files under retention that are associated with the specified retention policy assignment. --- ## Untitled *Type: page* RetentionPoliciesManager List retention policies Create retention policy Get retention policy Update retention policy Delete retention… # RetentionPoliciesManager - [List retention policies](#list-retention-policies) - [Create retention policy](#create-retention-policy) - [Get retention policy](#get-retention-policy) - [Update retention policy](#update-retention-policy) - [Delete retention policy](#delete-retention-policy) ## List retention policies Retrieves all of the retention policies for an enterprise. This operation is performed by calling function `get_retention_policies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies/). ``` client.retention_policies.get_retention_policies() ``` ### Arguments policy_name `Optional[str]` - Filters results by a case sensitive prefix of the name of retention policies. policy_type `Optional[GetRetentionPoliciesPolicyType]` - Filters results by the type of retention policy. created_by_user_id `Optional[str]` - Filters results by the ID of the user who created policy. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RetentionPolicies`. Returns a list retention policies in the enterprise. ## Create retention policy Creates a retention policy. This operation is performed by calling function `create_retention_policy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policies/). ``` client.retention_policies.create_retention_policy( retention_policy_name, CreateRetentionPolicyPolicyType.FINITE, CreateRetentionPolicyDispositionAction.REMOVE_RETENTION, description=retention_description, retention_length="1", retention_type=CreateRetentionPolicyRetentionType.MODIFIABLE, can_owner_extend_retention=True, are_owners_notified=True, ) ``` ### Arguments policy_name `str` - The name for the retention policy. description `Optional[str]` - The additional text description of the retention policy. policy_type `CreateRetentionPolicyPolicyType` - The type of the retention policy. A retention policy type can either be `finite`, where a specific amount of time to retain the content is known upfront, or `indefinite`, where the amount of time to retain the content is still unknown. disposition_action `CreateRetentionPolicyDispositionAction` - The disposition action of the retention policy. `permanently_delete` deletes the content retained by the policy permanently. `remove_retention` lifts retention policy from the content, allowing it to be deleted by users once the retention policy has expired. retention_length `Optional[str]` - The length of the retention policy. This value specifies the duration in days that the retention policy will be active for after being assigned to content. If the policy has a `policy_type` of `indefinite`, the `retention_length` will also be `indefinite`. retention_type `Optional[CreateRetentionPolicyRetentionType]` - Specifies the retention type: _ `modifiable`: You can modify the retention policy. For example, you can add or remove folders, shorten or lengthen the policy duration, or delete the assignment. Use this type if your retention policy is not related to any regulatory purposes. _ `non_modifiable`: You can modify the retention policy only in a limited way: add a folder, lengthen the duration, retire the policy, change the disposition action or notification settings. You cannot perform other actions, such as deleting the assignment or shortening the policy duration. Use this type to ensure compliance with regulatory retention policies. can_owner_extend_retention `Optional[bool]` - Whether the owner of a file will be allowed to extend the retention. are_owners_notified `Optional[bool]` - Whether owner and co-owners of a file are notified when the policy nears expiration. custom_notification_recipients `Optional[List[UserMini]]` - A list of users notified when the retention policy duration is about to end. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RetentionPolicy`. Returns a new retention policy object. ## Get retention policy Retrieves a retention policy. This operation is performed by calling function `get_retention_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id/). ``` client.retention_policies.get_retention_policy_by_id(retention_policy.id) ``` ### Arguments retention_policy_id `str` - The ID of the retention policy. Example: "982312" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RetentionPolicy`. Returns the retention policy object. ## Update retention policy Updates a retention policy. This operation is performed by calling function `update_retention_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-retention-policies-id/). ``` client.retention_policies.update_retention_policy_by_id( retention_policy.id, policy_name=updated_retention_policy_name ) ``` ### Arguments retention_policy_id `str` - The ID of the retention policy. Example: "982312" policy_name `Optional[str]` - The name for the retention policy. description `Optional[str]` - The additional text description of the retention policy. disposition_action `Optional[str]` - The disposition action of the retention policy. This action can be `permanently_delete`, which will cause the content retained by the policy to be permanently deleted, or `remove_retention`, which will lift the retention policy from the content, allowing it to be deleted by users, once the retention policy has expired. You can use `null` if you don't want to change `disposition_action`. retention_type `Optional[str]` - Specifies the retention type: _ `modifiable`: You can modify the retention policy. For example, you can add or remove folders, shorten or lengthen the policy duration, or delete the assignment. Use this type if your retention policy is not related to any regulatory purposes. _ `non-modifiable`: You can modify the retention policy only in a limited way: add a folder, lengthen the duration, retire the policy, change the disposition action or notification settings. You cannot perform other actions, such as deleting the assignment or shortening the policy duration. Use this type to ensure compliance with regulatory retention policies. When updating a retention policy, you can use `non-modifiable` type only. You can convert a `modifiable` policy to `non-modifiable`, but not the other way around. retention_length `Optional[str]` - The length of the retention policy. This value specifies the duration in days that the retention policy will be active for after being assigned to content. If the policy has a `policy_type` of `indefinite`, the `retention_length` will also be `indefinite`. status `Optional[str]` - Used to retire a retention policy. If not retiring a policy, do not include this parameter or set it to `null`. can_owner_extend_retention `Optional[bool]` - Determines if the owner of items under the policy can extend the retention when the original retention duration is about to end. are_owners_notified `Optional[bool]` - Determines if owners and co-owners of items under the policy are notified when the retention duration is about to end. custom_notification_recipients `Optional[List[UserBase]]` - A list of users notified when the retention duration is about to end. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `RetentionPolicy`. Returns the updated retention policy object. ## Delete retention policy Permanently deletes a retention policy. This operation is performed by calling function `delete_retention_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policies-id/). ``` client.retention_policies.delete_retention_policy_by_id(retention_policy.id) ``` ### Arguments retention_policy_id `str` - The ID of the retention policy. Example: "982312" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the policy has been deleted. --- ## Untitled *Type: page* SearchManager Query files/folders by metadata Search for content Query files/folders by metadata Create a search using SQL-like syntax to… # SearchManager - [Query files/folders by metadata](#query-files-folders-by-metadata) - [Search for content](#search-for-content) ## Query files/folders by metadata Create a search using SQL-like syntax to return items that match specific metadata. By default, this endpoint returns only the most basic info about the items for which the query matches. To get additional fields for each item, including any of the metadata, use the `fields` attribute in the query. This operation is performed by calling function `search_by_metadata_query`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-queries-execute-read/). ``` client.search.search_by_metadata_query( search_from, "0", query="name = :name AND age < :age AND birthDate >= :birthDate AND countryCode = :countryCode AND sports = :sports", query_params={ "name": "John", "age": 50, "birthDate": "2001-01-01T02:20:10.120Z", "countryCode": "US", "sports": ["basketball", "tennis"], }, ) ``` ### Arguments from_ `str` - Specifies the template used in the query. Must be in the form `scope.templateKey`. Not all templates can be used in this field, most notably the built-in, Box-provided classification templates can not be used in a query. query `Optional[str]` - The query to perform. A query is a logical expression that is very similar to a SQL `SELECT` statement. Values in the search query can be turned into parameters specified in the `query_param` arguments list to prevent having to manually insert search values into the query string. For example, a value of `:amount` would represent the `amount` value in `query_params` object. query_params `Optional[Dict]` - Set of arguments corresponding to the parameters specified in the `query`. The type of each parameter used in the `query_params` must match the type of the corresponding metadata template field. ancestor_folder_id `str` - The ID of the folder that you are restricting the query to. A value of zero will return results from all folders you have access to. A non-zero value will only return results found in the folder corresponding to the ID or in any of its subfolders. order_by `Optional[List[SearchByMetadataQueryOrderBy]]` - A list of template fields and directions to sort the metadata query results by. The ordering `direction` must be the same for each item in the array. limit `Optional[int]` - A value between 0 and 100 that indicates the maximum number of results to return for a single request. This only specifies a maximum boundary and will not guarantee the minimum number of results returned. marker `Optional[str]` - Marker to use for requesting the next page. fields `Optional[List[str]]` - By default, this endpoint returns only the most basic info about the items for which the query matches. This attribute can be used to specify a list of additional attributes to return for any item, including its metadata. This attribute takes a list of item fields, metadata template identifiers, or metadata template field identifiers. For example: _ `created_by` will add the details of the user who created the item to the response. _ `metadata.<scope>.<templateKey>` will return the mini-representation of the metadata instance identified by the `scope` and `templateKey`. * `metadata.<scope>.<templateKey>.<field>` will return all the mini-representation of the metadata instance identified by the `scope` and `templateKey` plus the field specified by the `field` name. Multiple fields for the same `scope` and `templateKey` can be defined. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `MetadataQueryResults`. Returns a list of files and folders that match this metadata query. ## Search for content Searches for files, folders, web links, and shared files across the users content or across the entire enterprise. This operation is performed by calling function `search_for_content`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-search/). ``` client.search.search_for_content( ancestor_folder_ids=["0"], mdfilters=[ MetadataFilter( filters=search_filters, scope=MetadataFilterScopeField.ENTERPRISE, template_key=template_key, ) ], ) ``` ### Arguments query `Optional[str]` - The string to search for. This query is matched against item names, descriptions, text content of files, and various other fields of the different item types. This parameter supports a variety of operators to further refine the results returns. _ `""` - by wrapping a query in double quotes only exact matches are returned by the API. Exact searches do not return search matches based on specific character sequences. Instead, they return matches based on phrases, that is, word sequences. For example: A search for `"Blue-Box"` may return search results including the sequence `"blue.box"`, `"Blue Box"`, and `"Blue-Box"`; any item containing the words `Blue` and `Box` consecutively, in the order specified. _ `AND` - returns items that contain both the search terms. For example, a search for `marketing AND BoxWorks` returns items that have both `marketing` and `BoxWorks` within its text in any order. It does not return a result that only has `BoxWorks` in its text. _ `OR` - returns items that contain either of the search terms. For example, a search for `marketing OR BoxWorks` returns a result that has either `marketing` or `BoxWorks` within its text. Using this operator is not necessary as we implicitly interpret multi-word queries as `OR` unless another supported boolean term is used. _ `NOT` - returns items that do not contain the search term provided. For example, a search for `marketing AND NOT BoxWorks` returns a result that has only `marketing` within its text. Results containing `BoxWorks` are omitted. We do not support lower case (that is, `and`, `or`, and `not`) or mixed case (that is, `And`, `Or`, and `Not`) operators. This field is required unless the `mdfilters` parameter is defined. scope `Optional[SearchForContentScope]` - Limits the search results to either the files that the user has access to, or to files available to the entire enterprise. The scope defaults to `user_content`, which limits the search results to content that is available to the currently authenticated user. The `enterprise_content` can be requested by an admin through our support channels. Once this scope has been enabled for a user, it will allow that use to query for content across the entire enterprise and not only the content that they have access to. file_extensions `Optional[List[str]]` - Limits the search results to any files that match any of the provided file extensions. This list is a comma-separated list of file extensions without the dots. created_at_range `Optional[List[str]]` - Limits the search results to any items created within a given date range. Date ranges are defined as comma separated RFC3339 timestamps. If the the start date is omitted (`,2014-05-17T13:35:01-07:00`) anything created before the end date will be returned. If the end date is omitted (`2014-05-15T13:35:01-07:00,`) the current date will be used as the end date instead. updated_at_range `Optional[List[str]]` - Limits the search results to any items updated within a given date range. Date ranges are defined as comma separated RFC3339 timestamps. If the start date is omitted (`,2014-05-17T13:35:01-07:00`) anything updated before the end date will be returned. If the end date is omitted (`2014-05-15T13:35:01-07:00,`) the current date will be used as the end date instead. size_range `Optional[List[int]]` - Limits the search results to any items with a size within a given file size range. This applied to files and folders. Size ranges are defined as comma separated list of a lower and upper byte size limit (inclusive). The upper and lower bound can be omitted to create open ranges. owner_user_ids `Optional[List[str]]` - Limits the search results to any items that are owned by the given list of owners, defined as a list of comma separated user IDs. The items still need to be owned or shared with the currently authenticated user for them to show up in the search results. If the user does not have access to any files owned by any of the users an empty result set will be returned. To search across an entire enterprise, we recommend using the `enterprise_content` scope parameter which can be requested with our support team. recent_updater_user_ids `Optional[List[str]]` - Limits the search results to any items that have been updated by the given list of users, defined as a list of comma separated user IDs. The items still need to be owned or shared with the currently authenticated user for them to show up in the search results. If the user does not have access to any files owned by any of the users an empty result set will be returned. This feature only searches back to the last 10 versions of an item. ancestor_folder_ids `Optional[List[str]]` - Limits the search results to items within the given list of folders, defined as a comma separated lists of folder IDs. Search results will also include items within any subfolders of those ancestor folders. The folders still need to be owned or shared with the currently authenticated user. If the folder is not accessible by this user, or it does not exist, a `HTTP 404` error code will be returned instead. To search across an entire enterprise, we recommend using the `enterprise_content` scope parameter which can be requested with our support team. content_types `Optional[List[SearchForContentContentTypes]]` - Limits the search results to any items that match the search query for a specific part of the file, for example the file description. Content types are defined as a comma separated lists of Box recognized content types. The allowed content types are as follows. _ `name` - The name of the item, as defined by its `name` field. _ `description` - The description of the item, as defined by its `description` field. _ `file_content` - The actual content of the file. _ `comments` - The content of any of the comments on a file or folder. * `tags` - Any tags that are applied to an item, as defined by its `tags` field. type `Optional[SearchForContentType]` - Limits the search results to any items of this type. This parameter only takes one value. By default the API returns items that match any of these types. _ `file` - Limits the search results to files, _ `folder` - Limits the search results to folders, * `web_link` - Limits the search results to web links, also known as bookmarks. trash_content `Optional[SearchForContentTrashContent]` - Determines if the search should look in the trash for items. By default, this API only returns search results for items not currently in the trash (`non_trashed_only`). _ `trashed_only` - Only searches for items currently in the trash _ `non_trashed_only` - Only searches for items currently not in the trash * `all_items` - Searches for both trashed and non-trashed items. mdfilters `Optional[List[MetadataFilter]]` - Limits the search results to any items for which the metadata matches the provided filter. This parameter is a list that specifies exactly **one** metadata template used to filter the search results. The parameter is required unless the `query` parameter is provided. sort `Optional[SearchForContentSort]` - Defines the order in which search results are returned. This API defaults to returning items by relevance unless this parameter is explicitly specified. _ `relevance` (default) returns the results sorted by relevance to the query search term. The relevance is based on the occurrence of the search term in the items name, description, content, and additional properties. _ `modified_at` returns the results ordered in descending order by date at which the item was last modified. direction `Optional[SearchForContentDirection]` - Defines the direction in which search results are ordered. This API defaults to returning items in descending (`DESC`) order unless this parameter is explicitly specified. When results are sorted by `relevance` the ordering is locked to returning items in descending order of relevance, and this parameter is ignored. limit `Optional[int]` - Defines the maximum number of items to return as part of a page of results. include_recent_shared_links `Optional[bool]` - Defines whether the search results should include any items that the user recently accessed through a shared link. When this parameter has been set to true, the format of the response of this API changes to return a list of [Search Results with Shared Links](r://search_results_with_shared_links). fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. deleted_user_ids `Optional[List[str]]` - Limits the search results to items that were deleted by the given list of users, defined as a list of comma separated user IDs. The `trash_content` parameter needs to be set to `trashed_only`. If searching in trash is not performed, an empty result set is returned. The items need to be owned or shared with the currently authenticated user for them to show up in the search results. If the user does not have access to any files owned by any of the users, an empty result set is returned. Data available from 2023-02-01 onwards. deleted_at_range `Optional[List[str]]` - Limits the search results to any items deleted within a given date range. Date ranges are defined as comma separated RFC3339 timestamps. If the the start date is omitted (`2014-05-17T13:35:01-07:00`), anything deleted before the end date will be returned. If the end date is omitted (`2014-05-15T13:35:01-07:00`), the current date will be used as the end date instead. The `trash_content` parameter needs to be set to `trashed_only`. If searching in trash is not performed, then an empty result is returned. Data available from 2023-02-01 onwards. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Union[SearchResults, SearchResultsWithSharedLinks]`. Returns a collection of search results. If there are no matching search results, the `entries` array will be empty. --- ## Untitled *Type: page* SessionTerminationManager Create jobs to terminate users session Create jobs to terminate user group session Create jobs to terminate users… # SessionTerminationManager - [Create jobs to terminate users session](#create-jobs-to-terminate-users-session) - [Create jobs to terminate user group session](#create-jobs-to-terminate-user-group-session) ## Create jobs to terminate users session Validates the roles and permissions of the user, and creates asynchronous jobs to terminate the user's sessions. Returns the status for the POST request. This operation is performed by calling function `terminate_users_sessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-terminate-sessions/). ``` client.session_termination.terminate_users_sessions( [get_env_var("USER_ID")], [user.login] ) ``` ### Arguments user_ids `List[str]` - A list of user IDs. user_logins `List[str]` - A list of user logins. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. ## Create jobs to terminate user group session Validates the roles and permissions of the group, and creates asynchronous jobs to terminate the group's sessions. Returns the status for the POST request. This operation is performed by calling function `terminate_groups_sessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups-terminate-sessions/). ``` client.session_termination.terminate_groups_sessions([group.id]) ``` ### Arguments group_ids `List[str]` - A list of group IDs. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. --- ## Untitled *Type: page* SharedLinksFilesManager Find file for shared link Get shared link for file Add shared link to file Update shared link on file Remove shared… # SharedLinksFilesManager - [Find file for shared link](#find-file-for-shared-link) - [Get shared link for file](#get-shared-link-for-file) - [Add shared link to file](#add-shared-link-to-file) - [Update shared link on file](#update-shared-link-on-file) - [Remove shared link from file](#remove-shared-link-from-file) ## Find file for shared link Returns the file represented by a shared link. A shared file can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared file when only given a shared link. The `shared_link_permission_options` array field can be returned by requesting it in the `fields` query parameter. This operation is performed by calling function `find_file_for_shared_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items/). ``` user_client.shared_links_files.find_file_for_shared_link( "".join( [ "shared_link=", file_from_api.shared_link.url, "&shared_link_password=Secret123@", ] ) ) ``` ### Arguments fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. if_none_match `Optional[str]` - Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. boxapi `str` - A header containing the shared link and optional password for the shared link. The format for this header is as follows: `shared_link=[link]&shared_link_password=[password]`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileFull`. Returns a full file resource if the shared link is valid and the user has access to it. ## Get shared link for file Gets the information for a shared link on a file. This operation is performed by calling function `get_shared_link_for_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id--get-shared-link/). ``` client.shared_links_files.get_shared_link_for_file(file_id, "shared_link") ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with the additional shared link information. ## Add shared link to file Adds a shared link to a file. This operation is performed by calling function `add_share_link_to_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--add-shared-link/). ``` client.shared_links_files.add_share_link_to_file( file_id, "shared_link", shared_link=AddShareLinkToFileSharedLink( access=AddShareLinkToFileSharedLinkAccessField.OPEN, password="Secret123@" ), ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" shared_link `Optional[AddShareLinkToFileSharedLink]` - The settings for the shared link to create on the file. Use an empty object (`{}`) to use the default settings for shared links. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with a new shared link attached. ## Update shared link on file Updates a shared link on a file. This operation is performed by calling function `update_shared_link_on_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--update-shared-link/). ``` client.shared_links_files.update_shared_link_on_file( file_id, "shared_link", shared_link=UpdateSharedLinkOnFileSharedLink( access=UpdateSharedLinkOnFileSharedLinkAccessField.COLLABORATORS ), ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" shared_link `Optional[UpdateSharedLinkOnFileSharedLink]` - The settings for the shared link to update. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileFull`. Returns a basic representation of the file, with the updated shared link attached. ## Remove shared link from file Removes a shared link from a file. This operation is performed by calling function `remove_shared_link_from_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--remove-shared-link/). ``` client.shared_links_files.remove_shared_link_from_file( file_id, "shared_link", shared_link=create_null() ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" shared_link `Optional[RemoveSharedLinkFromFileSharedLink]` - By setting this value to `null`, the shared link is removed from the file. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FileFull`. Returns a basic representation of a file, with the shared link removed. --- ## Untitled *Type: page* SharedLinksAppItemsManager Find app item for shared link Find app item for shared link Returns the app item represented by a shared link… # SharedLinksAppItemsManager - [Find app item for shared link](#find-app-item-for-shared-link) ## Find app item for shared link Returns the app item represented by a shared link. The link can originate from the current enterprise or another. This operation is performed by calling function `find_app_item_for_shared_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--app-items/). ``` client.shared_links_app_items.find_app_item_for_shared_link( "".join(["shared_link=", app_item_shared_link]) ) ``` ### Arguments boxapi `str` - A header containing the shared link and optional password for the shared link. The format for this header is `shared_link=[link]&shared_link_password=[password]`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `AppItem`. Returns a full app item resource if the shared link is valid and the user has access to it. --- ## Untitled *Type: page* SharedLinksFoldersManager Find folder for shared link Get shared link for folder Add shared link to folder Update shared link on folder… # SharedLinksFoldersManager - [Find folder for shared link](#find-folder-for-shared-link) - [Get shared link for folder](#get-shared-link-for-folder) - [Add shared link to folder](#add-shared-link-to-folder) - [Update shared link on folder](#update-shared-link-on-folder) - [Remove shared link from folder](#remove-shared-link-from-folder) ## Find folder for shared link Return the folder represented by a shared link. A shared folder can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared folder when only given a shared link. This operation is performed by calling function `find_folder_for_shared_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--folders/). ``` user_client.shared_links_folders.find_folder_for_shared_link( "".join( [ "shared_link=", folder_from_api.shared_link.url, "&shared_link_password=Secret123@", ] ) ) ``` ### Arguments fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. if_none_match `Optional[str]` - Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. boxapi `str` - A header containing the shared link and optional password for the shared link. The format for this header is as follows: `shared_link=[link]&shared_link_password=[password]`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns a full folder resource if the shared link is valid and the user has access to it. ## Get shared link for folder Gets the information for a shared link on a folder. This operation is performed by calling function `get_shared_link_for_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id--get-shared-link/). ``` client.shared_links_folders.get_shared_link_for_folder(folder.id, "shared_link") ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with the additional shared link information. ## Add shared link to folder Adds a shared link to a folder. This operation is performed by calling function `add_share_link_to_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--add-shared-link/). ``` client.shared_links_folders.add_share_link_to_folder( folder.id, "shared_link", shared_link=AddShareLinkToFolderSharedLink( access=AddShareLinkToFolderSharedLinkAccessField.OPEN, password="Secret123@" ), ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" shared_link `Optional[AddShareLinkToFolderSharedLink]` - The settings for the shared link to create on the folder. Use an empty object (`{}`) to use the default settings for shared links. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with a new shared link attached. ## Update shared link on folder Updates a shared link on a folder. This operation is performed by calling function `update_shared_link_on_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--update-shared-link/). ``` client.shared_links_folders.update_shared_link_on_folder( folder.id, "shared_link", shared_link=UpdateSharedLinkOnFolderSharedLink( access=UpdateSharedLinkOnFolderSharedLinkAccessField.COLLABORATORS ), ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" shared_link `Optional[UpdateSharedLinkOnFolderSharedLink]` - The settings for the shared link to update. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of the folder, with the updated shared link attached. ## Remove shared link from folder Removes a shared link from a folder. This operation is performed by calling function `remove_shared_link_from_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--remove-shared-link/). ``` client.shared_links_folders.remove_shared_link_from_folder( folder.id, "shared_link", shared_link=create_null() ) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" shared_link `Optional[RemoveSharedLinkFromFolderSharedLink]` - By setting this value to `null`, the shared link is removed from the folder. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of a folder, with the shared link removed. --- ## Untitled *Type: page* ShieldInformationBarrierReportsManager List shield information barrier reports Create shield information barrier report Get shield… # ShieldInformationBarrierReportsManager - [List shield information barrier reports](#list-shield-information-barrier-reports) - [Create shield information barrier report](#create-shield-information-barrier-report) - [Get shield information barrier report by ID](#get-shield-information-barrier-report-by-id) ## List shield information barrier reports Lists shield information barrier reports. This operation is performed by calling function `get_shield_information_barrier_reports`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports/). ``` client.shield_information_barrier_reports.get_shield_information_barrier_reports( barrier_id ) ``` ### Arguments shield_information_barrier_id `str` - The ID of the shield information barrier. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierReports`. Returns a paginated list of shield information barrier report objects. ## Create shield information barrier report Creates a shield information barrier report for a given barrier. This operation is performed by calling function `create_shield_information_barrier_report`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-reports/). ``` client.shield_information_barrier_reports.create_shield_information_barrier_report( shield_information_barrier=ShieldInformationBarrierBase( id=barrier_id, type=ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER, ) ) ``` ### Arguments - shield_information_barrier `Optional[ShieldInformationBarrierBase]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report information object. ## Get shield information barrier report by ID Retrieves a shield information barrier report by its ID. This operation is performed by calling function `get_shield_information_barrier_report_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports-id/). ``` client.shield_information_barrier_reports.get_shield_information_barrier_report_by_id( created_report.id ) ``` ### Arguments shield_information_barrier_report_id `str` - The ID of the shield information barrier Report. Example: "3423" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report object. --- ## Untitled *Type: page* SharedLinksWebLinksManager Find web link for shared link Get shared link for web link Add shared link to web link Update shared link on web… # SharedLinksWebLinksManager - [Find web link for shared link](#find-web-link-for-shared-link) - [Get shared link for web link](#get-shared-link-for-web-link) - [Add shared link to web link](#add-shared-link-to-web-link) - [Update shared link on web link](#update-shared-link-on-web-link) - [Remove shared link from web link](#remove-shared-link-from-web-link) ## Find web link for shared link Returns the web link represented by a shared link. A shared web link can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared web link when only given a shared link. This operation is performed by calling function `find_web_link_for_shared_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--web-links/). ``` user_client.shared_links_web_links.find_web_link_for_shared_link( "".join( [ "shared_link=", web_link_from_api.shared_link.url, "&shared_link_password=Secret123@", ] ) ) ``` ### Arguments fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. if_none_match `Optional[str]` - Ensures an item is only returned if it has changed. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `304 Not Modified` if the item has not changed since. boxapi `str` - A header containing the shared link and optional password for the shared link. The format for this header is as follows: `shared_link=[link]&shared_link_password=[password]`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `WebLink`. Returns a full web link resource if the shared link is valid and the user has access to it. ## Get shared link for web link Gets the information for a shared link on a web link. This operation is performed by calling function `get_shared_link_for_web_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id--get-shared-link/). ``` client.shared_links_web_links.get_shared_link_for_web_link(web_link_id, "shared_link") ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with the additional shared link information. ## Add shared link to web link Adds a shared link to a web link. This operation is performed by calling function `add_share_link_to_web_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--add-shared-link/). ``` client.shared_links_web_links.add_share_link_to_web_link( web_link_id, "shared_link", shared_link=AddShareLinkToWebLinkSharedLink( access=AddShareLinkToWebLinkSharedLinkAccessField.OPEN, password="Secret123@" ), ) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" shared_link `Optional[AddShareLinkToWebLinkSharedLink]` - The settings for the shared link to create on the web link. Use an empty object (`{}`) to use the default settings for shared links. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with a new shared link attached. ## Update shared link on web link Updates a shared link on a web link. This operation is performed by calling function `update_shared_link_on_web_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--update-shared-link/). ``` client.shared_links_web_links.update_shared_link_on_web_link( web_link_id, "shared_link", shared_link=UpdateSharedLinkOnWebLinkSharedLink( access=UpdateSharedLinkOnWebLinkSharedLinkAccessField.COLLABORATORS ), ) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" shared_link `Optional[UpdateSharedLinkOnWebLinkSharedLink]` - The settings for the shared link to update. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `WebLink`. Returns a basic representation of the web link, with the updated shared link attached. ## Remove shared link from web link Removes a shared link from a web link. This operation is performed by calling function `remove_shared_link_from_web_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--remove-shared-link/). ``` client.shared_links_web_links.remove_shared_link_from_web_link( web_link_id, "shared_link", shared_link=create_null() ) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" shared_link `Optional[RemoveSharedLinkFromWebLinkSharedLink]` - By setting this value to `null`, the shared link is removed from the web link. fields `str` - Explicitly request the `shared_link` fields to be returned for this item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `WebLink`. Returns a basic representation of a web link, with the shared link removed. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentRestrictionsManager Get shield information barrier segment restriction by ID Delete shield information… # ShieldInformationBarrierSegmentRestrictionsManager - [Get shield information barrier segment restriction by ID](#get-shield-information-barrier-segment-restriction-by-id) - [Delete shield information barrier segment restriction by ID](#delete-shield-information-barrier-segment-restriction-by-id) - [List shield information barrier segment restrictions](#list-shield-information-barrier-segment-restrictions) - [Create shield information barrier segment restriction](#create-shield-information-barrier-segment-restriction) ## Get shield information barrier segment restriction by ID Retrieves a shield information barrier segment restriction based on provided ID. This operation is performed by calling function `get_shield_information_barrier_segment_restriction_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions-id/). ``` client.shield_information_barrier_segment_restrictions.get_shield_information_barrier_segment_restriction_by_id( segment_restriction_id ) ``` ### Arguments shield_information_barrier_segment_restriction_id `str` - The ID of the shield information barrier segment Restriction. Example: "4563" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the shield information barrier segment restriction object. ## Delete shield information barrier segment restriction by ID Delete shield information barrier segment restriction based on provided ID. This operation is performed by calling function `delete_shield_information_barrier_segment_restriction_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-restrictions-id/). ``` client.shield_information_barrier_segment_restrictions.delete_shield_information_barrier_segment_restriction_by_id( segment_restriction_id ) ``` ### Arguments shield_information_barrier_segment_restriction_id `str` - The ID of the shield information barrier segment Restriction. Example: "4563" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Empty body in response. ## List shield information barrier segment restrictions Lists shield information barrier segment restrictions based on provided segment ID. This operation is performed by calling function `get_shield_information_barrier_segment_restrictions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions/). ``` client.shield_information_barrier_segment_restrictions.get_shield_information_barrier_segment_restrictions( segment_id ) ``` ### Arguments shield_information_barrier_segment_id `str` - The ID of the shield information barrier segment. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestrictions`. Returns a paginated list of shield information barrier segment restriction objects. ## Create shield information barrier segment restriction Creates a shield information barrier segment restriction object. This operation is performed by calling function `create_shield_information_barrier_segment_restriction`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-restrictions/). ``` client.shield_information_barrier_segment_restrictions.create_shield_information_barrier_segment_restriction( CreateShieldInformationBarrierSegmentRestrictionShieldInformationBarrierSegment( id=segment_id, type=CreateShieldInformationBarrierSegmentRestrictionShieldInformationBarrierSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT, ), CreateShieldInformationBarrierSegmentRestrictionRestrictedSegment( id=segment_to_restrict_id, type=CreateShieldInformationBarrierSegmentRestrictionRestrictedSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT, ), type=CreateShieldInformationBarrierSegmentRestrictionType.SHIELD_INFORMATION_BARRIER_SEGMENT_RESTRICTION, ) ``` ### Arguments type `CreateShieldInformationBarrierSegmentRestrictionType` - The type of the shield barrier segment restriction for this member. shield_information_barrier `Optional[ShieldInformationBarrierBase]` shield_information_barrier_segment `CreateShieldInformationBarrierSegmentRestrictionShieldInformationBarrierSegment` - The `type` and `id` of the requested shield information barrier segment. restricted_segment `CreateShieldInformationBarrierSegmentRestrictionRestrictedSegment` - The `type` and `id` of the restricted shield information barrier segment. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the newly created Shield Information Barrier Segment Restriction object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentMembersManager Get shield information barrier segment member by ID Delete shield information barrier segment… # ShieldInformationBarrierSegmentMembersManager - [Get shield information barrier segment member by ID](#get-shield-information-barrier-segment-member-by-id) - [Delete shield information barrier segment member by ID](#delete-shield-information-barrier-segment-member-by-id) - [List shield information barrier segment members](#list-shield-information-barrier-segment-members) - [Create shield information barrier segment member](#create-shield-information-barrier-segment-member) ## Get shield information barrier segment member by ID Retrieves a shield information barrier segment member by its ID. This operation is performed by calling function `get_shield_information_barrier_segment_member_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members-id/). ``` client.shield_information_barrier_segment_members.get_shield_information_barrier_segment_member_by_id( segment_member.id ) ``` ### Arguments shield_information_barrier_segment_member_id `str` - The ID of the shield information barrier segment Member. Example: "7815" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns the shield information barrier segment member object. ## Delete shield information barrier segment member by ID Deletes a shield information barrier segment member based on provided ID. This operation is performed by calling function `delete_shield_information_barrier_segment_member_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-members-id/). ``` client.shield_information_barrier_segment_members.delete_shield_information_barrier_segment_member_by_id( segment_member.id ) ``` ### Arguments shield_information_barrier_segment_member_id `str` - The ID of the shield information barrier segment Member. Example: "7815" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response if the segment member was deleted successfully. ## List shield information barrier segment members Lists shield information barrier segment members based on provided segment IDs. This operation is performed by calling function `get_shield_information_barrier_segment_members`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members/). ``` client.shield_information_barrier_segment_members.get_shield_information_barrier_segment_members( segment.id ) ``` ### Arguments shield_information_barrier_segment_id `str` - The ID of the shield information barrier segment. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMembers`. Returns a paginated list of shield information barrier segment member objects. ## Create shield information barrier segment member Creates a new shield information barrier segment member. This operation is performed by calling function `create_shield_information_barrier_segment_member`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-members/). ``` client.shield_information_barrier_segment_members.create_shield_information_barrier_segment_member( CreateShieldInformationBarrierSegmentMemberShieldInformationBarrierSegment( id=segment.id, type=CreateShieldInformationBarrierSegmentMemberShieldInformationBarrierSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT, ), UserBase(id=get_env_var("USER_ID")), ) ``` ### Arguments type `Optional[CreateShieldInformationBarrierSegmentMemberType]` - A type of the shield barrier segment member. shield_information_barrier `Optional[ShieldInformationBarrierBase]` shield_information_barrier_segment `CreateShieldInformationBarrierSegmentMemberShieldInformationBarrierSegment` - The `type` and `id` of the requested shield information barrier segment. user `UserBase` - User to which restriction will be applied. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns a new shield information barrier segment member object. --- ## Untitled *Type: page* ShieldInformationBarriersManager Get shield information barrier with specified ID Add changed status of shield information barrier with… # ShieldInformationBarriersManager - [Get shield information barrier with specified ID](#get-shield-information-barrier-with-specified-id) - [Add changed status of shield information barrier with specified ID](#add-changed-status-of-shield-information-barrier-with-specified-id) - [List shield information barriers](#list-shield-information-barriers) - [Create shield information barrier](#create-shield-information-barrier) ## Get shield information barrier with specified ID Get shield information barrier based on provided ID. This operation is performed by calling function `get_shield_information_barrier_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers-id/). ``` client.shield_information_barriers.get_shield_information_barrier_by_id(barrier_id) ``` ### Arguments shield_information_barrier_id `str` - The ID of the shield information barrier. Example: "1910967" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the shield information barrier object. ## Add changed status of shield information barrier with specified ID Change status of shield information barrier with the specified ID. This operation is performed by calling function `update_shield_information_barrier_status`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers-change-status/). ``` client.shield_information_barriers.update_shield_information_barrier_status( barrier_id, UpdateShieldInformationBarrierStatusStatus.DISABLED ) ``` ### Arguments id `str` - The ID of the shield information barrier. status `UpdateShieldInformationBarrierStatusStatus` - The desired status for the shield information barrier. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the updated shield information barrier object. ## List shield information barriers Retrieves a list of shield information barrier objects for the enterprise of JWT. This operation is performed by calling function `get_shield_information_barriers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers/). ``` client.shield_information_barriers.get_shield_information_barriers() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarriers`. Returns a paginated list of shield information barrier objects, empty list if currently no barrier. ## Create shield information barrier Creates a shield information barrier to separate individuals/groups within the same firm and prevents confidential information passing between them. This operation is performed by calling function `create_shield_information_barrier`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers/). ``` client.shield_information_barriers.create_shield_information_barrier( EnterpriseBase(id=enterprise_id) ) ``` ### Arguments enterprise `EnterpriseBase` - The `type` and `id` of enterprise this barrier is under. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns a new shield information barrier object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentsManager Get shield information barrier segment with specified ID Delete shield information barrier segment… # ShieldInformationBarrierSegmentsManager - [Get shield information barrier segment with specified ID](#get-shield-information-barrier-segment-with-specified-id) - [Delete shield information barrier segment](#delete-shield-information-barrier-segment) - [Update shield information barrier segment with specified ID](#update-shield-information-barrier-segment-with-specified-id) - [List shield information barrier segments](#list-shield-information-barrier-segments) - [Create shield information barrier segment](#create-shield-information-barrier-segment) ## Get shield information barrier segment with specified ID Retrieves shield information barrier segment based on provided ID.. This operation is performed by calling function `get_shield_information_barrier_segment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments-id/). ``` client.shield_information_barrier_segments.get_shield_information_barrier_segment_by_id( segment_id ) ``` ### Arguments shield_information_barrier_segment_id `str` - The ID of the shield information barrier segment. Example: "3423" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the shield information barrier segment object. ## Delete shield information barrier segment Deletes the shield information barrier segment based on provided ID. This operation is performed by calling function `delete_shield_information_barrier_segment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segments-id/). ``` client.shield_information_barrier_segments.delete_shield_information_barrier_segment_by_id( segment_id ) ``` ### Arguments shield_information_barrier_segment_id `str` - The ID of the shield information barrier segment. Example: "3423" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Empty body in response. ## Update shield information barrier segment with specified ID Updates the shield information barrier segment based on provided ID.. This operation is performed by calling function `update_shield_information_barrier_segment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-shield-information-barrier-segments-id/). ``` client.shield_information_barrier_segments.update_shield_information_barrier_segment_by_id( segment_id, description=updated_segment_description ) ``` ### Arguments shield_information_barrier_segment_id `str` - The ID of the shield information barrier segment. Example: "3423" name `Optional[str]` - The updated name for the shield information barrier segment. description `Optional[str]` - The updated description for the shield information barrier segment. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the updated shield information barrier segment object. ## List shield information barrier segments Retrieves a list of shield information barrier segment objects for the specified Information Barrier ID. This operation is performed by calling function `get_shield_information_barrier_segments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments/). ``` client.shield_information_barrier_segments.get_shield_information_barrier_segments( barrier_id ) ``` ### Arguments shield_information_barrier_id `str` - The ID of the shield information barrier. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegments`. Returns a paginated list of shield information barrier segment objects. ## Create shield information barrier segment Creates a shield information barrier segment. This operation is performed by calling function `create_shield_information_barrier_segment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segments/). ``` client.shield_information_barrier_segments.create_shield_information_barrier_segment( ShieldInformationBarrierBase( id=barrier_id, type=ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER, ), segment_name, description=segment_description, ) ``` ### Arguments - shield_information_barrier `ShieldInformationBarrierBase` name `str` - Name of the shield information barrier segment. description `Optional[str]` - Description of the shield information barrier segment. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns a new shield information barrier segment object. --- ## Untitled *Type: page* ShieldListsManager Get all shield lists in enterprise Create shield list Get single shield list by shield list id Delete single shield list… # ShieldListsManager - [Get all shield lists in enterprise](#get-all-shield-lists-in-enterprise) - [Create shield list](#create-shield-list) - [Get single shield list by shield list id](#get-single-shield-list-by-shield-list-id) - [Delete single shield list by shield list id](#delete-single-shield-list-by-shield-list-id) - [Update shield list](#update-shield-list) ## Get all shield lists in enterprise Retrieves all shield lists in the enterprise. This operation is performed by calling function `get_shield_lists_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists/). ``` client.shield_lists.get_shield_lists_v2025_r0() ``` ### Arguments box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldListsV2025R0`. Returns the list of shield list objects. ## Create shield list Creates a shield list. This operation is performed by calling function `create_shield_list_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-shield-lists/). ``` client.shield_lists.create_shield_list_v2025_r0( shield_list_country_name, ShieldListContentCountryV2025R0( type=ShieldListContentCountryV2025R0TypeField.COUNTRY, country_codes=["US", "PL"], ), description="A list of things that are shielded", ) ``` ### Arguments name `str` - The name of the shield list. description `Optional[str]` - Optional description of Shield List. content `ShieldListContentRequestV2025R0` box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Get single shield list by shield list id Retrieves a single shield list by its ID. This operation is performed by calling function `get_shield_list_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists-id/). ``` client.shield_lists.get_shield_list_by_id_v2025_r0(shield_list_country.id) ``` ### Arguments shield_list_id `str` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Delete single shield list by shield list id Delete a single shield list by its ID. This operation is performed by calling function `delete_shield_list_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-shield-lists-id/). ``` client.shield_lists.delete_shield_list_by_id_v2025_r0(shield_list_country.id) ``` ### Arguments shield_list_id `str` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Shield List correctly removed. No content in response. ## Update shield list Updates a shield list. This operation is performed by calling function `update_shield_list_by_id_v2025_r0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-shield-lists-id/). ``` client.shield_lists.update_shield_list_by_id_v2025_r0( shield_list_country.id, shield_list_country_name, ShieldListContentCountryV2025R0( type=ShieldListContentCountryV2025R0TypeField.COUNTRY, country_codes=["US"] ), description="Updated description", ) ``` ### Arguments shield_list_id `str` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " name `str` - The name of the shield list. description `Optional[str]` - Optional description of Shield List. content `ShieldListContentRequestV2025R0` box_version `BoxVersionHeaderV2025R0` - Version header. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. --- ## Untitled *Type: page* SignRequestsManager Cancel Box Sign request Resend Box Sign request Get Box Sign request by ID List Box Sign requests Create Box Sign… # SignRequestsManager - [Cancel Box Sign request](#cancel-box-sign-request) - [Resend Box Sign request](#resend-box-sign-request) - [Get Box Sign request by ID](#get-box-sign-request-by-id) - [List Box Sign requests](#list-box-sign-requests) - [Create Box Sign request](#create-box-sign-request) ## Cancel Box Sign request Cancels a sign request. This operation is performed by calling function `cancel_sign_request`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-cancel/). ``` client.sign_requests.cancel_sign_request(created_sign_request.id) ``` ### Arguments sign_request_id `str` - The ID of the signature request. Example: "33243242" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SignRequest`. Returns a Sign Request object. ## Resend Box Sign request Resends a signature request email to all outstanding signers. This operation is performed by calling function `resend_sign_request`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-resend/). *Currently we don't have an example for calling `resend_sign_request` in integration tests* ### Arguments sign_request_id `str` - The ID of the signature request. Example: "33243242" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the API call was successful. The email notifications will be sent asynchronously. ## Get Box Sign request by ID Gets a sign request by ID. This operation is performed by calling function `get_sign_request_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests-id/). ``` client.sign_requests.get_sign_request_by_id(created_sign_request.id) ``` ### Arguments sign_request_id `str` - The ID of the signature request. Example: "33243242" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SignRequest`. Returns a signature request. ## List Box Sign requests Gets signature requests created by a user. If the `sign_files` and/or `parent_folder` are deleted, the signature request will not return in the list. This operation is performed by calling function `get_sign_requests`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests/). ``` client.sign_requests.get_sign_requests() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. senders `Optional[List[str]]` - A list of sender emails to filter the signature requests by sender. If provided, `shared_requests` must be set to `true`. shared_requests `Optional[bool]` - If set to `true`, only includes requests that user is not an owner, but user is a collaborator. Collaborator access is determined by the user access level of the sign files of the request. Default is `false`. Must be set to `true` if `senders` are provided. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SignRequests`. Returns a collection of sign requests. ## Create Box Sign request Creates a signature request. This involves preparing a document for signing and sending the signature request to signers. This operation is performed by calling function `create_sign_request`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests/). ``` client.sign_requests.create_sign_request( [ SignRequestCreateSigner( email=signer_email, suppress_notifications=True, declined_redirect_url="https://www.box.com", embed_url_external_user_id="123", is_in_person=False, login_required=False, password="password", role=SignRequestCreateSignerRoleField.SIGNER, ) ], source_files=[FileBase(id=file_to_sign.id)], parent_folder=FolderMini(id=destination_folder.id), is_document_preparation_needed=False, redirect_url="https://www.box.com", declined_redirect_url="https://www.box.com", are_text_signatures_enabled=True, email_subject="Sign this document", email_message="Please sign this document", are_reminders_enabled=True, name="Sign Request", prefill_tags=[ SignRequestPrefillTag( date_value=date_from_string("2035-01-01"), document_tag_id="0" ) ], days_valid=30, external_id="123", external_system_name="BoxSignIntegration", ) ``` ### Arguments source_files `Optional[List[FileBase]]` - List of files to create a signing document from. This is currently limited to ten files. Only the ID and type fields are required for each file. signature_color `Optional[CreateSignRequestSignatureColor]` - Force a specific color for the signature (blue, black, or red). signers `List[SignRequestCreateSigner]` - Array of signers for the signature request. 35 is the max number of signers permitted. **Note**: It may happen that some signers belong to conflicting [segments](r://shield-information-barrier-segment-member) (user groups). This means that due to the security policies, users are assigned to segments to prevent exchanges or communication that could lead to ethical conflicts. In such a case, an attempt to send the sign request will result in an error. Read more about [segments and ethical walls](https://support.box.com/hc/en-us/articles/9920431507603-Understanding-Information-Barriers#h_01GFVJEHQA06N7XEZ4GCZ9GFAQ). parent_folder `Optional[FolderMini]` is_document_preparation_needed `Optional[bool]` - Indicates if the sender should receive a `prepare_url` in the response to complete document preparation using the UI. redirect_url `Optional[str]` - When specified, the signature request will be redirected to this url when a document is signed. declined_redirect_url `Optional[str]` - The uri that a signer will be redirected to after declining to sign a document. are_text_signatures_enabled `Optional[bool]` - Disables the usage of signatures generated by typing (text). email_subject `Optional[str]` - Subject of sign request email. This is cleaned by sign request. If this field is not passed, a default subject will be used. email_message `Optional[str]` - Message to include in sign request email. The field is cleaned through sanitization of specific characters. However, some html tags are allowed. Links included in the message are also converted to hyperlinks in the email. The message may contain the following html tags including `a`, `abbr`, `acronym`, `b`, `blockquote`, `code`, `em`, `i`, `ul`, `li`, `ol`, and `strong`. Be aware that when the text to html ratio is too high, the email may end up in spam filters. Custom styles on these tags are not allowed. If this field is not passed, a default message will be used. are_reminders_enabled `Optional[bool]` - Reminds signers to sign a document on day 3, 8, 13 and 18. Reminders are only sent to outstanding signers. name `Optional[str]` - Name of the signature request. prefill_tags `Optional[List[SignRequestPrefillTag]]` - When a document contains sign-related tags in the content, you can prefill them using this `prefill_tags` by referencing the 'id' of the tag as the `external_id` field of the prefill tag. days_valid `Optional[int]` - Set the number of days after which the created signature request will automatically expire if not completed. By default, we do not apply any expiration date on signature requests, and the signature request does not expire. external_id `Optional[str]` - This can be used to reference an ID in an external system that the sign request is related to. template_id `Optional[str]` - When a signature request is created from a template this field will indicate the id of that template. external_system_name `Optional[str]` - Used as an optional system name to appear in the signature log next to the signers who have been assigned the `embed_url_external_id`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SignRequest`. Returns a Box Sign request object. --- ## Untitled *Type: page* SignTemplatesManager List Box Sign templates Get Box Sign template by ID List Box Sign templates Gets Box Sign templates created by a user… # SignTemplatesManager - [List Box Sign templates](#list-box-sign-templates) - [Get Box Sign template by ID](#get-box-sign-template-by-id) ## List Box Sign templates Gets Box Sign templates created by a user. This operation is performed by calling function `get_sign_templates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates/). ``` client.sign_templates.get_sign_templates(limit=2) ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SignTemplates`. Returns a collection of templates. ## Get Box Sign template by ID Fetches details of a specific Box Sign template. This operation is performed by calling function `get_sign_template_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates-id/). ``` client.sign_templates.get_sign_template_by_id(sign_templates.entries[0].id) ``` ### Arguments template_id `str` - The ID of a Box Sign template. Example: "123075213-7d117509-8f05-42e4-a5ef-5190a319d41d" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SignTemplate`. Returns details of a template. --- ## Untitled *Type: page* StoragePoliciesManager List storage policies Get storage policy List storage policies Fetches all the storage policies in the enterprise… # StoragePoliciesManager - [List storage policies](#list-storage-policies) - [Get storage policy](#get-storage-policy) ## List storage policies Fetches all the storage policies in the enterprise. This operation is performed by calling function `get_storage_policies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies/). ``` client.storage_policies.get_storage_policies() ``` ### Arguments fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `StoragePolicies`. Returns a collection of storage policies. ## Get storage policy Fetches a specific storage policy. This operation is performed by calling function `get_storage_policy_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies-id/). ``` client.storage_policies.get_storage_policy_by_id(storage_policy.id) ``` ### Arguments storage_policy_id `str` - The ID of the storage policy. Example: "34342" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `StoragePolicy`. Returns a storage policy object. --- ## Untitled *Type: page* StoragePolicyAssignmentsManager List storage policy assignments Assign storage policy Get storage policy assignment Update storage policy… # StoragePolicyAssignmentsManager - [List storage policy assignments](#list-storage-policy-assignments) - [Assign storage policy](#assign-storage-policy) - [Get storage policy assignment](#get-storage-policy-assignment) - [Update storage policy assignment](#update-storage-policy-assignment) - [Unassign storage policy](#unassign-storage-policy) ## List storage policy assignments Fetches all the storage policy assignment for an enterprise or user. This operation is performed by calling function `get_storage_policy_assignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments/). ``` client.storage_policy_assignments.get_storage_policy_assignments( GetStoragePolicyAssignmentsResolvedForType.USER, user_id ) ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. resolved_for_type `GetStoragePolicyAssignmentsResolvedForType` - The target type to return assignments for. resolved_for_id `str` - The ID of the user or enterprise to return assignments for. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `StoragePolicyAssignments`. Returns a collection of storage policies for the enterprise or user. ## Assign storage policy Creates a storage policy assignment for an enterprise or user. This operation is performed by calling function `create_storage_policy_assignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-storage-policy-assignments/). ``` client.storage_policy_assignments.create_storage_policy_assignment( CreateStoragePolicyAssignmentStoragePolicy(id=policy_id), CreateStoragePolicyAssignmentAssignedTo( id=user_id, type=CreateStoragePolicyAssignmentAssignedToTypeField.USER ), ) ``` ### Arguments storage_policy `CreateStoragePolicyAssignmentStoragePolicy` - The storage policy to assign to the user or enterprise. assigned_to `CreateStoragePolicyAssignmentAssignedTo` - The user or enterprise to assign the storage policy to. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns the new storage policy assignment created. ## Get storage policy assignment Fetches a specific storage policy assignment. This operation is performed by calling function `get_storage_policy_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments-id/). ``` client.storage_policy_assignments.get_storage_policy_assignment_by_id( storage_policy_assignment.id ) ``` ### Arguments storage_policy_assignment_id `str` - The ID of the storage policy assignment. Example: "932483" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns a storage policy assignment object. ## Update storage policy assignment Updates a specific storage policy assignment. This operation is performed by calling function `update_storage_policy_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-storage-policy-assignments-id/). ``` client.storage_policy_assignments.update_storage_policy_assignment_by_id( storage_policy_assignment.id, UpdateStoragePolicyAssignmentByIdStoragePolicy(id=storage_policy_2.id), ) ``` ### Arguments storage_policy_assignment_id `str` - The ID of the storage policy assignment. Example: "932483" storage_policy `UpdateStoragePolicyAssignmentByIdStoragePolicy` - The storage policy to assign to the user or enterprise. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns an updated storage policy assignment object. ## Unassign storage policy Delete a storage policy assignment. Deleting a storage policy assignment on a user will have the user inherit the enterprise's default storage policy. There is a rate limit for calling this endpoint of only twice per user in a 24 hour time frame. This operation is performed by calling function `delete_storage_policy_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-storage-policy-assignments-id/). ``` client.storage_policy_assignments.delete_storage_policy_assignment_by_id( storage_policy_assignment.id ) ``` ### Arguments storage_policy_assignment_id `str` - The ID of the storage policy assignment. Example: "932483" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the storage policy assignment is successfully deleted. --- ## Untitled *Type: page* TaskAssignmentsManager List task assignments Assign task Get task assignment Update task assignment Unassign task List task assignments… # TaskAssignmentsManager - [List task assignments](#list-task-assignments) - [Assign task](#assign-task) - [Get task assignment](#get-task-assignment) - [Update task assignment](#update-task-assignment) - [Unassign task](#unassign-task) ## List task assignments Lists all of the assignments for a given task. This operation is performed by calling function `get_task_assignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id-assignments/). ``` client.task_assignments.get_task_assignments(task.id) ``` ### Arguments task_id `str` - The ID of the task. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TaskAssignments`. Returns a collection of task assignment defining what task on a file has been assigned to which users and by who. ## Assign task Assigns a task to a user. A task can be assigned to more than one user by creating multiple assignments. This operation is performed by calling function `create_task_assignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-task-assignments/). ``` client.task_assignments.create_task_assignment( CreateTaskAssignmentTask(type=CreateTaskAssignmentTaskTypeField.TASK, id=task.id), CreateTaskAssignmentAssignTo(id=current_user.id), ) ``` ### Arguments task `CreateTaskAssignmentTask` - The task to assign to a user. assign_to `CreateTaskAssignmentAssignTo` - The user to assign the task to. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TaskAssignment`. Returns a new task assignment object. ## Get task assignment Retrieves information about a task assignment. This operation is performed by calling function `get_task_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-task-assignments-id/). ``` client.task_assignments.get_task_assignment_by_id(task_assignment.id) ``` ### Arguments task_assignment_id `str` - The ID of the task assignment. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TaskAssignment`. Returns a task assignment, specifying who the task has been assigned to and by whom. ## Update task assignment Updates a task assignment. This endpoint can be used to update the state of a task assigned to a user. This operation is performed by calling function `update_task_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-task-assignments-id/). ``` client.task_assignments.update_task_assignment_by_id( task_assignment.id, message="updated message", resolution_state=UpdateTaskAssignmentByIdResolutionState.APPROVED, ) ``` ### Arguments task_assignment_id `str` - The ID of the task assignment. Example: "12345" message `Optional[str]` - An optional message by the assignee that can be added to the task. resolution_state `Optional[UpdateTaskAssignmentByIdResolutionState]` - The state of the task assigned to the user. _ For a task with an `action` value of `complete` this can be `incomplete` or `completed`. _ For a task with an `action` of `review` this can be `incomplete`, `approved`, or `rejected`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TaskAssignment`. Returns the updated task assignment object. ## Unassign task Deletes a specific task assignment. This operation is performed by calling function `delete_task_assignment_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-task-assignments-id/). ``` client.task_assignments.delete_task_assignment_by_id(task_assignment.id) ``` ### Arguments task_assignment_id `str` - The ID of the task assignment. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the task assignment was successfully deleted. --- ## Untitled *Type: page* SkillsManager List Box Skill cards on file Create Box Skill cards on file Update Box Skill cards on file Remove Box Skill cards from file… # SkillsManager - [List Box Skill cards on file](#list-box-skill-cards-on-file) - [Create Box Skill cards on file](#create-box-skill-cards-on-file) - [Update Box Skill cards on file](#update-box-skill-cards-on-file) - [Remove Box Skill cards from file](#remove-box-skill-cards-from-file) - [Update all Box Skill cards on file](#update-all-box-skill-cards-on-file) ## List Box Skill cards on file List the Box Skills metadata cards that are attached to a file. This operation is performed by calling function `get_box_skill_cards_on_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-global-boxSkillsCards/). ``` client.skills.get_box_skill_cards_on_file(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SkillCardsMetadata`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Create Box Skill cards on file Applies one or more Box Skills metadata cards to a file. This operation is performed by calling function `create_box_skill_cards_on_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-global-boxSkillsCards/). ``` client.skills.create_box_skill_cards_on_file(file.id, cards_to_create) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" cards `List[Union[KeywordSkillCard, TimelineSkillCard, TranscriptSkillCard, StatusSkillCard]]` - A list of Box Skill cards to apply to this file. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update Box Skill cards on file Updates one or more Box Skills metadata cards to a file. This operation is performed by calling function `update_box_skill_cards_on_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-global-boxSkillsCards/). ``` client.skills.update_box_skill_cards_on_file( file.id, [ UpdateBoxSkillCardsOnFileRequestBody( op=UpdateBoxSkillCardsOnFileRequestBodyOpField.REPLACE, path="/cards/0", value=card_to_update, ) ], ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" request_body `List[UpdateBoxSkillCardsOnFileRequestBody]` - Request body of updateBoxSkillCardsOnFile method extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the updated metadata template, with the custom template data included. ## Remove Box Skill cards from file Removes any Box Skills cards metadata from a file. This operation is performed by calling function `delete_box_skill_cards_from_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-global-boxSkillsCards/). ``` client.skills.delete_box_skill_cards_from_file(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the cards are successfully deleted. ## Update all Box Skill cards on file An alternative method that can be used to overwrite and update all Box Skill metadata cards on a file. This operation is performed by calling function `update_all_skill_cards_on_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-skill-invocations-id/). *Currently we don't have an example for calling `update_all_skill_cards_on_file` in integration tests* ### Arguments skill_id `str` - The ID of the skill to apply this metadata for. Example: "33243242" status `UpdateAllSkillCardsOnFileStatus` - Defines the status of this invocation. Set this to `success` when setting Skill cards. metadata `UpdateAllSkillCardsOnFileMetadata` - The metadata to set for this skill. This is a list of Box Skills cards. These cards will overwrite any existing Box skill cards on the file. file `UpdateAllSkillCardsOnFileFile` - The file to assign the cards to. file_version `Optional[UpdateAllSkillCardsOnFileFileVersion]` - The optional file version to assign the cards to. usage `Optional[UpdateAllSkillCardsOnFileUsage]` - A descriptor that defines what items are affected by this call. Set this to the default values when setting a card to a `success` state, and leave it out in most other situations. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the card has been successfully updated. --- ## Untitled *Type: page* TermsOfServiceUserStatusesManager List terms of service user statuses Create terms of service status for new user Update terms of service… # TermsOfServiceUserStatusesManager - [List terms of service user statuses](#list-terms-of-service-user-statuses) - [Create terms of service status for new user](#create-terms-of-service-status-for-new-user) - [Update terms of service status for existing user](#update-terms-of-service-status-for-existing-user) ## List terms of service user statuses Retrieves an overview of users and their status for a terms of service, including Whether they have accepted the terms and when. This operation is performed by calling function `get_terms_of_service_user_statuses`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-service-user-statuses/). ``` client.terms_of_service_user_statuses.get_terms_of_service_user_statuses( tos.id, user_id=user.id ) ``` ### Arguments tos_id `str` - The ID of the terms of service. user_id `Optional[str]` - Limits results to the given user ID. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TermsOfServiceUserStatuses`. Returns a list of terms of service statuses. ## Create terms of service status for new user Sets the status for a terms of service for a user. This operation is performed by calling function `create_terms_of_service_status_for_user`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-service-user-statuses/). ``` client.terms_of_service_user_statuses.create_terms_of_service_status_for_user( CreateTermsOfServiceStatusForUserTos(id=tos.id), CreateTermsOfServiceStatusForUserUser(id=user.id), False, ) ``` ### Arguments tos `CreateTermsOfServiceStatusForUserTos` - The terms of service to set the status for. user `CreateTermsOfServiceStatusForUserUser` - The user to set the status for. is_accepted `bool` - Whether the user has accepted the terms. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns a terms of service status object. ## Update terms of service status for existing user Updates the status for a terms of service for a user. This operation is performed by calling function `update_terms_of_service_status_for_user_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-service-user-statuses-id/). ``` client.terms_of_service_user_statuses.update_terms_of_service_status_for_user_by_id( created_tos_user_status.id, True ) ``` ### Arguments terms_of_service_user_status_id `str` - The ID of the terms of service status. Example: "324234" is_accepted `bool` - Whether the user has accepted the terms. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns the updated terms of service status object. --- ## Untitled *Type: page* TasksManager List tasks on file Create task Get task Update task Remove task List tasks on file Retrieves a list of all the tasks for a file… # TasksManager - [List tasks on file](#list-tasks-on-file) - [Create task](#create-task) - [Get task](#get-task) - [Update task](#update-task) - [Remove task](#remove-task) ## List tasks on file Retrieves a list of all the tasks for a file. This endpoint does not support pagination. This operation is performed by calling function `get_file_tasks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-tasks/). ``` client.tasks.get_file_tasks(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Tasks`. Returns a list of tasks on a file. If there are no tasks on this file an empty collection is returned instead. ## Create task Creates a single task on a file. This task is not assigned to any user and will need to be assigned separately. This operation is performed by calling function `create_task`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-tasks/). ``` client.tasks.create_task( CreateTaskItem(type=CreateTaskItemTypeField.FILE, id=file.id), action=CreateTaskAction.REVIEW, message="test message", due_at=date_time, completion_rule=CreateTaskCompletionRule.ALL_ASSIGNEES, ) ``` ### Arguments item `CreateTaskItem` - The file to attach the task to. action `Optional[CreateTaskAction]` - The action the task assignee will be prompted to do. Must be _ `review` defines an approval task that can be approved or, rejected _ `complete` defines a general task which can be completed. message `Optional[str]` - An optional message to include with the task. due_at `Optional[DateTime]` - Defines when the task is due. Defaults to `null` if not provided. completion_rule `Optional[CreateTaskCompletionRule]` - Defines which assignees need to complete this task before the task is considered completed. _ `all_assignees` (default) requires all assignees to review or approve the the task in order for it to be considered completed. _ `any_assignee` accepts any one assignee to review or approve the the task in order for it to be considered completed. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Task`. Returns the newly created task. ## Get task Retrieves information about a specific task. This operation is performed by calling function `get_task_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id/). ``` client.tasks.get_task_by_id(task.id) ``` ### Arguments task_id `str` - The ID of the task. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Task`. Returns a task object. ## Update task Updates a task. This can be used to update a task's configuration, or to update its completion state. This operation is performed by calling function `update_task_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-tasks-id/). ``` client.tasks.update_task_by_id(task.id, message="updated message") ``` ### Arguments task_id `str` - The ID of the task. Example: "12345" action `Optional[UpdateTaskByIdAction]` - The action the task assignee will be prompted to do. Must be _ `review` defines an approval task that can be approved or rejected, _ `complete` defines a general task which can be completed. message `Optional[str]` - The message included with the task. due_at `Optional[DateTime]` - When the task is due at. completion_rule `Optional[UpdateTaskByIdCompletionRule]` - Defines which assignees need to complete this task before the task is considered completed. _ `all_assignees` (default) requires all assignees to review or approve the the task in order for it to be considered completed. _ `any_assignee` accepts any one assignee to review or approve the the task in order for it to be considered completed. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Task`. Returns the updated task object. ## Remove task Removes a task from a file. This operation is performed by calling function `delete_task_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-tasks-id/). ``` client.tasks.delete_task_by_id(task.id) ``` ### Arguments task_id `str` - The ID of the task. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the task was successfully deleted. --- ## Untitled *Type: page* TermsOfServicesManager List terms of services Create terms of service Get terms of service Update terms of service List terms of services… # TermsOfServicesManager - [List terms of services](#list-terms-of-services) - [Create terms of service](#create-terms-of-service) - [Get terms of service](#get-terms-of-service) - [Update terms of service](#update-terms-of-service) ## List terms of services Returns the current terms of service text and settings for the enterprise. This operation is performed by calling function `get_terms_of_service`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services/). ``` client.terms_of_services.get_terms_of_service() ``` ### Arguments tos_type `Optional[GetTermsOfServiceTosType]` - Limits the results to the terms of service of the given type. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TermsOfServices`. Returns a collection of terms of service text and settings for the enterprise. ## Create terms of service Creates a terms of service for a given enterprise and type of user. This operation is performed by calling function `create_terms_of_service`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-services/). ``` client.terms_of_services.create_terms_of_service( CreateTermsOfServiceStatus.DISABLED, "Test TOS", tos_type=CreateTermsOfServiceTosType.MANAGED, ) ``` ### Arguments status `CreateTermsOfServiceStatus` - Whether this terms of service is active. tos_type `Optional[CreateTermsOfServiceTosType]` - The type of user to set the terms of service for. text `str` - The terms of service text to display to users. The text can be set to empty if the `status` is set to `disabled`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TermsOfService`. Returns a new task object. ## Get terms of service Fetches a specific terms of service. This operation is performed by calling function `get_terms_of_service_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services-id/). *Currently we don't have an example for calling `get_terms_of_service_by_id` in integration tests* ### Arguments terms_of_service_id `str` - The ID of the terms of service. Example: "324234" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TermsOfService`. Returns a terms of service object. ## Update terms of service Updates a specific terms of service. This operation is performed by calling function `update_terms_of_service_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-services-id/). ``` client.terms_of_services.update_terms_of_service_by_id( tos.id, UpdateTermsOfServiceByIdStatus.DISABLED, "TOS" ) ``` ### Arguments terms_of_service_id `str` - The ID of the terms of service. Example: "324234" status `UpdateTermsOfServiceByIdStatus` - Whether this terms of service is active. text `str` - The terms of service text to display to users. The text can be set to empty if the `status` is set to `disabled`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TermsOfService`. Returns an updated terms of service object. --- ## Untitled *Type: page* TransferManager Transfer owned folders Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into… # TransferManager - [Transfer owned folders](#transfer-owned-folders) ## Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into another user's account Only the root folder (`0`) can be transferred. Folders can only be moved across users by users with administrative permissions. All existing shared links and folder-level collaborations are transferred during the operation. Please note that while collaborations at the individual file-level are transferred during the operation, the collaborations are deleted when the original user is deleted. If the user has a large number of items across all folders, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. If the destination path has a metadata cascade policy attached to any of the parent folders, a metadata cascade operation will be kicked off asynchronously. There is currently no way to check for when this operation is finished. The destination folder's name will be in the format `{User}'s Files and Folders`, where `{User}` is the display name of the user. To make this API call your application will need to have the "Read and write all files and folders stored in Box" scope enabled. Please make sure the destination user has access to `Relay` or `Relay Lite`, and has access to the files and folders involved in the workflows being transferred. Admins will receive an email when the operation is completed. This operation is performed by calling function `transfer_owned_folder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id-folders-0/). ``` client.transfer.transfer_owned_folder( source_user.id, TransferOwnedFolderOwnedBy(id=target_user.id), notify=False ) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" owned_by `TransferOwnedFolderOwnedBy` - The user who the folder will be transferred to. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. notify `Optional[bool]` - Determines if users should receive email notification for the action performed. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `FolderFull`. Returns the information for the newly created destination folder. --- ## Untitled *Type: page* TrashedItemsManager List trashed items List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute… # TrashedItemsManager - [List trashed items](#list-trashed-items) ## List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute in the full files or folders objects can be passed in with the `fields` parameter to retrieve those specific attributes that are not returned by default. This endpoint defaults to use offset-based pagination, yet also supports marker-based pagination using the `marker` parameter. This operation is performed by calling function `get_trashed_items`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-trash-items/). ``` client.trashed_items.get_trashed_items() ``` ### Arguments fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. limit `Optional[int]` - The maximum number of items to return per page. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. usemarker `Optional[bool]` - Specifies whether to use marker-based pagination instead of offset-based pagination. Only one pagination method can be used at a time. By setting this value to true, the API will return a `marker` field that can be passed as a parameter to this endpoint to get the next page of the response. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. direction `Optional[GetTrashedItemsDirection]` - The direction to sort results in. This can be either in alphabetical ascending (`ASC`) or descending (`DESC`) order. sort `Optional[GetTrashedItemsSort]` - Defines the **second** attribute by which items are sorted. Items are always sorted by their `type` first, with folders listed before files, and files listed before web links. This parameter is not supported when using marker-based pagination. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Items`. Returns a list of items that have been deleted. --- ## Untitled *Type: page* TrashedFilesManager Restore file Get trashed file Permanently remove file Restore file Restores a file that has been moved to the trash. An… # TrashedFilesManager - [Restore file](#restore-file) - [Get trashed file](#get-trashed-file) - [Permanently remove file](#permanently-remove-file) ## Restore file Restores a file that has been moved to the trash. An optional new parent ID can be provided to restore the file to in case the original folder has been deleted. This operation is performed by calling function `restore_file_from_trash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id/). ``` client.trashed_files.restore_file_from_trash(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" name `Optional[str]` - An optional new name for the file. parent `Optional[RestoreFileFromTrashParent]` fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TrashFileRestored`. Returns a file object when the file has been restored. ## Get trashed file Retrieves a file that has been moved to the trash. Please note that only if the file itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `get_trashed_file_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-trash/). ``` client.trashed_files.get_trashed_file_by_id(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TrashFile`. Returns the file that was trashed, including information about when the it was moved to the trash. ## Permanently remove file Permanently deletes a file that is in the trash. This action cannot be undone. This operation is performed by calling function `delete_trashed_file_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-trash/). ``` client.trashed_files.delete_trashed_file_by_id(file.id) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the file was permanently deleted. --- ## Untitled *Type: page* TrashedWebLinksManager Restore web link Get trashed web link Permanently remove web link Restore web link Restores a web link that has been… # TrashedWebLinksManager - [Restore web link](#restore-web-link) - [Get trashed web link](#get-trashed-web-link) - [Permanently remove web link](#permanently-remove-web-link) ## Restore web link Restores a web link that has been moved to the trash. An optional new parent ID can be provided to restore the web link to in case the original folder has been deleted. This operation is performed by calling function `restore_weblink_from_trash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links-id/). ``` client.trashed_web_links.restore_weblink_from_trash(weblink.id) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" name `Optional[str]` - An optional new name for the web link. parent `Optional[RestoreWeblinkFromTrashParent]` fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TrashWebLinkRestored`. Returns a web link object when it has been restored. ## Get trashed web link Retrieves a web link that has been moved to the trash. This operation is performed by calling function `get_trashed_web_link_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id-trash/). ``` client.trashed_web_links.get_trashed_web_link_by_id(weblink.id) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TrashWebLink`. Returns the web link that was trashed, including information about when the it was moved to the trash. ## Permanently remove web link Permanently deletes a web link that is in the trash. This action cannot be undone. This operation is performed by calling function `delete_trashed_web_link_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id-trash/). ``` client.trashed_web_links.delete_trashed_web_link_by_id(weblink.id) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the web link was permanently deleted. --- ## Untitled *Type: page* TrashedFoldersManager Restore folder Get trashed folder Permanently remove folder Restore folder Restores a folder that has been moved to… # TrashedFoldersManager - [Restore folder](#restore-folder) - [Get trashed folder](#get-trashed-folder) - [Permanently remove folder](#permanently-remove-folder) ## Restore folder Restores a folder that has been moved to the trash. An optional new parent ID can be provided to restore the folder to in case the original folder has been deleted. During this operation, part of the file tree will be locked, mainly the source folder and all of its descendants, as well as the destination folder. For the duration of the operation, no other move, copy, delete, or restore operation can performed on any of the locked folders. This operation is performed by calling function `restore_folder_from_trash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id/). ``` client.trashed_folders.restore_folder_from_trash(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" name `Optional[str]` - An optional new name for the folder. parent `Optional[RestoreFolderFromTrashParent]` fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TrashFolderRestored`. Returns a folder object when the folder has been restored. ## Get trashed folder Retrieves a folder that has been moved to the trash. Please note that only if the folder itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `get_trashed_folder_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-trash/). ``` client.trashed_folders.get_trashed_folder_by_id(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `TrashFolder`. Returns the folder that was trashed, including information about when the it was moved to the trash. ## Permanently remove folder Permanently deletes a folder that is in the trash. This action cannot be undone. This operation is performed by calling function `delete_trashed_folder_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-trash/). ``` client.trashed_folders.delete_trashed_folder_by_id(folder.id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Returns an empty response when the folder was permanently deleted. --- ## Untitled *Type: page* UploadsManager Upload file version Preflight check before upload Upload file Upload a file with a preflight check Upload file version Update… # UploadsManager - [Upload file version](#upload-file-version) - [Preflight check before upload](#preflight-check-before-upload) - [Upload file](#upload-file) - [Upload a file with a preflight check](#upload-a-file-with-a-preflight-check) ## Upload file version Update a file's content. For file sizes over 50MB we recommend using the Chunk Upload APIs. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. This operation is performed by calling function `upload_file_version`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-content/). ``` client.uploads.upload_file_version( uploaded_file.id, UploadFileVersionAttributes(name=new_file_version_name), new_file_content_stream, ) ``` ### Arguments file_id `str` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" attributes `UploadFileVersionAttributes` - The additional attributes of the file being uploaded. Mainly the name and the parent folder. These attributes are part of the multi part request body and are in JSON format. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. file `ByteStream` - The content of the file to upload to Box. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. file_file_name `Optional[str]` file_content_type `Optional[str]` fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. if_match `Optional[str]` - Ensures this item hasn't recently changed before making changes. Pass in the item's last observed `etag` value into this header and the endpoint will fail with a `412 Precondition Failed` if it has changed since. content_md_5 `Optional[str]` - An optional header containing the SHA1 hash of the file to ensure that the file was not corrupted in transit. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Files`. Returns the new file object in a list. ## Preflight check before upload Performs a check to verify that a file will be accepted by Box before you upload the entire file. This operation is performed by calling function `preflight_file_upload_check`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-files-content/). ``` client.uploads.preflight_file_upload_check( name=new_file_name, size=1024 * 1024, parent=PreflightFileUploadCheckParent(id="0") ) ``` ### Arguments name `Optional[str]` - The name for the file. size `Optional[int]` - The size of the file in bytes. parent `Optional[PreflightFileUploadCheckParent]` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UploadUrl`. If the check passed, the response will include a session URL that can be used to upload the file to. ## Upload file Uploads a small file to Box. For file sizes over 50MB we recommend using the Chunk Upload APIs. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. This operation is performed by calling function `upload_file`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-content/). ``` client.uploads.upload_file( UploadFileAttributes( name=new_file_name, parent=UploadFileAttributesParentField(id="0") ), file_content_stream, ) ``` ### Arguments attributes `UploadFileAttributes` - The additional attributes of the file being uploaded. Mainly the name and the parent folder. These attributes are part of the multi part request body and are in JSON format. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. file `ByteStream` - The content of the file to upload to Box. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. file_file_name `Optional[str]` file_content_type `Optional[str]` fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. content_md_5 `Optional[str]` - An optional header containing the SHA1 hash of the file to ensure that the file was not corrupted in transit. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Files`. Returns the new file object in a list. ## Upload a file with a preflight check Upload a file with a preflight check This operation is performed by calling function `upload_with_preflight_check`. ``` client.uploads.upload_with_preflight_check( UploadWithPreflightCheckAttributes( name=new_file_name, size=-1, parent=UploadWithPreflightCheckAttributesParentField(id="0"), ), file_content_stream, ) ``` ### Arguments - attributes `UploadWithPreflightCheckAttributes` file `ByteStream` - The content of the file to upload to Box. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. file_file_name `Optional[str]` file_content_type `Optional[str]` fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. content_md_5 `Optional[str]` - An optional header containing the SHA1 hash of the file to ensure that the file was not corrupted in transit. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Files`. --- ## Untitled *Type: page* UserCollaborationsManager Get collaboration Update collaboration Remove collaboration Create collaboration Get collaboration Retrieves a… # UserCollaborationsManager - [Get collaboration](#get-collaboration) - [Update collaboration](#update-collaboration) - [Remove collaboration](#remove-collaboration) - [Create collaboration](#create-collaboration) ## Get collaboration Retrieves a single collaboration. This operation is performed by calling function `get_collaboration_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations-id/). ``` client.user_collaborations.get_collaboration_by_id(collaboration_id) ``` ### Arguments collaboration_id `str` - The ID of the collaboration. Example: "1234" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Collaboration`. Returns a collaboration object. ## Update collaboration Updates a collaboration. Can be used to change the owner of an item, or to accept collaboration invites. This operation is performed by calling function `update_collaboration_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-collaborations-id/). ``` client.user_collaborations.update_collaboration_by_id( collaboration_id, UpdateCollaborationByIdRole.VIEWER ) ``` ### Arguments collaboration_id `str` - The ID of the collaboration. Example: "1234" role `UpdateCollaborationByIdRole` - The level of access granted. status `Optional[UpdateCollaborationByIdStatus]` - Set the status of a `pending` collaboration invitation, effectively accepting, or rejecting the invite. expires_at `Optional[DateTime]` - Update the expiration date for the collaboration. At this date, the collaboration will be automatically removed from the item. This feature will only work if the **Automatically remove invited collaborators: Allow folder owners to extend the expiry date** setting has been enabled in the **Enterprise Settings** of the **Admin Console**. When the setting is not enabled, collaborations can not have an expiry date and a value for this field will be result in an error. Additionally, a collaboration can only be given an expiration if it was created after the **Automatically remove invited collaborator** setting was enabled. can_view_path `Optional[bool]` - Determines if the invited users can see the entire parent path to the associated folder. The user will not gain privileges in any parent folder and therefore can not see content the user is not collaborated on. Be aware that this meaningfully increases the time required to load the invitee's **All Files** page. We recommend you limit the number of collaborations with `can_view_path` enabled to 1,000 per user. Only owner or co-owners can invite collaborators with a `can_view_path` of `true`. `can_view_path` can only be used for folder collaborations. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Optional[Collaboration]`. Returns an updated collaboration object unless the owner has changed.If the role is changed to `owner`, the collaboration is deleted and a new collaboration is created. The previous `owner` of the old collaboration will be a `co-owner` on the new collaboration. ## Remove collaboration Deletes a single collaboration. This operation is performed by calling function `delete_collaboration_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaborations-id/). ``` client.user_collaborations.delete_collaboration_by_id(collaboration_id) ``` ### Arguments collaboration_id `str` - The ID of the collaboration. Example: "1234" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. A blank response is returned if the collaboration was successfully deleted. ## Create collaboration Adds a collaboration for a single user or a single group to a file or folder. Collaborations can be created using email address, user IDs, or a group IDs. If a collaboration is being created with a group, access to this endpoint is dependent on the group's ability to be invited. If collaboration is in `pending` status, the following fields are redacted: `login` and `name` are hidden if a collaboration was created using `user_id`, - `name` is hidden if a collaboration was created using `login`. This operation is performed by calling function `create_collaboration`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaborations/). ``` client.user_collaborations.create_collaboration( CreateCollaborationItem(type=CreateCollaborationItemTypeField.FOLDER, id=folder.id), CreateCollaborationAccessibleBy( type=CreateCollaborationAccessibleByTypeField.USER, id=user.id ), CreateCollaborationRole.EDITOR, ) ``` ### Arguments item `CreateCollaborationItem` - The item to attach the comment to. accessible_by `CreateCollaborationAccessibleBy` - The user or group to give access to the item. role `CreateCollaborationRole` - The level of access granted. is_access_only `Optional[bool]` - If set to `true`, collaborators have access to shared items, but such items won't be visible in the All Files list. Additionally, collaborators won't see the the path to the root folder for the shared item. can_view_path `Optional[bool]` - Determines if the invited users can see the entire parent path to the associated folder. The user will not gain privileges in any parent folder and therefore can not see content the user is not collaborated on. Be aware that this meaningfully increases the time required to load the invitee's **All Files** page. We recommend you limit the number of collaborations with `can_view_path` enabled to 1,000 per user. Only owner or co-owners can invite collaborators with a `can_view_path` of `true`. `can_view_path` can only be used for folder collaborations. expires_at `Optional[DateTime]` - Set the expiration date for the collaboration. At this date, the collaboration will be automatically removed from the item. This feature will only work if the **Automatically remove invited collaborators: Allow folder owners to extend the expiry date** setting has been enabled in the **Enterprise Settings** of the **Admin Console**. When the setting is not enabled, collaborations can not have an expiry date and a value for this field will be result in an error. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. notify `Optional[bool]` - Determines if users should receive email notification for the action performed. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Collaboration`. Returns a new collaboration object. --- ## Untitled *Type: page* UsersManager List enterprise users Create user Get current user Get user Update user Delete user List enterprise users Returns a list of all… # UsersManager - [List enterprise users](#list-enterprise-users) - [Create user](#create-user) - [Get current user](#get-current-user) - [Get user](#get-user) - [Update user](#update-user) - [Delete user](#delete-user) ## List enterprise users Returns a list of all users for the Enterprise along with their `user_id`, `public_name`, and `login`. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This operation is performed by calling function `get_users`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users/). ``` client.users.get_users() ``` ### Arguments filter_term `Optional[str]` - Limits the results to only users who's `name` or `login` start with the search term. For externally managed users, the search term needs to completely match the in order to find the user, and it will only return one user at a time. user_type `Optional[GetUsersUserType]` - Limits the results to the kind of user specified. _ `all` returns every kind of user for whom the `login` or `name` partially matches the `filter_term`. It will only return an external user if the login matches the `filter_term` completely, and in that case it will only return that user. _ `managed` returns all managed and app users for whom the `login` or `name` partially matches the `filter_term`. * `external` returns all external users for whom the `login` matches the `filter_term` exactly. external_app_user_id `Optional[str]` - Limits the results to app users with the given `external_app_user_id` value. When creating an app user, an `external_app_user_id` value can be set. This value can then be used in this endpoint to find any users that match that `external_app_user_id` value. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. offset `Optional[int]` - The offset of the item at which to begin the response. Queries with offset parameter value exceeding 10000 will be rejected with a 400 response. limit `Optional[int]` - The maximum number of items to return per page. usemarker `Optional[bool]` - Specifies whether to use marker-based pagination instead of offset-based pagination. Only one pagination method can be used at a time. By setting this value to true, the API will return a `marker` field that can be passed as a parameter to this endpoint to get the next page of the response. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Users`. Returns all of the users in the enterprise. ## Create user Creates a new managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `create_user`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users/). ``` client.users.create_user(user_name, login=user_login, is_platform_access_only=True) ``` ### Arguments name `str` - The name of the user. login `Optional[str]` - The email address the user uses to log in Required, unless `is_platform_access_only` is set to `true`. is_platform_access_only `Optional[bool]` - Specifies that the user is an app user. role `Optional[CreateUserRole]` - The user’s enterprise role. language `Optional[str]` - The language of the user, formatted in modified version of the [ISO 639-1](https://developer.box.com/guides/api-calls/language-codes) format. is_sync_enabled `Optional[bool]` - Whether the user can use Box Sync. job_title `Optional[str]` - The user’s job title. phone `Optional[str]` - The user’s phone number. address `Optional[str]` - The user’s address. space_amount `Optional[int]` - The user’s total available space in bytes. Set this to `-1` to indicate unlimited storage. tracking_codes `Optional[List[TrackingCode]]` - Tracking codes allow an admin to generate reports from the admin console and assign an attribute to a specific group of users. This setting must be enabled for an enterprise before it can be used. can_see_managed_users `Optional[bool]` - Whether the user can see other enterprise users in their contact list. timezone `Optional[str]` - The user's timezone. is_external_collab_restricted `Optional[bool]` - Whether the user is allowed to collaborate with users outside their enterprise. is_exempt_from_device_limits `Optional[bool]` - Whether to exempt the user from enterprise device limits. is_exempt_from_login_verification `Optional[bool]` - Whether the user must use two-factor authentication. status `Optional[CreateUserStatus]` - The user's account status. external_app_user_id `Optional[str]` - An external identifier for an app user, which can be used to look up the user. This can be used to tie user IDs from external identity providers to Box users. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UserFull`. Returns a user object for the newly created user. ## Get current user Retrieves information about the user who is currently authenticated. In the case of a client-side authenticated OAuth 2.0 application this will be the user who authorized the app. In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default. Use the `As-User` header to change who this API call is made on behalf of. This operation is performed by calling function `get_user_me`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-me/). ``` client.users.get_user_me() ``` ### Arguments fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UserFull`. Returns a single user object. ## Get user Retrieves information about a user in the enterprise. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This endpoint also returns a limited set of information for external users who are collaborated on content owned by the enterprise for authenticated users with the right scopes. In this case, disallowed fields will return null instead. This operation is performed by calling function `get_user_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id/). ``` client.users.get_user_by_id(user.id) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UserFull`. Returns a single user object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields using the [fields](#get-users-id--request--fields) parameter. ## Update user Updates a managed or app user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `update_user_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id/). ``` client.users.update_user_by_id(user.id, name=updated_user_name) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" enterprise `Optional[str]` - Set this to `null` to roll the user out of the enterprise and make them a free user. notify `Optional[bool]` - Whether the user should receive an email when they are rolled out of an enterprise. name `Optional[str]` - The name of the user. login `Optional[str]` - The email address the user uses to log in Note: If the target user's email is not confirmed, then the primary login address cannot be changed. role `Optional[UpdateUserByIdRole]` - The user’s enterprise role. language `Optional[str]` - The language of the user, formatted in modified version of the [ISO 639-1](https://developer.box.com/guides/api-calls/language-codes) format. is_sync_enabled `Optional[bool]` - Whether the user can use Box Sync. job_title `Optional[str]` - The user’s job title. phone `Optional[str]` - The user’s phone number. address `Optional[str]` - The user’s address. tracking_codes `Optional[List[TrackingCode]]` - Tracking codes allow an admin to generate reports from the admin console and assign an attribute to a specific group of users. This setting must be enabled for an enterprise before it can be used. can_see_managed_users `Optional[bool]` - Whether the user can see other enterprise users in their contact list. timezone `Optional[str]` - The user's timezone. is_external_collab_restricted `Optional[bool]` - Whether the user is allowed to collaborate with users outside their enterprise. is_exempt_from_device_limits `Optional[bool]` - Whether to exempt the user from enterprise device limits. is_exempt_from_login_verification `Optional[bool]` - Whether the user must use two-factor authentication. is_password_reset_required `Optional[bool]` - Whether the user is required to reset their password. status `Optional[UpdateUserByIdStatus]` - The user's account status. space_amount `Optional[int]` - The user’s total available space in bytes. Set this to `-1` to indicate unlimited storage. notification_email `Optional[UpdateUserByIdNotificationEmail]` - An alternate notification email address to which email notifications are sent. When it's confirmed, this will be the email address to which notifications are sent instead of to the primary email address. Set this value to `null` to remove the notification email. external_app_user_id `Optional[str]` - An external identifier for an app user, which can be used to look up the user. This can be used to tie user IDs from external identity providers to Box users. Note: In order to update this field, you need to request a token using the application that created the app user. fields `Optional[List[str]]` - A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response. Be aware that specifying this parameter will have the effect that none of the standard fields are returned in the response unless explicitly specified, instead only fields for the mini representation are returned, additional to the fields requested. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `UserFull`. Returns the updated user object. ## Delete user Deletes a user. By default this will fail if the user still owns any content. Move their owned content first before proceeding, or use the `force` field to delete the user and their files. This operation is performed by calling function `delete_user_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id/). ``` client.users.delete_user_by_id(user.id) ``` ### Arguments user_id `str` - The ID of the user. Example: "12345" notify `Optional[bool]` - Whether the user will receive email notification of the deletion. force `Optional[bool]` - Whether the user should be deleted even if this user still own files. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Removes the user and returns an empty response. --- ## Untitled *Type: page* WebLinksManager Create web link Get web link Update web link Remove web link Create web link Creates a web link object within a folder. This… # WebLinksManager - [Create web link](#create-web-link) - [Get web link](#get-web-link) - [Update web link](#update-web-link) - [Remove web link](#remove-web-link) ## Create web link Creates a web link object within a folder. This operation is performed by calling function `create_web_link`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links/). ``` client.web_links.create_web_link( "https://www.box.com", CreateWebLinkParent(id=parent.id), name=get_uuid(), description="Weblink description", ) ``` ### Arguments url `str` - The URL that this web link links to. Must start with `"http://"` or `"https://"`. parent `CreateWebLinkParent` - The parent folder to create the web link within. name `Optional[str]` - Name of the web link. Defaults to the URL if not set. description `Optional[str]` - Description of the web link. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `WebLink`. Returns the newly created web link object. ## Get web link Retrieve information about a web link. This operation is performed by calling function `get_web_link_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id/). ``` client.web_links.get_web_link_by_id(weblink.id) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" boxapi `Optional[str]` - The URL, and optional password, for the shared link of this item. This header can be used to access items that have not been explicitly shared with a user. Use the format `shared_link=[link]` or if a password is required then use `shared_link=[link]&shared_link_password=[password]`. This header can be used on the file or folder shared, as well as on any files or folders nested within the item. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `WebLink`. Returns the web link object. ## Update web link Updates a web link object. This operation is performed by calling function `update_web_link_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id/). ``` client.web_links.update_web_link_by_id( weblink.id, name=updated_name, shared_link=UpdateWebLinkByIdSharedLink( access=UpdateWebLinkByIdSharedLinkAccessField.OPEN, password=password ), ) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" url `Optional[str]` - The new URL that the web link links to. Must start with `"http://"` or `"https://"`. parent `Optional[UpdateWebLinkByIdParent]` name `Optional[str]` - A new name for the web link. Defaults to the URL if not set. description `Optional[str]` - A new description of the web link. shared_link `Optional[UpdateWebLinkByIdSharedLink]` - The settings for the shared link to update. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `WebLink`. Returns the updated web link object. ## Remove web link Deletes a web link. This operation is performed by calling function `delete_web_link_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id/). ``` client.web_links.delete_web_link_by_id(web_link_id) ``` ### Arguments web_link_id `str` - The ID of the web link. Example: "12345" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. An empty response will be returned when the web link was successfully deleted. --- ## Untitled *Type: page* WebhooksManager List all webhooks Create webhook Get webhook Update webhook Remove webhook Validate a webhook message List all webhooks… # WebhooksManager - [List all webhooks](#list-all-webhooks) - [Create webhook](#create-webhook) - [Get webhook](#get-webhook) - [Update webhook](#update-webhook) - [Remove webhook](#remove-webhook) - [Validate a webhook message](#validate-a-webhook-message) ## List all webhooks Returns all defined webhooks for the requesting application. This API only returns webhooks that are applied to files or folders that are owned by the authenticated user. This means that an admin can not see webhooks created by a service account unless the admin has access to those folders, and vice versa. This operation is performed by calling function `get_webhooks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks/). ``` client.webhooks.get_webhooks() ``` ### Arguments marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. limit `Optional[int]` - The maximum number of items to return per page. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Webhooks`. Returns a list of webhooks. ## Create webhook Creates a webhook. This operation is performed by calling function `create_webhook`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-webhooks/). ``` client.webhooks.create_webhook( CreateWebhookTarget(id=folder.id, type=CreateWebhookTargetTypeField.FOLDER), "https://example.com/new-webhook", [CreateWebhookTriggers.FILE_UPLOADED], ) ``` ### Arguments target `CreateWebhookTarget` - The item that will trigger the webhook. address `str` - The URL that is notified by this webhook. triggers `List[CreateWebhookTriggers]` - An array of event names that this webhook is to be triggered for. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Get webhook Retrieves a specific webhook. This operation is performed by calling function `get_webhook_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks-id/). ``` client.webhooks.get_webhook_by_id(webhook.id) ``` ### Arguments webhook_id `str` - The ID of the webhook. Example: "3321123" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Webhook`. Returns a webhook object. ## Update webhook Updates a webhook. This operation is performed by calling function `update_webhook_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-webhooks-id/). ``` client.webhooks.update_webhook_by_id( webhook.id, address="https://example.com/updated-webhook" ) ``` ### Arguments webhook_id `str` - The ID of the webhook. Example: "3321123" target `Optional[UpdateWebhookByIdTarget]` - The item that will trigger the webhook. address `Optional[str]` - The URL that is notified by this webhook. triggers `Optional[List[UpdateWebhookByIdTriggers]]` - An array of event names that this webhook is to be triggered for. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Remove webhook Deletes a webhook. This operation is performed by calling function `delete_webhook_by_id`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-webhooks-id/). ``` client.webhooks.delete_webhook_by_id(webhook.id) ``` ### Arguments webhook_id `str` - The ID of the webhook. Example: "3321123" extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. An empty response will be returned when the webhook was successfully deleted. ## Validate a webhook message Validate a webhook message by verifying the signature and the delivery timestamp This operation is performed by calling function `validate_message`. ``` WebhooksManager.validate_message( body, headers_with_correct_datetime, primary_key, secondary_key=secondary_key ) ``` ### Arguments body `str` - The request body of the webhook message headers `Dict[str, str]` - The headers of the webhook message primary_key `str` - The primary signature to verify the message with secondary_key `Optional[str]` - The secondary signature to verify the message with max_age `Optional[int]` - The maximum age of the message in seconds, defaults to 10 minutes ### Returns This function returns a value of type `bool`. --- ## Untitled *Type: page* Handling null values in Box Python SDK Gen While using Box Python SDK it's important to understand how null values behave. This document… # Handling null values in Box Python SDK Gen While using Box Python SDK it's important to understand how null values behave. This document provides a general overview of null value behaviour in Box Python SDK to help developers manage data consistently and predictably. ## Understanding null behaviour The Box Python SDK follows a consistent pattern when handling null values in update operations. This behaviour applies to most endpoints that modify resources such as users, files, folders and metadata. The updating field behaves differently depending on weather you omit it, set it to null, or provide a value: - Omitting the field: The field won't be included in request and the value will remain unchanged. - Setting it to null: Setting a field to null, will cause sending HTTP request with field value set to null, what will result in removing its current value or disassociates it from the resource. - Providing a value: Providing a non-null value assigns or updates the field to that value. ## Example Usage The client.files.update_file_by_id() method demonstrates null handling when modifying the lock field while updating the file: ``` import null from box_sdk_gen def createUpdateFile(client): uploaded_file_id = '12345' # locking the file file_with_lock = client.files.update_file_by_id( uploaded_file_id, lock=UpdateFileByIdLock(access=UpdateFileByIdLockAccessField.LOCK), fields=['lock'], ) # unlocking the file using lock value as null file_without_lock = client.files.update_file_by_id( uploaded_file_id, lock=null, fields=['lock'] ) ``` ## Summary To summarize, if you omit the field, the field remains unchanged. If you set it to null, it clears/removes the value. If you provide a value to that field, the field gets updated to that specified value. --- ## Untitled *Type: page* WorkflowsManager List workflows Starts workflow based on request body List workflows Returns list of workflows that act on a given folder ID… # WorkflowsManager - [List workflows](#list-workflows) - [Starts workflow based on request body](#starts-workflow-based-on-request-body) ## List workflows Returns list of workflows that act on a given `folder ID`, and have a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in to use this endpoint. This operation is performed by calling function `get_workflows`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-workflows/). ``` admin_client.workflows.get_workflows(workflow_folder_id) ``` ### Arguments folder_id `str` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. trigger_type `Optional[str]` - Type of trigger to search for. limit `Optional[int]` - The maximum number of items to return per page. marker `Optional[str]` - Defines the position marker at which to begin returning results. This is used when paginating using marker-based pagination. This requires `usemarker` to be set to `true`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `Workflows`. Returns the workflow. ## Starts workflow based on request body Initiates a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console. This operation is performed by calling function `start_workflow`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-workflows-id-start/). ``` admin_client.workflows.start_workflow( workflow_to_run.id, StartWorkflowFlow(type="flow", id=workflow_to_run.flows[0].id), [StartWorkflowFiles(type=StartWorkflowFilesTypeField.FILE, id=workflow_file_id)], StartWorkflowFolder( type=StartWorkflowFolderTypeField.FOLDER, id=workflow_folder_id ), type=StartWorkflowType.WORKFLOW_PARAMETERS, ) ``` ### Arguments workflow_id `str` - The ID of the workflow. Example: "12345" type `Optional[StartWorkflowType]` - The type of the parameters object. flow `StartWorkflowFlow` - The flow that will be triggered. files `List[StartWorkflowFiles]` - The array of files for which the workflow should start. All files must be in the workflow's configured folder. folder `StartWorkflowFolder` - The folder object for which the workflow is configured. outcomes `Optional[List[Outcome]]` - A configurable outcome the workflow should complete. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `None`. Starts the workflow. --- ## Untitled *Type: page* ZipDownloadsManager Create zip download Download zip archive Get zip download status Download ZIP Create zip download Creates a request to… # ZipDownloadsManager - [Create zip download](#create-zip-download) - [Download zip archive](#download-zip-archive) - [Get zip download status](#get-zip-download-status) - [Download ZIP](#download-zip) ## Create zip download Creates a request to download multiple files and folders as a single `zip` archive file. This API does not return the archive but instead performs all the checks to ensure that the user has access to all the items, and then returns a `download_url` and a `status_url` that can be used to download the archive. The limit for an archive is either the Account's upload limit or 10,000 files, whichever is met first. **Note**: Downloading a large file can be affected by various factors such as distance, network latency, bandwidth, and congestion, as well as packet loss ratio and current server load. For these reasons we recommend that a maximum ZIP archive total size does not exceed 25GB. This operation is performed by calling function `create_zip_download`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-zip-downloads/). ``` client.zip_downloads.create_zip_download( [ CreateZipDownloadItems(id=file_1.id, type=DownloadZipItemsTypeField.FILE), CreateZipDownloadItems(id=file_2.id, type=DownloadZipItemsTypeField.FILE), CreateZipDownloadItems(id=folder_1.id, type=DownloadZipItemsTypeField.FOLDER), ], download_file_name="zip", ) ``` ### Arguments items `List[CreateZipDownloadItems]` - A list of items to add to the `zip` archive. These can be folders or files. download_file_name `Optional[str]` - The optional name of the `zip` archive. This name will be appended by the `.zip` file extension, for example `January Financials.zip`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ZipDownload`. If the `zip` archive is ready to be downloaded, the API will return a response that will include a `download_url`, a `status_url`, as well as any conflicts that might have occurred when creating the request. ## Download zip archive Returns the contents of a `zip` archive in binary format. This URL does not require any form of authentication and could be used in a user's browser to download the archive to a user's device. By default, this URL is only valid for a few seconds from the creation of the request for this archive. Once a download has started it can not be stopped and resumed, instead a new request for a zip archive would need to be created. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `download_url` field in the response to this endpoint. This operation is performed by calling function `get_zip_download_content`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-content/). ``` client.zip_downloads.get_zip_download_content(zip_download.download_url) ``` ### Arguments download_url `str` - The URL that can be used to download created `zip` archive. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ByteStream`. Returns the content of the items requested for this download, formatted as a stream of files and folders in a `zip` archive. ## Get zip download status Returns the download status of a `zip` archive, allowing an application to inspect the progress of the download as well as the number of items that might have been skipped. This endpoint can only be accessed once the download has started. Subsequently this endpoint is valid for 12 hours from the start of the download. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `status_url` field in the response to this endpoint. This operation is performed by calling function `get_zip_download_status`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-status/). ``` client.zip_downloads.get_zip_download_status(zip_download.status_url) ``` ### Arguments status_url `str` - The URL that can be used to get the status of the `zip` archive being downloaded. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status` extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ZipDownloadStatus`. Returns the status of the `zip` archive that is being downloaded. ## Download ZIP Creates a zip and downloads its content This operation is performed by calling function `download_zip`. ``` client.zip_downloads.download_zip( [ DownloadZipItems(id=file_1.id, type=DownloadZipItemsTypeField.FILE), DownloadZipItems(id=file_2.id, type=DownloadZipItemsTypeField.FILE), DownloadZipItems(id=folder_1.id, type=DownloadZipItemsTypeField.FOLDER), ], download_file_name="zip", ) ``` ### Arguments items `List[DownloadZipItems]` - A list of items to add to the `zip` archive. These can be folders or files. download_file_name `Optional[str]` - The optional name of the `zip` archive. This name will be appended by the `.zip` file extension, for example `January Financials.zip`. extra_headers `Optional[Dict[str, Optional[str]]]` - Extra headers that will be included in the HTTP request. ### Returns This function returns a value of type `ByteStream`. --- ## Untitled *Type: page* Box Python SDK Gen Project Status build PyPI version image Platform Coverage We are excited to introduce the stable release of the latest… # Box Python SDK Gen [](http://opensource.box.com/badges) [](https://badge.fury.io/py/box-sdk-gen) [](https://pypi.python.org/pypi/box-sdk-gen) [](https://coveralls.io/github/box/box-python-sdk-gen?branch=main) We are excited to introduce the stable release of the latest generation of Box Python SDK, designed to elevate the developer experience and streamline your integration with the Box Content Cloud. With this SDK, you’ll have access to: 1. Full API Support: The new generation of Box SDKs empowers developers with complete coverage of the Box API ecosystem. You can now access all the latest features and functionalities offered by Box, allowing you to build even more sophisticated and feature-rich applications. 2. Rapid API Updates: Say goodbye to waiting for new Box APIs to be incorporated into the SDK. With our new auto-generation development approach, we can now add new Box APIs to the SDK at a much faster pace (in a matter of days). This means you can leverage the most up-to-date features in your applications without delay. 3. Embedded Documentation: We understand that easy access to information is crucial for developers. With our new approach, we have included comprehensive documentation for all objects and parameters directly in the source code of the SDK. This means you no longer need to look up this information on the developer portal, saving you time and streamlining your development process. 4. Enhanced Convenience Methods: Our commitment to enhancing your development experience continues with the introduction of convenience methods. These methods cover various aspects such as chunk uploads, classification, and much more. 5. Seamless Start: The new SDKs integrate essential functionalities like authentication, automatic retries with exponential backoff, exception handling, request cancellation, and type checking, enabling you to focus solely on your application's business logic. Embrace the new generation of Box SDKs and unlock the full potential of the Box Content Cloud. # Table of contents - [Box Python SDK Gen](#box-python-sdk-gen) - [Table of contents](#table-of-contents) - [Installing](#installing) - [Getting Started](#getting-started) - [Documentation](#documentation) - [Upgrades](#upgrades) [Integration Tests](#integration-tests) [Running integration tests locally](#running-integration-tests-locally) - [Create Platform Application](#create-platform-application) - [Export configuration](#export-configuration) - [Running tests](#running-tests) [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) [Copyright and License](#copyright-and-license) # Installing ``` pip install box-sdk-gen ``` This is autogenerated Box SDK version. Supported Python versions are Python 3.8 and above. To install also extra dependencies required for JWT authentication, use command: ``` pip install "box-sdk-gen[jwt]" ``` # Getting Started To get started with the SDK, get a Developer Token from the Configuration page of your app in the Box Developer Console. You can use this token to make test calls for your own Box account. The SDK provides an `BoxDeveloperTokenAuth` class, which allows you to authenticate using your Developer Token. Use instance of `BoxDeveloperTokenAuth` to initialize `BoxClient` object. Using `BoxClient` object you can access managers, which allow you to perform some operations on your Box account. The example below demonstrates how to authenticate with Developer Token and print names of all items inside a root folder. ``` from box_sdk_gen import BoxClient, BoxDeveloperTokenAuth def main(token: str): auth: BoxDeveloperTokenAuth = BoxDeveloperTokenAuth(token=token) client: BoxClient = BoxClient(auth=auth) for item in client.folders.get_folder_items('0').entries: print(item.name) if __name__ == '__main__': main('INSERT YOUR DEVELOPER TOKEN HERE') ``` # Documentation Browse the [docs](https://developer.box.com/d3a5e9bde0b74dc93b9f940067935450/README.md) or see [API Reference](https://developer.box.com/reference/) for more information. # Upgrades Upgrading from our legacy SDKs to the new generation SDKs is a straightforward process. See our [migration guide](https://developer.box.com/f56d27ebd4341fc1865ef46b28548d3e/migration-guide.md) and [changelog](https://developer.box.com/7daad47414f02b4f709aff16ad114fdb/CHANGELOG.md) for more information. # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created in the Box Developer Console with `Server Authentication (with JWT)` selected as authentication method. Once created you can edit properties of the application: - In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. - In section `Advanced Features` enable `Make API calls using the as-user header` and `Generate user access tokens`. Now select `Authorization` and submit application to be reviewed by account admin. ### Export configuration Select `Configuration` tab and in the bottom in the section `App Settings` download your app configuration settings as JSON. 1. Encode configuration file to Base64, e.g. using command: `base64 -i path_to_json_file` 2. Set environment variable: `JWT_CONFIG_BASE_64` with base64 encoded jwt configuration file 3. Set environment variable: `BOX_FILE_REQUEST_ID` with ID of file request already created in the user account, `BOX_EXTERNAL_USER_EMAIL` with email of free external user which not belongs to any enterprise. 4. Set environment variable: `WORKFLOW_FOLDER_ID` with the ID of the Relay workflow that deletes the file that triggered the workflow. The workflow should have a manual start to be able to start it from the API. 5. Set environment variable: `APP_ITEM_ASSOCIATION_FILE_ID` to the ID of the file with associated app item and `APP_ITEM_ASSOCIATION_FOLDER_ID` to the ID of the folder with associated app item. 6. Set environment variable: `APP_ITEM_SHARED_LINK` to the shared link associated with app item. 7. Set environment variable: `SLACK_AUTOMATION_USER_ID` to the ID of the user responsible for the Slack automation, `SLACK_ORG_ID` to the ID of the Slack organization and `SLACK_PARTNER_ITEM_ID` to the ID of the Slack partner item. ### Running tests To run integration tests locally: 1. `pip install -r requirements-test.txt` 2. `pytest` # Questions, Bugs, and Feature Requests? Need to contact us directly? Browse the issues tickets! Or, if that doesn't work, file a new one and we will get back to you. If you have general questions about the Box API, you can post to the [Box Developer Forum](https://forum.box.com/). # Copyright and License Copyright 2023 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - this project is generated using [Box Codegen](https://github.com/box/box-codegen) based on[Box OpenAPI 3.0 Specification](https://github.com/box/box-openapi), so if you want found something you want to change in the generated code, you'll need to modify the codegen project and submit a pull request there. --- ## Untitled *Type: page* Migration guide from boxsdk to box-sdk-gen Introduction Installation Key differences Manager approach Explicitly defined schemas Immutable… # Migration guide from boxsdk to box-sdk-gen - [Introduction](#introduction) - [Installation](#installation) [Key differences](#key-differences) - [Manager approach](#manager-approach) - [Explicitly defined schemas](#explicitly-defined-schemas) - [Immutable design](#immutable-design) [Authentication](#authentication) - [Developer Token](#developer-token) [JWT Auth](#jwt-auth) - [Using JWT configuration file](#using-jwt-configuration-file) - [Providing JWT configuration manually](#providing-jwt-configuration-manually) - [Authenticate user](#authenticate-user) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) [Switching between Service Account and User](#switching-between-service-account-and-user) [OAuth 2.0 Auth](#oauth-20-auth) - [Get Authorization URL](#get-authorization-url) - [Authenticate](#authenticate) [Store token and retrieve token callbacks](#store-token-and-retrieve-token-callbacks) [Downscope token](#downscope-token) [Revoke token](#revoke-token) [Configuration](#configuration) - [As-User header](#as-user-header) - [Custom Base URLs](#custom-base-urls) [Convenience methods](#convenience-methods) - [Webhook validation](#webhook-validation) - [Chunked upload of big files](#chunked-upload-of-big-files) ## Introduction The new `box-sdk-gen` SDK library, which helps Python developers to conveniently integrate with Box API. In the contrary to the previous library (`boxsdk`), it is not manually maintained, but auto-generated based on Open API Specification. This means you can leverage the most up-to-date Box API features in your applications without delay. More information and benefits of using the new can be found in the [README](https://github.com/box/box-python-sdk-gen/blob/main/README.md) file. ## Installation To install a new Box Python SDK GENERATED use command: ``` pip install box-sdk-gen ``` The new Box Python SDK GENERATED library could be used in the same project along with the legacy one. If you want to use a feature available only in the new SDK, you don't need to necessarily migrate all your code to use Box Python SDK GENERATED at once. You can use a new feature from the new library, while keeping the rest of your code unchanged. Note that it may be required to alias some imported names from the new SDK to avoid conflicts with the old one. However, we recommend to fully migrate to the new SDK eventually. ## Key differences ### Manager approach The main difference between the old SDK and the new one is the way how API methods are aggregated into objects. **Old (`boxsdk`)** Firstly, in the old SDK to be able to perform any action on an API object, e.g. `User`, you first had to create its class. To do it is required to call: ``` user = client.user(user_id='123456') ``` to create a class representing an already existing User with id '12345', or create a new one with a call: ``` user = client.create_user(name='Some User') ``` Then, you could perform any action on created class, which will affect the user, e.g. ``` updated_user = user.update_info(data={'name': 'New User Name'}) ``` **New (`box-sdk-gen`)** In the new SDK the API methods are grouped into dedicated manager classes, e.g. `User` object has dedicated `UserManager` class. Each manager class instance is available in `BoxClient` object. The fields storing references to the managers are named in the plural form of the resource that the manager handles - `client.users` for `UsersManager`. If you want to perform any operation connected with a `User` you need to call a respective method of `UserManager`. For example, to get info about existing user you need to call: ``` user = client.users.get_user_by_id(user_id='123456') ``` or to create a new user: ``` user = client.users.create_user(name='Some User') ``` The `User` object returned by both of these methods is a data class - it does not contain any methods to call. To perform any action on `User` object, you need to still use a `UserManager` method for that. Usually these methods have a first argument, which accepts id of the object you want to access, e.g. to update a user name, call method: ``` updated_user = client.users.update_user_by_id(user_id=user.id, name='New User Name') ``` ### Explicitly defined schemas **Old (`boxsdk`)** In the old SDK there were no data types explicitly defined - the responses were dynamically mapped into classes in the runtime. For example, if you get information about a file: ``` file = client.file(file_id='12345678').get() ``` you couldn't be sure which fields to expect in the response object until the runtime, because `File` class doesn't have any predefined fields. **New (`box-sdk-gen`)** In the new SDK the data classe are defined in `schemas` module, so you know, which fields to expect before actually making a call. For example `FileBase` class is defined this way: ``` class FileBase(BaseObject): def __init__(self, id: str, *, etag: Optional[str] = None, type: FileBaseTypeField = FileBaseTypeField.FILE.value, **kwargs): super().__init__(**kwargs) self.id = id self.type = type self.etag = etag ``` ### Immutable design The new SDK is designed to be mostly immutable. This means that methods, which used to modify the existing object in old SDK now return a new instance of the class with the modified state. This design pattern is used to avoid side effects and make the code more predictable and easier to reason about. Methods, which returns a new modified instance of an object, will always have a prefix `with_` in their names, e.g. **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxClient as_user_client: BoxClient = client.with_as_user_header('USER_ID') ``` ## Authentication The Box Python SDK GENERATED library offers the same authentication methods as the legacy one. Let's see the differences of their usage: ### Developer Token **Old (`boxsdk`)** ``` from boxsdk import Client, OAuth2 auth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', access_token='DEVELOPER_TOKEN_GOES_HERE', ) client = Client(auth) ``` The new SDK provides a convenient `BoxDeveloperTokenAuth`, which allows authenticating using developer token without necessity to provide a Client ID and Client Secret **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxClient, BoxDeveloperTokenAuth auth = BoxDeveloperTokenAuth(token='DEVELOPER_TOKEN_GOES_HERE') client = BoxClient(auth=auth) ``` ### JWT Auth #### Using JWT configuration file **Old (`boxsdk`)** The static method, which reads the JWT configuration file has been changed: ``` from boxsdk import JWTAuth, Client auth = JWTAuth.from_settings_file('/path/to/config.json') client = Client(auth) ``` **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxClient, BoxJWTAuth, JWTConfig jwt_config = JWTConfig.from_config_file(config_file_path='/path/to/config.json') auth = BoxJWTAuth(config=jwt_config) client = BoxClient(auth=auth) ``` #### Providing JWT configuration manually Some params in `JWTConfig` constructor have slightly different names than one in old `JWTAuth` class. **Old (`boxsdk`)** ``` from boxsdk import JWTAuth auth = JWTAuth( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', enterprise_id='YOUR_ENTERPRISE_ID', user_id='USER_ID', jwt_key_id='YOUR_JWT_KEY_ID', rsa_private_key_file_sys_path='CERT.PEM', rsa_private_key_passphrase='PASSPHRASE', jwt_algorithm='RS256', ) ``` **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxJWTAuth, JWTConfig, JwtAlgorithm jwt_config = JWTConfig( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', enterprise_id='YOUR_ENTERPRISE_ID', user_id='USER_ID', jwt_key_id='YOUR_JWT_KEY_ID', private_key='YOUR_PRIVATE_KEY', private_key_passphrase='PASSPHRASE', algorithm=JwtAlgorithm.RS256, ) auth = BoxJWTAuth(config=jwt_config) ``` #### Authenticate user In old SDK method for user authentication was named `authenticate_user(self, user: Union[str, 'User'] = None) -> str` and was accepting either user object or user id. If none provided, user ID stored in `JWTAuth` class instance was used. The `authenticate_user` method was modifying existing `BoxJWTAuth` class, which was exchanging the existing token with the one with the user access. **Old (`boxsdk`)** ``` auth.authenticate_user(user) ``` or ``` auth.authenticate_user('USER_ID') ``` **New (`box-sdk-gen`)** In new SDK, to authenticate as user you need to call `with_user_subject(self, user_id: str, *, token_storage: TokenStorage = None) -> BoxJWTAuth` method with id of the user to authenticate. The method returns a new instance of `BoxJWTAuth` class, which will perform authentication call in scope of the user on the first API call. The `token_storage` parameter is optional and allows to provide a custom token storage for the new instance of `BoxJWTAuth` class. The new auth instance can be used to create a new user client instance. ``` from box_sdk_gen import BoxJWTAuth, BoxClient user_auth: BoxJWTAuth = auth.with_user_subject('USER_ID') user_client: BoxClient = BoxClient(auth=user_auth) ``` ### Client Credentials Grant #### Obtaining Service Account token To authenticate as enterprise, the only difference between the old and the new SDK, is using the `CCGConfig` as a middle step. **Old (`boxsdk`)** ``` from boxsdk import CCGAuth, Client auth = CCGAuth( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", enterprise_id="YOUR_ENTERPRISE_ID", ) client = Client(auth) ``` **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxClient, BoxCCGAuth, CCGConfig ccg_config = CCGConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", enterprise_id="YOUR_ENTERPRISE_ID", ) auth = BoxCCGAuth(config=ccg_config) client = BoxClient(auth=auth) ``` #### Obtaining User token In old SDK `CCGAuth` was accepting both user object and User ID. In the box-sdk-gen the `BoxCCGAuth` constructor accepts only User ID instead. **Old (`boxsdk`)** ``` from boxsdk import CCGAuth auth = CCGAuth( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user="YOUR_USER_ID" ) ``` **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxCCGAuth, CCGConfig ccg_config = CCGConfig( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user_id="YOUR_USER_ID" ) auth = BoxCCGAuth(config=ccg_config) ``` ### Switching between Service Account and User In old SDK there were two methods which allowed to switch between using service and user account. Calling these methods were modifying existing state of `CCGAuth` class, which was fetching a new token on the next API call. **Old (`boxsdk`)** ``` auth.authenticate_enterprise('ENTERPRISE_ID') ``` ``` auth.authenticate_user('USER_ID') ``` In the new SDK, to keep the immutability design, the methods switching authenticated subject were replaced with methods returning a new instance of `BoxCCGAuth` class. The new instance will fetch a new token on the next API call. The new auth instance can be used to create a new client instance. You can also specify `token_storage` parameter to provide a custom token storage for the new instance. The old instance of `BoxCCGAuth` class will remain unchanged and will still use the old token. **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxCCGAuth, BoxClient enterprise_auth: BoxCCGAuth = auth.with_enterprise_subject(enterprise_id='ENTERPRISE_ID') enterprise_client: BoxClient = BoxClient(auth=enterprise_auth) ``` ``` from box_sdk_gen import BoxCCGAuth, BoxClient user_auth: BoxCCGAuth = auth.with_user_subject(user_id='USER_ID') user_client: BoxClient = BoxClient(auth=user_auth) ``` Note that the new methods accept only user id or enterprise id, while the old ones were accepting user and enterprise object too. ### OAuth 2.0 Auth #### Get Authorization URL To get authorization url in the new SDK, you need to first create the `BoxOAuth` class (previously `OAuth2`) using `OAuthConfig` class. Then to get authorization url, call `get_authorize_url(self, *, options: GetAuthorizeUrlOptions = None) -> str` instead of `get_authorization_url(self, redirect_url: Optional[str]) -> Tuple[str, str]`. Note that this method now accepts the instance of `GetAuthorizeUrlOptions` class, which allows specifying extra options to API call. The new function returns only the authentication url string, while the old one returns tuple of authentication url and csrf_token. **Old (`boxsdk`)** ``` from boxsdk import OAuth2 auth = OAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', ) auth_url, csrf_token = auth.get_authorization_url('http://YOUR_REDIRECT_URL') ``` **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxOAuth, OAuthConfig, GetAuthorizeUrlOptions auth = BoxOAuth( OAuthConfig( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', ) ) auth_url = auth.get_authorize_url(options=GetAuthorizeUrlOptions(redirect_uri='http://YOUR_REDIRECT_URL')) ``` #### Authenticate The signature of method for authenticating with obtained auth code got changed from: `authenticate(self, auth_code: Optional[str]) -> Tuple[str, str]` to `get_tokens_authorization_code_grant(self, authorization_code: str, *, network_session: Optional[NetworkSession] = None) -> AccessToken`. The method now returns an AccessToken object with `access_token` and `refresh_token` fields, while the old one was returning a tuple of access token and refresh token. **Old (`boxsdk`)** ``` from boxsdk import Client access_token, refresh_token = auth.authenticate('YOUR_AUTH_CODE') client = Client(auth) ``` **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxClient, AccessToken access_token: AccessToken = auth.get_tokens_authorization_code_grant('YOUR_AUTH_CODE') client = BoxClient(auth) ``` ### Store token and retrieve token callbacks In old SDK you could provide a `store_tokens` callback method to an authentication class, which was called each time an access token was refreshed. It could be used to save your access token to a custom token storage and allow to reuse this token later. What is more, old SDK allowed also to provide `retrieve_tokens` callback, which is called each time the SDK needs to use token to perform an API call. To provide that, it was required to use `CooperativelyManagedOAuth2` and provide `retrieve_tokens` callback method to its constructor. **Old (`boxsdk`)** ``` from typing import Tuple from boxsdk.auth import CooperativelyManagedOAuth2 from boxsdk import Client def retrieve_tokens() -> Tuple[str, str]: # retrieve access_token and refresh_token return access_token, refresh_token def store_tokens(access_token: str, refresh_token: str): # store access_token and refresh_token pass auth = CooperativelyManagedOAuth2( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', retrieve_tokens=retrieve_tokens, store_tokens=store_tokens ) access_token, refresh_token = auth.authenticate('YOUR_AUTH_CODE') client = Client(auth) ``` In the new SDK you can define your own class delegated for storing and retrieving a token. It has to inherit from `TokenStorage` and implement all of its abstract methods. Next step would be to pass an instance of this class to the AuthConfig constructor. **New (`box-sdk-gen`)** ``` from typing import Optional from box_sdk_gen import BoxOAuth, OAuthConfig, TokenStorage, AccessToken class MyCustomTokenStorage(TokenStorage): def store(self, token: AccessToken) -> None: # store token pass def get(self) -> Optional[AccessToken]: # get token pass def clear(self) -> None: # clear token pass auth = BoxOAuth( OAuthConfig( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', token_storage=MyCustomTokenStorage() ) ) ``` or reuse one of the provided implementations: `FileTokenStorage` or `FileWithInMemoryCacheTokenStorage`: ``` from box_sdk_gen import BoxOAuth, OAuthConfig, FileWithInMemoryCacheTokenStorage auth = BoxOAuth( OAuthConfig( client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET', token_storage=FileWithInMemoryCacheTokenStorage() ) ) ``` ### Downscope token The process of downscoping token in the new SDK is similar to the old one. The main difference is that the new method accepts the full resource path instead of file object. **Old (`boxsdk`)** ``` from boxsdk import Client, OAuth2 target_file = client.file(file_id='FILE_ID_HERE') token_info = client.downscope_token(['item_preview'], target_file) downscoped_auth = OAuth2( client_id=None, client_secret=None, access_token=token_info.access_token ) downscoped_client = Client(downscoped_auth) ``` **New (`box-sdk-gen`)** ``` from box_sdk_gen import BoxDeveloperTokenAuth, AccessToken, BoxClient resource = 'https://api.box.com/2.0/files/123456789' downscoped_token: AccessToken = auth.downscope_token( scopes=['item_preview'], resource=resource, ) downscoped_auth = BoxDeveloperTokenAuth(token=downscoped_token.access_token) client = BoxClient(auth=downscoped_auth) ``` ### Revoke token To revoke current client's tokens in the new SDK, you need to call `revoke_token` method of the auth class instead of `revoke` method. **Old (`boxsdk`)** ``` oauth.revoke() ``` **New (`box-sdk-gen`)** ``` client.auth.revoke_token() ``` ## Configuration ### As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an `As-User: USER-ID` header. The following examples assume that the client has been instantiated with an access token with appropriate privileges to make As-User calls. In old SDK you could call client `as_user(self, user: User)` method to create a new client to impersonate the provided user. **Old (`boxsdk`)** ``` from boxsdk import Client user_to_impersonate = client.user(user_id='USER_ID') user_client: Client = client.as_user(user_to_impersonate) ``` **New (`box-sdk-gen`)** In the new SDK the method was renamed to `with_as_user_header(self, user_id: str) -> BoxClient` and returns a new instance of `BoxClient` class with the As-User header appended to all API calls made by the client. The method accepts only user id as a parameter. ``` from box_sdk_gen import BoxClient user_client: BoxClient = client.with_as_user_header(user_id='USER_ID') ``` Additionally `BoxClient` offers a `with_extra_headers(self, *, extra_headers: Dict[str, str] = None) -> BoxClient` method, which allows you to specify the custom set of headers, which will be included in every API call made by client. Calling the `client.with_extra_headers()` method creates a new client, leaving the original client unmodified. ``` from box_sdk_gen import BoxClient new_client: BoxClient = client.with_extra_headers(extra_headers={'customHeader': 'customValue'}) ``` ### Custom Base URLs **Old (`boxsdk`)** In old SDK you could specify the custom base URLs, which will be used for API calls made by setting the new values of static variables of the `API` class. ``` from boxsdk.config import API API.BASE_API_URL = 'https://new-base-url.com' API.OAUTH2_API_URL = 'https://my-company.com/oauth2' API.UPLOAD_URL = 'https://my-company-upload-url.com' ``` **New (`box-sdk-gen`)** In the new SDK this functionality has been implemented as part of the `BoxClient` class. By calling the `client.with_custom_base_urls()` method, you can specify the custom base URLs that will be used for API calls made by client. Following the immutability pattern, this call creates a new client, leaving the original client unmodified. ``` from box_sdk_gen import BoxClient, BaseUrls new_client: BoxClient = client.with_custom_base_urls(base_urls=BaseUrls( base_url='https://new-base-url.com', upload_url='https://my-company-upload-url.com', oauth_2_url='https://my-company.com/oauth2', )) ``` ## Convenience methods ### Webhook validation Webhook validation is used to validate a webhook message by verifying the signature and the delivery timestamp. **Old (`boxsdk`)** In the old SDK, you could pass the `body` as `bytes`, and it would return a `boolean` value indicating whether the message was valid. ``` body = b'{"webhook":{"id":"1234567890"},"trigger":"FILE.UPLOADED","source":{"id":"1234567890","type":"file","name":"Test.txt"}}' headers = { 'box-delivery-id': 'f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f', 'box-delivery-timestamp': '2020-01-01T00:00:00-07:00', 'box-signature-algorithm': 'HmacSHA256', 'box-signature-primary': '4KvFa5/unRL8aaqOlnbInTwkOmieZkn1ZVzsAJuRipE=', 'box-signature-secondary': 'yxxwBNk7tFyQSy95/VNKAf1o+j8WMPJuo/KcFc7OS0Q=', 'box-signature-version': '1', } is_validated = Webhook.validate_message(body, headers, primary_key, secondary_key) print(f'The webhook message is validated to: {is_validated}') ``` **New (`box-sdk-gen`)** In the new SDK, the `WebhooksManager.validate_message()` method requires the `body` to be of type `string` and the rest of the code remains the same ``` from box_sdk_gen import WebhooksManager body = '{"webhook":{"id":"1234567890"},"trigger":"FILE.UPLOADED","source":{"id":"1234567890","type":"file","name":"Test.txt"}}' headers = { 'box-delivery-id': 'f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f', 'box-delivery-timestamp': '2020-01-01T00:00:00-07:00', 'box-signature-algorithm': 'HmacSHA256', 'box-signature-primary': '4KvFa5/unRL8aaqOlnbInTwkOmieZkn1ZVzsAJuRipE=', 'box-signature-secondary': 'yxxwBNk7tFyQSy95/VNKAf1o+j8WMPJuo/KcFc7OS0Q=', 'box-signature-version': '1', } WebhooksManager.validate_message( body=body, headers=headers, primary_key=primary_key, secondary_key=secondary_key ) ``` ### Chunked upload of big files For large files or in cases where the network connection is less reliable, you may want to upload the file in parts. This allows a single part to fail without aborting the entire upload, and failed parts are being retried automatically. **Old (`boxsdk`)** In the old SDK, you could use the `get_chunked_uploader()` method to create a chunked uploader object. Then, you would call the `start()` method to begin the upload process. The `get_chunked_uploader()` method requires the `file_path` and `file_name` parameters. ``` chunked_uploader = client.folder('0').get_chunked_uploader(file_path='/path/to/file.txt', file_name='new_name.txt') uploaded_file = chunked_uploader.start() print(f'File "{uploaded_file.name}" uploaded to Box with file ID {uploaded_file.id}') ``` **New (`box-sdk-gen`)** In the new SDK, the equivalent method is `chunked_uploads.upload_big_file()`. It accepts a file-like object as the `file` parameter, and the `file_name` and `file_size` parameters are now passed as arguments. The `parent_folder_id` parameter is also required to specify the folder where the file will be uploaded. ``` import os with open('/path/to/file.txt', 'rb') as file_byte_stream: file_name = 'new_name.txt' file_size = os.path.getsize('/path/to/file.txt') parent_folder_id = '0' # ID of the folder where the file will be uploaded uploaded_file = client.chunked_uploads.upload_big_file( file=file_byte_stream, file_name=file_name, file_size=file_size, parent_folder_id=parent_folder_id ) ``` --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 1.16.0 (2025-0… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## 1.16.0 (2025-08-05) ### Bug Fixes - Specify events `next_stream_position` property type as `int` (box/box-openapi[#535](https://github.com/box/box-python-sdk-gen/issues/535)) ([#644](https://github.com/box/box-python-sdk-gen/issues/644)) ([64069db](https://github.com/box/box-python-sdk-gen/commit/64069db8da33988c173380defd6be065daa02496)) ### New Features and Enhancements - Add AI spreadsheet processor (box/box-openapi[#533](https://github.com/box/box-python-sdk-gen/issues/533)) ([#630](https://github.com/box/box-python-sdk-gen/issues/630)) ([6635757](https://github.com/box/box-python-sdk-gen/commit/66357578218913240bc923cb0dc771157ec95f54)) - Add Archive Public API (box/box-openapi[#540](https://github.com/box/box-python-sdk-gen/issues/540)) ([#651](https://github.com/box/box-python-sdk-gen/issues/651)) ([c36d1db](https://github.com/box/box-python-sdk-gen/commit/c36d1dbff42c89876c037983c792c5c7282459cc)) - Add new Hubs APIs and Hubs items API (box/box-openapi[#538](https://github.com/box/box-python-sdk-gen/issues/538)) ([#645](https://github.com/box/box-python-sdk-gen/issues/645)) ([1daa3e8](https://github.com/box/box-python-sdk-gen/commit/1daa3e8814403c78ed2a1d64187b8e4c379028fe)) - Add new property for network exception retry strategy (box/box-codegen[#763](https://github.com/box/box-python-sdk-gen/issues/763)) ([#650](https://github.com/box/box-python-sdk-gen/issues/650)) ([13f9593](https://github.com/box/box-python-sdk-gen/commit/13f9593dbc4a45d094ee5709d602188ef341a1a5)) - Add new schema for `Metadata Error` (box/box-openapi[#539](https://github.com/box/box-python-sdk-gen/issues/539)) ([#646](https://github.com/box/box-python-sdk-gen/issues/646)) ([49d7f34](https://github.com/box/box-python-sdk-gen/commit/49d7f349e1be4e23939ef10db1edfc6042b98175)) - Allow injecting private key decryption mechanism for JWT (box/box-codegen[#754](https://github.com/box/box-python-sdk-gen/issues/754)) ([#636](https://github.com/box/box-python-sdk-gen/issues/636)) ([4ea0af5](https://github.com/box/box-python-sdk-gen/commit/4ea0af5f8f5b5516a7c23d7912c34690c017db29)) - Improve webhook validation checks (box/box-codegen[#745](https://github.com/box/box-python-sdk-gen/issues/745)) ([#628](https://github.com/box/box-python-sdk-gen/issues/628)) ([f0ece63](https://github.com/box/box-python-sdk-gen/commit/f0ece639d761c765b3bc59fbe3ba8582af755178)) - Support Hubs beta endpoints (box/box-openapi[#531](https://github.com/box/box-python-sdk-gen/issues/531)) ([#622](https://github.com/box/box-python-sdk-gen/issues/622)) ([b5e95fe](https://github.com/box/box-python-sdk-gen/commit/b5e95fe5b219d067028aa395170718eca0d62189)) - Support new tools in AI Studio (box/box-openapi[#534](https://github.com/box/box-python-sdk-gen/issues/534)) ([#633](https://github.com/box/box-python-sdk-gen/issues/633)) ([ac76eb2](https://github.com/box/box-python-sdk-gen/commit/ac76eb2d7c5560b30c4cec171dd90b0a0ece4ab5)) ## 1.15.0 (2025-06-12) ### Bug Fixes - Compute webhook signature with and without escaping the body (box/box-codegen[#737](https://github.com/box/box-python-sdk-gen/issues/737)) ([#607](https://github.com/box/box-python-sdk-gen/issues/607)) ([e5118b8](https://github.com/box/box-python-sdk-gen/commit/e5118b8a257a042510374d91bd62a1f98c662fef)) - Fix downscope token to use `retrieveToken` method for token retrieval (box/box-codegen[#731](https://github.com/box/box-python-sdk-gen/issues/731)) ([#598](https://github.com/box/box-python-sdk-gen/issues/598)) ([e492685](https://github.com/box/box-python-sdk-gen/commit/e4926851edccd4ee7e66157050cedd0d01cec5ea)) - Fix slash escaping when calculating webhook signature (box/box-codegen[#736](https://github.com/box/box-python-sdk-gen/issues/736)) ([#603](https://github.com/box/box-python-sdk-gen/issues/603)) ([430b175](https://github.com/box/box-python-sdk-gen/commit/430b1754ec840582e28a277c6c8d369cbe7ebdf5)) - Use constant-time comparison for HMAC signatures (box/box-codegen[#739](https://github.com/box/box-python-sdk-gen/issues/739)) ([#610](https://github.com/box/box-python-sdk-gen/issues/610)) ([6f6660c](https://github.com/box/box-python-sdk-gen/commit/6f6660c8f3aa2b7b75b0fcd4ed015d8d761cd77f)) ### New Features and Enhancements - Add AI agents warnings; allow for more types of metadata value (box/box-openapi[#520](https://github.com/box/box-python-sdk-gen/issues/520)) ([#567](https://github.com/box/box-python-sdk-gen/issues/567)) ([86aa1cc](https://github.com/box/box-python-sdk-gen/commit/86aa1ccadac9acead7bceeafb50e45f38eb2d9cc)) - Add Shield Lists APIs (box/box-openapi[#528](https://github.com/box/box-python-sdk-gen/issues/528)) ([#601](https://github.com/box/box-python-sdk-gen/issues/601)) ([f980f65](https://github.com/box/box-python-sdk-gen/commit/f980f6544a58a5c64ab0b3ec13b2771b81ea25ed)) - Add support of IBM models to AI API (box/box-openapi[#522](https://github.com/box/box-python-sdk-gen/issues/522)) ([#568](https://github.com/box/box-python-sdk-gen/issues/568)) ([767547a](https://github.com/box/box-python-sdk-gen/commit/767547ae070909852800c447e65cbcc95b97c5a3)) - Update legal holds and AI models (box/box-openapi[#526](https://github.com/box/box-python-sdk-gen/issues/526)) ([#599](https://github.com/box/box-python-sdk-gen/issues/599)) ([d56228d](https://github.com/box/box-python-sdk-gen/commit/d56228d81bd9777af5431ccc9d05233e13a0c2ed)) ## 1.14.0 (2025-05-02) ### Bug Fixes - set default timeouts for requests (box/box-codegen[#707](https://github.com/box/box-python-sdk-gen/issues/707)) ([#552](https://github.com/box/box-python-sdk-gen/issues/552)) ([66b87c8](https://github.com/box/box-python-sdk-gen/commit/66b87c8986ce2f5fdb3a9eac995ef8a9643bcd76)) ### New Features and Enhancements - Add security settings properties on sign template schema (box/box-openapi[#518](https://github.com/box/box-python-sdk-gen/issues/518)) ([#543](https://github.com/box/box-python-sdk-gen/issues/543)) ([0a45d21](https://github.com/box/box-python-sdk-gen/commit/0a45d218d1aa3fa62da7b5c8c01506fb657c0b36)) - Support sensitive data sanitization in errors (box/box-codegen[#695](https://github.com/box/box-python-sdk-gen/issues/695)) ([#533](https://github.com/box/box-python-sdk-gen/issues/533)) ([abb7b1d](https://github.com/box/box-python-sdk-gen/commit/abb7b1d16a192edd99ff1fc4fb7c4caf79ee5f10)) ## 1.13.0 (2025-03-18) ### Bug Fixes - Add `verification_phone_number` property to create sign request (box/box-openapi[#515](https://github.com/box/box-python-sdk-gen/issues/515)) ([#503](https://github.com/box/box-python-sdk-gen/issues/503)) ([6d19d19](https://github.com/box/box-python-sdk-gen/commit/6d19d197481a578d7d5ad8d632ac6f5c06bd3dce)) ### New Features and Enhancements - Add find app item for shared link endpoint (box/box-openapi[#514](https://github.com/box/box-python-sdk-gen/issues/514)) ([#502](https://github.com/box/box-python-sdk-gen/issues/502)) ([fd6c693](https://github.com/box/box-python-sdk-gen/commit/fd6c6933f0fb518830e9ac810fd511a0cf60b429)) - Add Integration Mappings Teams API (box/box-openapi[#517](https://github.com/box/box-python-sdk-gen/issues/517)) ([#505](https://github.com/box/box-python-sdk-gen/issues/505)) ([d1aa250](https://github.com/box/box-python-sdk-gen/commit/d1aa250fb01fbf742daf266d4458ba2eab2c5669)) - Support upload with preflight check (box/box-codegen[#676](https://github.com/box/box-python-sdk-gen/issues/676)) ([#515](https://github.com/box/box-python-sdk-gen/issues/515)) ([bb4597e](https://github.com/box/box-python-sdk-gen/commit/bb4597e40d49e20eca44c4414e406b1352af1a2b)) ## 1.12.0 (2025-02-20) ### Bug Fixes - Fix handling responses with invalid JSON (box/box-codegen[#667](https://github.com/box/box-python-sdk-gen/issues/667)) ([#485](https://github.com/box/box-python-sdk-gen/issues/485)) ([46399d8](https://github.com/box/box-python-sdk-gen/commit/46399d8d91d9a22c75e03e870b091cac6d81237f)), closes [#470](https://github.com/box/box-python-sdk-gen/issues/470) ### New Features and Enhancements - Support AI Studio API (box/box-codegen[#626](https://github.com/box/box-python-sdk-gen/issues/626)) ([#483](https://github.com/box/box-python-sdk-gen/issues/483)) ([bd7fefa](https://github.com/box/box-python-sdk-gen/commit/bd7fefad8f2d941676732ea66c5b0d75bae9e703)) ### 1.11.1 (2025-02-12) ### Bug Fixes - Fix proxy usage (box/box-codegen[#662](https://github.com/box/box-python-sdk-gen/issues/662)) ([#476](https://github.com/box/box-python-sdk-gen/issues/476)) ([e1d62ac](https://github.com/box/box-python-sdk-gen/commit/e1d62ac5a8063bf37244329329100752c3a069af)) ## 1.11.0 (2025-02-06) ### Bug Fixes - Correct types of `paged` and `thumb` properties in File representation (box/box-openapi[#503](https://github.com/box/box-python-sdk-gen/issues/503)) ([#451](https://github.com/box/box-python-sdk-gen/issues/451)) ([e818fa6](https://github.com/box/box-python-sdk-gen/commit/e818fa6c9c80e61a293fc24ed6f1a15978681662)) ### New Features and Enhancements - Add Box Sign shared requests (box/box-openapi[#504](https://github.com/box/box-python-sdk-gen/issues/504)) ([#453](https://github.com/box/box-python-sdk-gen/issues/453)) ([3590918](https://github.com/box/box-python-sdk-gen/commit/359091873d26111b82f000e7837553cc799f2433)) - feat: Add hubs support to `/ai/ask`. Replace type of `items` parameter from `List[AiItemBase]` to `List[AiItemAsk]` in `create_ai_ask` method (box/box-openapi[#506](https://github.com/box/box-python-sdk-gen/issues/506)) ([#466](https://github.com/box/box-python-sdk-gen/issues/466)) ([29f0364](https://github.com/box/box-python-sdk-gen/commit/29f03649f3ec1471e859609d2b8bd77ad5d09106)) - Update `/ai/extract_structured` response schema (box/box-codegen[#641](https://github.com/box/box-python-sdk-gen/issues/641)) ([#459](https://github.com/box/box-python-sdk-gen/issues/459)) ([7c73cea](https://github.com/box/box-python-sdk-gen/commit/7c73ceaa8888332b23bca4d6b64ef4999f942940)) ## 1.10.0 (2025-01-21) ### Bug Fixes - Add missing token scope (box/box-openapi[#490](https://github.com/box/box-python-sdk-gen/issues/490)) ([#420](https://github.com/box/box-python-sdk-gen/issues/420)) ([41afe8b](https://github.com/box/box-python-sdk-gen/commit/41afe8bcbfc20e3ff22d34a273dcb416afb455da)) - Fix invalid variant config for Integration mapping Slack (box/box-openapi[#492](https://github.com/box/box-python-sdk-gen/issues/492)) ([#423](https://github.com/box/box-python-sdk-gen/issues/423)) ([d03ccd4](https://github.com/box/box-python-sdk-gen/commit/d03ccd46b88c71450c1c67ecef439e25b97cbad7)) - order of fields in the `IntegrationMapping` schema (box/box-openapi[#497](https://github.com/box/box-python-sdk-gen/issues/497)) ([#438](https://github.com/box/box-python-sdk-gen/issues/438)) ([13dea88](https://github.com/box/box-python-sdk-gen/commit/13dea88c4e43748eed600f55a638c14ef0a1a60a)) ### New Features and Enhancements - Support Box Doc Gen API (box/box-codegen[#644](https://github.com/box/box-python-sdk-gen/issues/644)) ([#446](https://github.com/box/box-python-sdk-gen/issues/446)) ([41fa63c](https://github.com/box/box-python-sdk-gen/commit/41fa63c0a3c957a34b03163dfeaa44a03a5873ff)) ## 1.9.0 (2024-12-30) ### Bug Fixes - Remove unused parameter from `SignRequest` (box/box-openapi[#489](https://github.com/box/box-python-sdk-gen/issues/489)) ([#411](https://github.com/box/box-python-sdk-gen/issues/411)) ([578d9b4](https://github.com/box/box-python-sdk-gen/commit/578d9b48da7e55d2e3e4736c871400dc90d826b1)) ### New Features and Enhancements - Add `ai_agent` info to `AiResponse` (box/box-openapi[#485](https://github.com/box/box-python-sdk-gen/issues/485)) ([#402](https://github.com/box/box-python-sdk-gen/issues/402)) ([351a5b8](https://github.com/box/box-python-sdk-gen/commit/351a5b8dfbc8a0095bafbbf0245d8575217fc3c9)) - Add support for replacing the network client implementation (box/box-codegen[#629](https://github.com/box/box-python-sdk-gen/issues/629)) ([#415](https://github.com/box/box-python-sdk-gen/issues/415)) ([fb118dd](https://github.com/box/box-python-sdk-gen/commit/fb118ddb1cbfb1d6a72e657bed57088fdff1ec02)) - Allow for customizing retry strategy (box/box-codegen[#635](https://github.com/box/box-python-sdk-gen/issues/635)) ([#418](https://github.com/box/box-python-sdk-gen/issues/418)) ([8dfb3ed](https://github.com/box/box-python-sdk-gen/commit/8dfb3ed13196de37a78a53325079e284c7e921d5)) - Support optional `userId` parameter for updating files, folders and web links (box/box-openapi[#488](https://github.com/box/box-python-sdk-gen/issues/488)) ([#406](https://github.com/box/box-python-sdk-gen/issues/406)) ([d9cff4c](https://github.com/box/box-python-sdk-gen/commit/d9cff4c6adc9c5cc9ce1edf73dffe8ac5979ce71)) - Support webhook message validation (box/box-codegen[#631](https://github.com/box/box-python-sdk-gen/issues/631)) ([#416](https://github.com/box/box-python-sdk-gen/issues/416)) ([0fec20b](https://github.com/box/box-python-sdk-gen/commit/0fec20b281fe195f0dd6aaf8f164bdd414587fc4)) ## 1.8.0 (2024-12-02) ### Bug Fixes - Fix enums usage (box/box-codegen[#615](https://github.com/box/box-python-sdk-gen/issues/615)) ([#387](https://github.com/box/box-python-sdk-gen/issues/387)) ([a9abccb](https://github.com/box/box-python-sdk-gen/commit/a9abccb8e552c971774ea1a9fa2096395a40317b)), closes [#385](https://github.com/box/box-python-sdk-gen/issues/385) - Support status codes with no content (box/box-codegen[#604](https://github.com/box/box-python-sdk-gen/issues/604)) ([#378](https://github.com/box/box-python-sdk-gen/issues/378)) ([051716c](https://github.com/box/box-python-sdk-gen/commit/051716c84b4f0ab32b82608f94e3cf3ba09b390b)) - update collaboration, metadata and collection resources (box/box-openapi[#483](https://github.com/box/box-python-sdk-gen/issues/483)) ([#380](https://github.com/box/box-python-sdk-gen/issues/380)) ([0d45fed](https://github.com/box/box-python-sdk-gen/commit/0d45fedc0b7b96234ef3901f412f259b1cae4c1a)) ### New Features and Enhancements - Expose method for making custom HTTP requests (box/box-codegen[#610](https://github.com/box/box-python-sdk-gen/issues/610)) ([#393](https://github.com/box/box-python-sdk-gen/issues/393)) ([55a23d9](https://github.com/box/box-python-sdk-gen/commit/55a23d9d6840642c248ab3b967ad5c2635484c8c)) - Support getting file download URL and file thumbnail URL (box/box-codegen[#617](https://github.com/box/box-python-sdk-gen/issues/617)) ([#397](https://github.com/box/box-python-sdk-gen/issues/397)) ([fd609ab](https://github.com/box/box-python-sdk-gen/commit/fd609ab9fe94da43b1a71815597c49471e157bb8)) ## 1.7.0 (2024-11-04) ### New Features and Enhancements - Support get collection by ID endpoint (box/box-codegen[#595](https://github.com/box/box-codegen/issues/595)) ([#366](https://github.com/box/box-codegen/issues/366)) ([1db5722](https://github.com/box/box-codegen/commit/1db5722f7d02694739f1a52a6b2ebe0c406960b0)), closes [#355](https://github.com/box/box-codegen/issues/355) ## 1.6.0 (2024-10-30) ### Bug Fixes - Set stream position to 0 for multipart requests (box/box-codegen[#581](https://github.com/box/box-codegen/issues/581)) ([#348](https://github.com/box/box-codegen/issues/348)) ([fa6942c](https://github.com/box/box-codegen/commit/fa6942c231024947250955ccc52f352744ab5f38)) - Update client error schema (box/box-openapi[#467](https://github.com/box/box-codegen/issues/467)) ([#347](https://github.com/box/box-codegen/issues/347)) ([a42a253](https://github.com/box/box-codegen/commit/a42a2532337c79d20b6524fda0acf717d9ccbd5f)) - Use original stream position when retrying requests (box/box-codegen[#583](https://github.com/box/box-codegen/issues/583)) ([#358](https://github.com/box/box-codegen/issues/358)) ([060b4dc](https://github.com/box/box-codegen/commit/060b4dc2b8bbbc1e17cce0fc049394e0527952b7)) - use raw `docstrings` when comments contain backslash (box/box-codegen[#571](https://github.com/box/box-codegen/issues/571)) ([#330](https://github.com/box/box-codegen/issues/330)) ([8dd8cb7](https://github.com/box/box-codegen/commit/8dd8cb71105c200bd03f5f894a4dbfb42baf0865)) ### New Features and Enhancements - Add `download_file_to_output_stream` method to `DownloadsManager` (box/box-codegen[#575](https://github.com/box/box-codegen/issues/575)) ([#334](https://github.com/box/box-codegen/issues/334)) ([6820d08](https://github.com/box/box-codegen/commit/6820d08f37c5c0605a580391bef2dc4f2a384c00)) - add AI LLM endpoint AWS `params` (box/box-openapi[#478](https://github.com/box/box-codegen/issues/478)) ([#354](https://github.com/box/box-codegen/issues/354)) ([c8fa2c1](https://github.com/box/box-codegen/commit/c8fa2c1131154d07a500290db6a7b34b06005c2b)) ### 1.5.1 (2024-09-19) ### Bug Fixes - Fix proxy `url` without proxy credentials (box/box-codegen[#568](https://github.com/box/box-codegen/issues/568)) ([#322](https://github.com/box/box-codegen/issues/322)) ([fb19160](https://github.com/box/box-codegen/commit/fb19160307b58d5f08bb12e0f846d71ff936ad6a)), closes [#318](https://github.com/box/box-codegen/issues/318) - Stop sending last empty chunk for chunk upload (box/box-codegen[#569](https://github.com/box/box-codegen/issues/569)) ([#324](https://github.com/box/box-codegen/issues/324)) ([1605f04](https://github.com/box/box-codegen/commit/1605f0495994b333e735bc98f28fa714324b75f5)), closes [#321](https://github.com/box/box-codegen/issues/321) ## 1.5.0 (2024-09-18) ### Bug Fixes - Add the missing license to `setup.py` (box/box-codegen[#562](https://github.com/box/box-codegen/issues/562)) ([#307](https://github.com/box/box-codegen/issues/307)) ([679d789](https://github.com/box/box-codegen/commit/679d7891b2a20e7407b8c9f00bd95c3b294ab861)) - Fix variants in metadata query results (box/box-openapi[#456](https://github.com/box/box-codegen/issues/456)) ([#313](https://github.com/box/box-codegen/issues/313)) ([8830303](https://github.com/box/box-codegen/commit/883030335e2a3c12a5e0b01d8a82df30ccce16a6)) ### New Features and Enhancements - Add support for proxy (box/box-codegen[#559](https://github.com/box/box-codegen/issues/559)) ([#302](https://github.com/box/box-codegen/issues/302)) ([3d881ac](https://github.com/box/box-codegen/commit/3d881acdebf2b18e2f0f82211f5abdcc32d1ddb0)) - Introduce `raw_data` field for storing raw `json` response (box/box-codegen[#566](https://github.com/box/box-codegen/issues/566)) ([#319](https://github.com/box/box-codegen/issues/319)) ([3776dc3](https://github.com/box/box-codegen/commit/3776dc3d44bc09eb68da99f45e36e058dca2607e)) - Support `ai/extract` and `ai/extract_structured` endpoints (box/box-codegen[#564](https://github.com/box/box-codegen/issues/564)) ([#317](https://github.com/box/box-codegen/issues/317)) ([b3d8da4](https://github.com/box/box-codegen/commit/b3d8da41007a9d47b73b699fd84da6f9540866d2)) - Support App item associations (box/box-codegen[#561](https://github.com/box/box-codegen/issues/561)) ([#299](https://github.com/box/box-codegen/issues/299)) ([8b6ea0b](https://github.com/box/box-codegen/commit/8b6ea0bbec719a36eb11b6d214c08801c4f1a40b)) ### 1.4.1 (2024-08-30) ### Bug Fixes - Do not store data in-memory during download process in Python (box/box-codegen[#557](https://github.com/box/box-codegen/issues/557)) ([#294](https://github.com/box/box-codegen/issues/294)) ([7c645ae](https://github.com/box/box-codegen/commit/7c645aea9fa8575531e0b40ffc997a0f65b6e409)) ## 1.4.0 (2024-08-23) ### Bug Fixes - Add missing fields to Sign Template Signer and fix AI schema (box/box-openapi[#451](https://github.com/box/box-codegen/issues/451)) ([#281](https://github.com/box/box-codegen/issues/281)) ([0708351](https://github.com/box/box-codegen/commit/0708351171eca1fe4914b823a4257bbabd3cd075)) - Fix `IntegrationMapping` schemas (box/box-codegen[#551](https://github.com/box/box-codegen/issues/551)) ([#279](https://github.com/box/box-codegen/issues/279)) ([0337e06](https://github.com/box/box-codegen/commit/0337e06c6bf6d35dd51409c429b7fef295f5a406)) ### New Features and Enhancements - Add new parameters to Box AI methods and introduce `AiResponseFull` variant (box/box-openapi[#446](https://github.com/box/box-codegen/issues/446)) ([#277](https://github.com/box/box-codegen/issues/277)) ([1267a21](https://github.com/box/box-codegen/commit/1267a215fbc8292059603665a53b0159d7a1242c)) - Include URL into `FetchOptions` (box/box-codegen[#549](https://github.com/box/box-codegen/issues/549)) ([#283](https://github.com/box/box-codegen/issues/283)) ([dd05b1c](https://github.com/box/box-codegen/commit/dd05b1c2b1687d8647f4116c022dbf1890984adc)) ## 1.3.0 (2024-08-12) ### Bug Fixes - Fix fetch method for multipart request (box/box-codegen[#545](https://github.com/box/box-codegen/issues/545)) ([#266](https://github.com/box/box-codegen/issues/266)) ([08a0818](https://github.com/box/box-codegen/commit/08a0818995d64995c3e2720a459f9221c9ca1dea)) ### New Features and Enhancements - Parametrise chunked uploads endpoint urls (box/box-openapi[#444](https://github.com/box/box-codegen/issues/444)) ([#264](https://github.com/box/box-codegen/issues/264)) ([b5bce24](https://github.com/box/box-codegen/commit/b5bce24478c70ae6bb997adc773a0e2a76223568)) ## 1.2.0 (2024-07-25) ### Bug Fixes - Improve chunked upload reliability ([#224](https://github.com/box/box-codegen/issues/224)) ([05f0353](https://github.com/box/box-codegen/commit/05f035354a76dac0d71849523e4a28641ac92aee)) ### New Features and Enhancements - Add `is_active` parameter to user collaboration (box/box-openapi[#437](https://github.com/box/box-codegen/issues/437)) ([#222](https://github.com/box/box-codegen/issues/222)) ([2b7bbe4](https://github.com/box/box-codegen/commit/2b7bbe41ed23e50c6717148fa5e9e2c24a3f5897)) - Retry request with status code `202` `(box/box-codegen[#511](https://github.com/box/box-codegen/issues/511))` ([#204](https://github.com/box/box-codegen/issues/204)) ([f50ad6e](https://github.com/box/box-codegen/commit/f50ad6e236003901792eb333738020cbdd8c8ae3)) - Support AI Agent API (box/box-codegen[#531](https://github.com/box/box-codegen/issues/531)) ([#229](https://github.com/box/box-codegen/issues/229)) ([c565383](https://github.com/box/box-codegen/commit/c5653839e1a150377e7d5c4764d4c2a7b7d07c4a)) - Support sending fields with `null` value (box/box-codegen[#528](https://github.com/box/box-codegen/issues/528)) ([#230](https://github.com/box/box-codegen/issues/230)) ([f91076e](https://github.com/box/box-codegen/commit/f91076e1bfbccae4a0dff4b66d7bafb5357858c5)), closes [#202](https://github.com/box/box-codegen/issues/202) ## 1.1.0 (2024-06-12) ### Bug Fixes - Fix CI for auto update pull requests (box/box-codegen[#506](https://github.com/box/box-codegen/issues/506)) ([#187](https://github.com/box/box-codegen/issues/187)) ([5e59f69](https://github.com/box/box-codegen/commit/5e59f69591e01cd2caf0033e0023061093989aa5)) ### New Features and Enhancements - add missing marker pagination fields and introduce new event type `AppItemEventSource` `(box/box-openapi[#431](https://github.com/box/box-codegen/issues/431))` ([#189](https://github.com/box/box-codegen/issues/189)) ([8d22ce2](https://github.com/box/box-codegen/commit/8d22ce20d57f4b5dcb5b344ff6bfc67bcaa3568d)) ## 1.0.0 (2024-05-20) ### Bug Fixes - Change base urls (box/box-codegen[#491](https://github.com/box/box-codegen/issues/491)) ([#167](https://github.com/box/box-codegen/issues/167)) ([7f7cb20](https://github.com/box/box-codegen/commit/7f7cb201720bf04efd25c21c1fb131b9f38e5f77)) - Fix schemas for updating classification on a file and folder (box/box-openapi[#423](https://github.com/box/box-codegen/issues/423)) ([#156](https://github.com/box/box-codegen/issues/156)) ([1c4bee1](https://github.com/box/box-codegen/commit/1c4bee1874dcf7f164cbe85ae200883bd4e81ea2)) - Make `PartAccumulator` class internal ([#169](https://github.com/box/box-codegen/issues/169)) ([16726e7](https://github.com/box/box-codegen/commit/16726e7324820572da50c3079b2fe449b103173d)) ### New Features and Enhancements - Add `suppressNotifications` and `externalSystemName` fields for Box Sign (box/box-openapi[#425](https://github.com/box/box-codegen/issues/425)) ([#165](https://github.com/box/box-codegen/issues/165)) ([34ea7c2](https://github.com/box/box-codegen/commit/34ea7c2275017a2d3256361de277272f36859974)) - Move schemas to separate modules (box/box-codegen[#483](https://github.com/box/box-codegen/issues/483)) ([#149](https://github.com/box/box-codegen/issues/149)) ([0ba0142](https://github.com/box/box-codegen/commit/0ba01427e8cffb3fa72892afbf281b11dac4f1ed)) - support excluding endpoints and schemas in parser (box/box-codegen[#487](https://github.com/box/box-codegen/issues/487)) ([#150](https://github.com/box/box-codegen/issues/150)) ([13308c4](https://github.com/box/box-codegen/commit/13308c48700528bd870ca97035d0c3f04e66c299)) ### 0.6.5 (2024-05-09) ### Bug Fixes - Add documentation to folder resource (box/box-openapi[#421](https://github.com/box/box-codegen/issues/421)) ([#144](https://github.com/box/box-codegen/issues/144)) ([ca4e62e](https://github.com/box/box-codegen/commit/ca4e62eafe6b508f92bfda4c7d7075e69c36fc31)) - Ensure `AuthorizationManager` in authentication classes is initialized with `NetworkSession` object (box/box-codegen[#469](https://github.com/box/box-codegen/issues/469)) ([#113](https://github.com/box/box-codegen/issues/113)) ([a5577c7](https://github.com/box/box-codegen/commit/a5577c734b5ca18567b423075661964735f6e46a)) - Fix Box AI endpoints (box/box-openapi[#418](https://github.com/box/box-codegen/issues/418)) ([#139](https://github.com/box/box-codegen/issues/139)) ([de2b8a3](https://github.com/box/box-codegen/commit/de2b8a3874d8647d9fc77d61ff998bf7d5400a69)) - Fix deserialization logic (box/box-codegen[#476](https://github.com/box/box-codegen/issues/476)) ([#126](https://github.com/box/box-codegen/issues/126)) ([90ea928](https://github.com/box/box-codegen/commit/90ea928aec6bf6a2d22c7156a570d2ade57daf80)) ### New Features and Enhancements - Support Box AI endpoints (box/box-openapi[#416](https://github.com/box/box-codegen/issues/416)) ([#137](https://github.com/box/box-codegen/issues/137)) ([7a90c0c](https://github.com/box/box-codegen/commit/7a90c0c10b29af35307fd1fbb3931442c4aad06b)) - Support revoking and downscoping token for `BoxDeveloperTokenAuth` (box/box-codegen[#472](https://github.com/box/box-codegen/issues/472)) ([#115](https://github.com/box/box-codegen/issues/115)) ([1b9628c](https://github.com/box/box-codegen/commit/1b9628c321b1ade72cbadac7ef4e63e4e7b132e0)) - Support union of primitives and objects (box/box-codegen[#481](https://github.com/box/box-codegen/issues/481)) ([#140](https://github.com/box/box-codegen/issues/140)) ([d08c3e9](https://github.com/box/box-codegen/commit/d08c3e9987c3d655b2741e412cfafa48d1959b6e)) ### 0.6.4 (2024-04-04) ### Bug Fixes - **docs:** fixes for chunked uploads docs (box/box-codegen[#457](https://github.com/box/box-codegen/issues/457)) ([#106](https://github.com/box/box-codegen/issues/106)) ([65f40f5](https://github.com/box/box-codegen/commit/65f40f55a5bd020fd9e1e2db31d4979a4f10d4cf)) ### New Features and Enhancements - Assign default value to fields and args of type enum with only one value (box/box-codegen[#465](https://github.com/box/box-codegen/issues/465)) ([#108](https://github.com/box/box-codegen/issues/108)) ([f884b60](https://github.com/box/box-codegen/commit/f884b600b8be77e8fdbbff553c066a927090c42d)) - Change `asUser` and `asEnterprise` method names (box/box-codegen[#464](https://github.com/box/box-codegen/issues/464)) ([#103](https://github.com/box/box-codegen/issues/103)) ([bb03852](https://github.com/box/box-codegen/commit/bb03852443fa0c3fcd8fec60cb10e5bff607abe5)) ### 0.6.3 (2024-03-26) ### New Features and Enhancements - Support datetime (box/box-codegen[#459](https://github.com/box/box-codegen/issues/459)) ([#98](https://github.com/box/box-codegen/issues/98)) ([5a4d1eb](https://github.com/box/box-codegen/commit/5a4d1ebec872faefeecb82fbc0262ba52cb7af9a)) ### 0.6.2 (2024-03-19) ### New Features and Enhancements - Support `additionalProperties` of type any in Python and TS (box/box-codegen[#453](https://github.com/box/box-codegen/issues/453)) ([#82](https://github.com/box/box-codegen/issues/82)) ([dfe7ef0](https://github.com/box/box-codegen/commit/dfe7ef02e47ec74da72b375d0b201df4bb9e68fc)) - use getDiscriminatorsForUnion in generic serialization (box/box-codegen[#448](https://github.com/box/box-codegen/issues/448)) ([#81](https://github.com/box/box-codegen/issues/81)) ([2bb15a8](https://github.com/box/box-codegen/commit/2bb15a8067d568a5d8699f73a2d808e8049e832f)) - Update `outcomes` parameter of `StartWorkflow` (box/box-openapi[#413](https://github.com/box/box-codegen/issues/413)) ([#88](https://github.com/box/box-codegen/issues/88)) ([238216f](https://github.com/box/box-codegen/commit/238216fa55be53c4f27e14e8807be389b2d5605a)) --- ## Untitled *Type: page* IAppItemAssociationsManager List file app item associations List folder app item associations List file app item associations This is a beta… # IAppItemAssociationsManager - [List file app item associations](#list-file-app-item-associations) - [List folder app item associations](#list-folder-app-item-associations) ## List file app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the file is associated with. This includes app items associated with ancestors of the file. Assuming the context user has access to the file, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `GetFileAppItemAssociations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-app-item-associations/). ``` await client.AppItemAssociations.GetFileAppItemAssociationsAsync(fileId: fileId); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileAppItemAssociationsQueryParams` - Query parameters of getFileAppItemAssociations method headers `GetFileAppItemAssociationsHeaders` - Headers of getFileAppItemAssociations method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this file, an empty collection will be returned. This list includes app items on ancestors of this File. ## List folder app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the folder is associated with. This includes app items associated with ancestors of the folder. Assuming the context user has access to the folder, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `GetFolderAppItemAssociations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-app-item-associations/). ``` await client.AppItemAssociations.GetFolderAppItemAssociationsAsync(folderId: folderId); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderAppItemAssociationsQueryParams` - Query parameters of getFolderAppItemAssociations method headers `GetFolderAppItemAssociationsHeaders` - Headers of getFolderAppItemAssociations method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this folder an empty collection will be returned. This list includes app items on ancestors of this folder. --- ## Untitled *Type: page* IArchivesManager List archives Create archive Delete archive List archives Retrieves archives for an enterprise. This operation is performed… # IArchivesManager - [List archives](#list-archives) - [Create archive](#create-archive) - [Delete archive](#delete-archive) ## List archives Retrieves archives for an enterprise. This operation is performed by calling function `GetArchivesV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-archives/). ``` await client.Archives.GetArchivesV2025R0Async(queryParams: new GetArchivesV2025R0QueryParams() { Limit = 100 }); ``` ### Arguments queryParams `GetArchivesV2025R0QueryParams` - Query parameters of getArchivesV2025R0 method headers `GetArchivesV2025R0Headers` - Headers of getArchivesV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ArchivesV2025R0`. Returns a list of archives in the enterprise. ## Create archive Creates an archive. This operation is performed by calling function `CreateArchiveV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-archives/). ``` await client.Archives.CreateArchiveV2025R0Async(requestBody: new CreateArchiveV2025R0RequestBody(name: archiveName)); ``` ### Arguments requestBody `CreateArchiveV2025R0RequestBody` - Request body of createArchiveV2025R0 method headers `CreateArchiveV2025R0Headers` - Headers of createArchiveV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ArchiveV2025R0`. Returns a new archive object. ## Delete archive Permanently deletes an archive. This operation is performed by calling function `DeleteArchiveByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-archives-id/). ``` await client.Archives.DeleteArchiveByIdV2025R0Async(archiveId: archive.Id); ``` ### Arguments archiveId `string` - The ID of the archive. Example: "982312" headers `DeleteArchiveByIdV2025R0Headers` - Headers of deleteArchiveByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the archive has been deleted. --- ## Untitled *Type: page* IAiStudioManager List AI agents Create AI agent Update AI agent Get AI agent by agent ID Delete AI agent List AI agents Lists AI agents… # IAiStudioManager - [List AI agents](#list-ai-agents) - [Create AI agent](#create-ai-agent) - [Update AI agent](#update-ai-agent) - [Get AI agent by agent ID](#get-ai-agent-by-agent-id) - [Delete AI agent](#delete-ai-agent) ## List AI agents Lists AI agents based on the provided parameters. This operation is performed by calling function `GetAiAgents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents/). ``` await client.AiStudio.GetAiAgentsAsync(); ``` ### Arguments queryParams `GetAiAgentsQueryParams` - Query parameters of getAiAgents method headers `GetAiAgentsHeaders` - Headers of getAiAgents method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiMultipleAgentResponse`. A successful response including the agents list. ## Create AI agent Creates an AI agent. At least one of the following capabilities must be provided: `ask`, `text_gen`, `extract`. This operation is performed by calling function `CreateAiAgent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-agents/). ``` await client.AiStudio.CreateAiAgentAsync(requestBody: new CreateAiAgent(name: agentName, accessState: "enabled") { Ask = new AiStudioAgentAsk(accessState: "enabled", description: "desc1") }); ``` ### Arguments requestBody `CreateAiAgent` - Request body of createAiAgent method headers `CreateAiAgentHeaders` - Headers of createAiAgent method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Update AI agent Updates an AI agent. This operation is performed by calling function `UpdateAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-ai-agents-id/). ``` await client.AiStudio.UpdateAiAgentByIdAsync(agentId: createdAgent.Id, requestBody: new CreateAiAgent(name: agentName, accessState: "enabled") { Ask = new AiStudioAgentAsk(accessState: "disabled", description: "desc2") }); ``` ### Arguments agentId `string` - The ID of the agent to update. Example: "1234" requestBody `CreateAiAgent` - Request body of updateAiAgentById method headers `UpdateAiAgentByIdHeaders` - Headers of updateAiAgentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Get AI agent by agent ID Gets an AI Agent using the `agent_id` parameter. This operation is performed by calling function `GetAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents-id/). ``` await client.AiStudio.GetAiAgentByIdAsync(agentId: createdAgent.Id, queryParams: new GetAiAgentByIdQueryParams() { Fields = Array.AsReadOnly(new [] {"ask"}) }); ``` ### Arguments agentId `string` - The agent id to get. Example: "1234" queryParams `GetAiAgentByIdQueryParams` - Query parameters of getAiAgentById method headers `GetAiAgentByIdHeaders` - Headers of getAiAgentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiSingleAgentResponseFull`. A successful response including the agent. ## Delete AI agent Deletes an AI agent using the provided parameters. This operation is performed by calling function `DeleteAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-ai-agents-id/). ``` await client.AiStudio.DeleteAiAgentByIdAsync(agentId: createdAgent.Id); ``` ### Arguments agentId `string` - The ID of the agent to delete. Example: "1234" headers `DeleteAiAgentByIdHeaders` - Headers of deleteAiAgentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A successful response with no content. --- ## Untitled *Type: page* IAiManager Ask question Generate text Get AI agent default configuration Extract metadata (freeform) Extract metadata (structured) Ask… # IAiManager - [Ask question](#ask-question) - [Generate text](#generate-text) - [Get AI agent default configuration](#get-ai-agent-default-configuration) - [Extract metadata (freeform)](#extract-metadata-freeform) - [Extract metadata (structured)](#extract-metadata-structured) ## Ask question Sends an AI request to supported LLMs and returns an answer specifically focused on the user's question given the provided context. This operation is performed by calling function `CreateAiAsk`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-ask/). ``` await client.Ai.CreateAiAskAsync(requestBody: new AiAsk(mode: AiAskModeField.SingleItemQa, prompt: "which direction sun rises", items: Array.AsReadOnly(new [] {new AiItemAsk(id: fileToAsk.Id, type: AiItemAskTypeField.File) { Content = "Sun rises in the East" }}))); ``` ### Arguments requestBody `AiAsk` - Request body of createAiAsk method headers `CreateAiAskHeaders` - Headers of createAiAsk method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiResponseFull?`. A successful response including the answer from the LLM.No content is available to answer the question. This is returned when the request item is a hub, but content in the hubs is not indexed. To ensure content in the hub is indexed, make sure Box AI for Hubs in the Admin Console was enabled before hub creation. ## Generate text Sends an AI request to supported Large Language Models (LLMs) and returns generated text based on the provided prompt. This operation is performed by calling function `CreateAiTextGen`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-text-gen/). ``` await client.Ai.CreateAiTextGenAsync(requestBody: new AiTextGen(prompt: "Parapharse the document.s", items: Array.AsReadOnly(new [] {new AiTextGenItemsField(id: fileToAsk.Id, type: AiTextGenItemsTypeField.File) { Content = "The Earth goes around the sun. Sun rises in the East in the morning." }})) { DialogueHistory = Array.AsReadOnly(new [] {new AiDialogueHistory() { Prompt = "What does the earth go around?", Answer = "The sun", CreatedAt = Utils.DateTimeFromString(dateTime: "2021-01-01T00:00:00Z") },new AiDialogueHistory() { Prompt = "On Earth, where does the sun rise?", Answer = "East", CreatedAt = Utils.DateTimeFromString(dateTime: "2021-01-01T00:00:00Z") }}) }); ``` ### Arguments requestBody `AiTextGen` - Request body of createAiTextGen method headers `CreateAiTextGenHeaders` - Headers of createAiTextGen method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiResponse`. A successful response including the answer from the LLM. ## Get AI agent default configuration Get the AI agent default config. This operation is performed by calling function `GetAiAgentDefaultConfig`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agent-default/). ``` await client.Ai.GetAiAgentDefaultConfigAsync(queryParams: new GetAiAgentDefaultConfigQueryParams(mode: GetAiAgentDefaultConfigQueryParamsModeField.Ask) { Language = "en-US" }); ``` ### Arguments queryParams `GetAiAgentDefaultConfigQueryParams` - Query parameters of getAiAgentDefaultConfig method headers `GetAiAgentDefaultConfigHeaders` - Headers of getAiAgentDefaultConfig method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiAgentAskOrAiAgentExtractOrAiAgentExtractStructuredOrAiAgentTextGen`. A successful response including the default agent configuration. This response can be one of the following four objects: - AI agent for questions - AI agent for text generation - AI agent for freeform metadata extraction - AI agent for structured metadata extraction. The response depends on the agent configuration requested in this endpoint. ## Extract metadata (freeform) Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of key-value pairs. In this request, both the prompt and the output can be freeform. Metadata template setup before sending the request is not required. This operation is performed by calling function `CreateAiExtract`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract/). ``` await client.Ai.CreateAiExtractAsync(requestBody: new AiExtract(prompt: "firstName, lastName, location, yearOfBirth, company", items: Array.AsReadOnly(new [] {new AiItemBase(id: file.Id)}))); ``` ### Arguments requestBody `AiExtract` - Request body of createAiExtract method headers `CreateAiExtractHeaders` - Headers of createAiExtract method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiResponse`. A response including the answer from the LLM. ## Extract metadata (structured) Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. For this request, you either need a metadata template or a list of fields you want to extract. Input is **either** a metadata template or a list of fields to ensure the structure. To learn more about creating templates, see [Creating metadata templates in the Admin Console](https://support.box.com/hc/en-us/articles/360044194033-Customizing-Metadata-Templates) or use the [metadata template API](g://metadata/templates/create). This operation is performed by calling function `CreateAiExtractStructured`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract-structured/). ``` await client.Ai.CreateAiExtractStructuredAsync(requestBody: new AiExtractStructured(items: Array.AsReadOnly(new [] {new AiItemBase(id: file.Id)})) { Fields = Array.AsReadOnly(new [] {new AiExtractStructuredFieldsField(key: "firstName") { DisplayName = "First name", Description = "Person first name", Prompt = "What is the your first name?", Type = "string" },new AiExtractStructuredFieldsField(key: "lastName") { DisplayName = "Last name", Description = "Person last name", Prompt = "What is the your last name?", Type = "string" },new AiExtractStructuredFieldsField(key: "dateOfBirth") { DisplayName = "Birth date", Description = "Person date of birth", Prompt = "What is the date of your birth?", Type = "date" },new AiExtractStructuredFieldsField(key: "age") { DisplayName = "Age", Description = "Person age", Prompt = "How old are you?", Type = "float" },new AiExtractStructuredFieldsField(key: "hobby") { DisplayName = "Hobby", Description = "Person hobby", Prompt = "What is your hobby?", Type = "multiSelect", Options = Array.AsReadOnly(new [] {new AiExtractStructuredFieldsOptionsField(key: "guitar"),new AiExtractStructuredFieldsOptionsField(key: "books")}) }}) }); ``` ### Arguments requestBody `AiExtractStructured` - Request body of createAiExtractStructured method headers `CreateAiExtractStructuredHeaders` - Headers of createAiExtractStructured method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AiExtractStructuredResponse`. A successful response including the answer from the LLM. --- ## Untitled *Type: page* IAvatarsManager Get user avatar Add or update user avatar Delete user avatar Get user avatar Retrieves an image of a the user's avatar. This… # IAvatarsManager - [Get user avatar](#get-user-avatar) - [Add or update user avatar](#add-or-update-user-avatar) - [Delete user avatar](#delete-user-avatar) ## Get user avatar Retrieves an image of a the user's avatar. This operation is performed by calling function `GetUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-avatar/). ``` await client.Avatars.GetUserAvatarAsync(userId: user.Id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" headers `GetUserAvatarHeaders` - Headers of getUserAvatar method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `System.IO.Stream`. When an avatar can be found for the user the image data will be returned in the body of the response. ## Add or update user avatar Adds or updates a user avatar. This operation is performed by calling function `CreateUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-avatar/). ``` await client.Avatars.CreateUserAvatarAsync(userId: user.Id, requestBody: new CreateUserAvatarRequestBody(pic: Utils.DecodeBase64ByteStream(data: "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg==")) { PicContentType = "image/png", PicFileName = "avatar.png" }); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" requestBody `CreateUserAvatarRequestBody` - Request body of createUserAvatar method headers `CreateUserAvatarHeaders` - Headers of createUserAvatar method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UserAvatar`. `ok`: Returns the `pic_urls` object with URLs to existing user avatars that were updated.`created`: Returns the `pic_urls` object with URLS to user avatars uploaded to Box with the request. ## Delete user avatar Removes an existing user avatar. You cannot reverse this operation. This operation is performed by calling function `DeleteUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-avatar/). ``` await client.Avatars.DeleteUserAvatarAsync(userId: user.Id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" headers `DeleteUserAvatarHeaders` - Headers of deleteUserAvatar method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. `no_content`: Removes the avatar and returns an empty response. --- ## Untitled *Type: page* Authentication Authentication Authentication methods Developer Token JWT Auth Authenticate Enterprise Authenticate User Client Credentials… # Authentication - [Authentication](#authentication) [Authentication methods](#authentication-methods) - [Developer Token](#developer-token) [JWT Auth](#jwt-auth) - [Authenticate Enterprise](#authenticate-enterprise) - [Authenticate User](#authenticate-user) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) - [Switching between Service Account and User](#switching-between-service-account-and-user) [OAuth 2.0 Auth](#oauth-20-auth) - [Authentication with OAuth2](#authentication-with-oauth2) - [Injecting existing token into BoxOAuth](#injecting-existing-token-into-boxoauth) [Retrieve current access token](#retrieve-current-access-token) [Refresh access token](#refresh-access-token) [Revoke token](#revoke-token) [Downscope token](#downscope-token) [Token storage](#token-storage) - [In-memory token storage](#in-memory-token-storage) - [Custom storage](#custom-storage) # Authentication methods ## Developer Token The fastest way to get started using the API is with developer token. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. To create a `BoxClient` with a developer token, construct an `BoxDeveloperTokenAuth` object with the `token` set to the developer token and construct the client with that. ``` using Box.Sdk.Gen; var auth = new BoxDeveloperTokenAuth(token: "DEVELOPER_TOKEN_GOES_HERE"); var client = new BoxClient(auth: auth)); var me = await client.Users.GetUserMeAsync(); Console.WriteLine($"My user ID is {me.Id}"); ``` ## JWT Auth Before using JWT Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with JWT](https://developer.box.com/guides/authentication/jwt/jwt-setup/) ### Authenticate Enterprise JWT auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. If you generated your public and private keys automatically through the [Box Developer Console](https://app.box.com/developers/console), you can use the JSON file created there to configure your SDK instance and create a client to make calls as the Service Account. Call one of static `JwtConfig` methods: `JwtConfig.FromConfigFile(configFilePath)` and pass JSON file local path or `JwtConfig.FromConfigJsonString(configJsonString)` and pass JSON config file content as string. ``` using Box.Sdk.Gen; var config = JwtConfig.FromConfigFile("/path/to/settings.json"); var jwtAuth = new BoxJwtAuth(config); var client = new BoxClient(jwtAuth); var me = await client.Users.GetUserMeAsync(); Console.WriteLine($"My user ID is {me.Id}"); ``` Otherwise, you'll need to provide the necessary configuration fields directly to the `JwtConfig` constructor: ``` using Box.Sdk.Gen; var jwtConfig = new JwtConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", jwtKeyId: "YOUR_JWT_KEY_ID", privateKey: "YOUR_PRIVATE_KEY", privateKeyPassphrase: "PASSPHRASE") { EnterpriseId = "YOUR_ENTERPRISE_ID" }; var jwtAuth = new BoxJwtAuth(jwtConfig); var serviceAccountClient = new BoxClient(jwtAuth); ``` ### Authenticate User App auth applications also often have associated [App Users](https://developer.box.com/guides/getting-started/user-types/app-users/), which are created and managed directly by the application — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user to make calls as that user. See the [API documentation](https://developer.box.com/) for detailed instructions on how to use app auth. Clients for making calls as an App User can be created with the same JSON JWT config file generated through the [Box Developer Console](https://app.box.com/developers/console). Calling `jwtAuth.WithUserSubject("USER_ID")` method will return a new auth object, which is authenticated as the user with provided id, leaving the original object unchanged. ``` using Box.Sdk.Gen; var config = JwtConfig.FromConfigFile("/path/to/settings.json"); var jwtAuth = new BoxJwtAuth(config); var userAuth = jwtAuth.WithUserSubject("USER_ID"); var userClient = new BoxClient(userAuth); ``` Alternatively, clients for making calls as an App User can be created with the same `JwtConfig` constructor as in the above examples, similarly to creating a Service Account client. Simply pass the `userId` instead of `enterpriseId` when constructing the auth config instance: ``` using Box.Sdk.Gen; var jwtConfig = new JwtConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", jwtKeyId: "YOUR_JWT_KEY_ID", privateKey: "YOUR_PRIVATE_KEY", privateKeyPassphrase: "PASSPHRASE") { UserId = "USER_ID" }; var jwtAuth = new BoxJwtAuth(jwtConfig); var userClient = new BoxClient(jwtAuth); ``` ## Client Credentials Grant Before using Client Credentials Grant Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with Client Credentials Grant](https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/) Client Credentials Grant Auth method allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account. You can use `BoxCcgAuth` to initialize a client object the same way as for other authentication types: ``` using Box.Sdk.Gen; var config = new CcgConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", userId: "YOUR_USER_ID"); var auth = new BoxCcgAuth(config: config); var client = new BoxClient(auth: auth); var me = await client.Users.GetUserMeAsync(); Console.WriteLine($"My user ID is {me.Id}")); ``` Obtained token is valid for specified amount of time, it will be refreshed automatically by default. ### Obtaining Service Account token The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID with client id and secret: ``` using Box.Sdk.Gen; var config = new CcgConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET") { EnterpriseId: "YOUR_ENTERPRISE_ID" }; var auth = new BoxCcgAuth(config: config); var client = new BoxClient(auth: auth); var auth = new BoxCcgAuth(config: config); var client = new BoxClient(auth: auth); ``` ### Obtaining User token In order to enable obtaining user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/console). In `Configuration` tab, in section `Advanced Features` select `Generate user access tokens`. Do not forget to re-authorize application if it was already authorized. To obtain user account you will have to provide user ID with client id and secret. ``` using Box.Sdk.Gen; var config = new CcgConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET") { UserId: "YOUR_USER_ID" }; var auth = new BoxCcgAuth(config: config); var client = new BoxClient(auth: auth); ``` ### Switching between Service Account and User In order to switch between being authenticated as Service Account and a User you can call: ``` await auth.WithEnterpriseSubjectAsync(enterpriseId: "YOUR_ENTERPRISE_ID"); ``` to authenticate as enterprise or ``` await auth.WithUserSubjectAsync(userId: "YOUR_USER_ID"); ``` to authenticate as User with provided ID. The new token will be automatically fetched with a next API call. ## OAuth 2.0 Auth ### Authentication with OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/en/guides/authentication/oauth2/). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code. ``` using Box.Sdk.Gen; var config = new OAuthConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET"); var auth = new BoxOAuth(config: config); // the URL to redirect the user to var authorizeUrl = auth.GetAuthorizeUrl(); ``` After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirect_uri` which will contain an auth code. This auth code can then be used along with your client ID and client secret to establish an API connection. You need to provide the auth code to the SDK to obtain an access token. Calling `oauth.getTokensAuthorizationCodeGrant('code')` will exchange the auth code for an access token and save it in the `BoxOAuth` token storage. The SDK will automatically refresh the token when needed. All you need to do is create a client object with the `BoxOAuth` object and start making API calls. ``` await auth.RetrieveTokenAsync(); ``` # Refresh access token Access tokens are short-lived and need to be refreshed periodically. The SDK will automatically refresh the token when needed. If you want to manually refresh the token, you can use the following code: ``` await auth.RefreshTokenAsync(); ``` # Revoke token Access tokens for a client can be revoked when needed. This call invalidates old token. For BoxCcgAuth and BoxJwtAuth you can still reuse the `auth` object to retrieve a new token. If you make any new call after revoking the token, a new token will be automatically retrieved. For BoxOAuth it would be necessary to manually go through the authentication process again. For BoxDeveloperTokenAuth, it is necessary to provide a DeveloperTokenConfig during initialization, containing the client ID and client secret. To revoke current client's tokens in the storage use the following code: ``` await auth.RevokeTokenAsync(); ``` # Downscope token You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). A downscoped token does not include a refresh token. In such a scenario, to obtain a new downscoped token, refresh the original token and utilize the newly acquired token to obtain the downscoped token. More information about downscoping tokens can be found [here](https://developer.box.com/guides/authentication/tokens/downscope/). If you want to learn more about available scopes please go [here](https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/#scopes-for-downscoping). For example to get a new token with only `item_preview` scope, restricted to a single file, suitable for the [Content Preview UI Element](https://developer.box.com/en/guides/embed/ui-elements/preview/) you can use the following code. You can also initialize `BoxDeveloperTokenAuth` with the retrieved access token and use it to create a new Client. ``` using Box.Sdk.Gen; resourcePath = 'https://api.box.com/2.0/files/123456789' AccessToken downscopedToken = await auth.DownscopeTokenAsync( scopes: Array.AsReadOnly(new [] {"item_rename","item_preview"}), resource: resourcePath ); BoxClient downscopedClient = new BoxClient(auth: new BoxDeveloperTokenAuth(token: downscopedToken.AccessTokenField)); ``` # Token storage ## In-memory token storage By default, the SDK stores the access token in volatile memory. When rerunning your application, the access token won't be reused from the previous run; a new token has to be obtained again. To use in-memory token storage, you don't need to do anything more than create an Auth class using AuthConfig, for example, for BoxOAuth: ``` using Box.Sdk.Gen; var config = new OAuthConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET"); var auth = new BoxOAuth(config: config); ``` ## Custom storage You can also provide a custom token storage class. All you need to do is create a class that inherits from `TokenStorage` and implements all of its abstract methods. Then, pass an instance of your class to the AuthConfig constructor. ``` using Box.Sdk.Gen; class MyCustomTokenStorage : ITokenStorage { public Task StoreAsync(AccessToken token) { // store token in your custom storage } public Task<AccessToken?> GetAsync() { // retrieve token from your custom storage } public Task ClearAsync() { // clear token from your custom storage } } var config = new OAuthConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", tokenStorage: new MyCustomTokenStorage()); var auth = new BoxOAuth(config: config) ``` --- ## Untitled *Type: page* IClassificationsManager List all classifications Add classification Update classification Add initial classifications List all… # IClassificationsManager - [List all classifications](#list-all-classifications) - [Add classification](#add-classification) - [Update classification](#update-classification) - [Add initial classifications](#add-initial-classifications) ## List all classifications Retrieves the classification metadata template and lists all the classifications available to this enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `GetClassificationTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema/). ``` await client.Classifications.GetClassificationTemplateAsync(); ``` ### Arguments headers `GetClassificationTemplateHeaders` - Headers of getClassificationTemplate method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ClassificationTemplate`. Returns the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification Adds one or more new classifications to the list of classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `AddClassification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--add/). ``` await client.Classifications.AddClassificationAsync(requestBody: Array.AsReadOnly(new [] {new AddClassificationRequestBody(data: new AddClassificationRequestBodyDataField(key: Utils.GetUUID()) { StaticConfig = new AddClassificationRequestBodyDataStaticConfigField() { Classification = new AddClassificationRequestBodyDataStaticConfigClassificationField() { ColorId = 4, ClassificationDefinition = "Other description" } } })})); ``` ### Arguments requestBody `IReadOnlyList<AddClassificationRequestBody>` - Request body of addClassification method headers `AddClassificationHeaders` - Headers of addClassification method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Update classification Updates the labels and descriptions of one or more classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `UpdateClassification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--update/). ``` await client.Classifications.UpdateClassificationAsync(requestBody: Array.AsReadOnly(new [] {new UpdateClassificationRequestBody(enumOptionKey: classification.Key, data: new UpdateClassificationRequestBodyDataField(key: updatedClassificationName) { StaticConfig = new UpdateClassificationRequestBodyDataStaticConfigField() { Classification = new UpdateClassificationRequestBodyDataStaticConfigClassificationField() { ColorId = 2, ClassificationDefinition = updatedClassificationDescription } } })})); ``` ### Arguments requestBody `IReadOnlyList<UpdateClassificationRequestBody>` - Request body of updateClassification method headers `UpdateClassificationHeaders` - Headers of updateClassification method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add initial classifications When an enterprise does not yet have any classifications, this API call initializes the classification template with an initial set of classifications. If an enterprise already has a classification, the template will already exist and instead an API call should be made to add additional classifications. This operation is performed by calling function `CreateClassificationTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema--classifications/). *Currently we don't have an example for calling `CreateClassificationTemplate` in integration tests* ### Arguments requestBody `CreateClassificationTemplateRequestBody` - Request body of createClassificationTemplate method headers `CreateClassificationTemplateHeaders` - Headers of createClassificationTemplate method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ClassificationTemplate`. Returns a new `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. --- ## Untitled *Type: page* IAuthorizationManager Authorize user Request access token Refresh access token Revoke access token Authorize user Authorize a user by… # IAuthorizationManager - [Authorize user](#authorize-user) - [Request access token](#request-access-token) - [Refresh access token](#refresh-access-token) - [Revoke access token](#revoke-access-token) ## Authorize user Authorize a user by sending them through the [Box](https://box.com) website and request their permission to act on their behalf. This is the first step when authenticating a user using OAuth 2.0. To request a user's authorization to use the Box APIs on their behalf you will need to send a user to the URL with this format. This operation is performed by calling function `AuthorizeUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-authorize/). *Currently we don't have an example for calling `AuthorizeUser` in integration tests* ### Arguments queryParams `AuthorizeUserQueryParams` - Query parameters of authorizeUser method headers `AuthorizeUserHeaders` - Headers of authorizeUser method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Does not return any data, but rather should be used in the browser. ## Request access token Request an Access Token using either a client-side obtained OAuth 2.0 authorization code or a server-side JWT assertion. An Access Token is a string that enables Box to verify that a request belongs to an authorized session. In the normal order of operations you will begin by requesting authentication from the [authorize](#get-authorize) endpoint and Box will send you an authorization code. You will then send this code to this endpoint to exchange it for an Access Token. The returned Access Token can then be used to to make Box API calls. This operation is performed by calling function `RequestAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token/). *Currently we don't have an example for calling `RequestAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2Token` - Request body of requestAccessToken method headers `RequestAccessTokenHeaders` - Headers of requestAccessToken method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Refresh access token Refresh an Access Token using its client ID, secret, and refresh token. This operation is performed by calling function `RefreshAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token--refresh/). *Currently we don't have an example for calling `RefreshAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2TokenRefreshAccessToken` - Request body of refreshAccessToken method headers `RefreshAccessTokenHeaders` - Headers of refreshAccessToken method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Revoke access token Revoke an active Access Token, effectively logging a user out that has been previously authenticated. This operation is performed by calling function `RevokeAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-revoke/). *Currently we don't have an example for calling `RevokeAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2Revoke` - Request body of revokeAccessToken method headers `RevokeAccessTokenHeaders` - Headers of revokeAccessToken method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the token was successfully revoked. --- ## Untitled *Type: page* Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers… # Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers. [Make custom HTTP request](#make-custom-http-request) - [JSON request](#json-request) - [Multi-part request](#multi-part-request) - [Binary response](#binary-response) [Additional headers](#additional-headers) - [As-User header](#as-user-header) - [Suppress notifications](#suppress-notifications) - [Custom headers](#custom-headers) [Custom Base URLs](#custom-base-urls) [Use Proxy for API calls](#use-proxy-for-api-calls) # Make custom HTTP request You can make custom HTTP requests using the `client.MakeRequestAsync()` method. This method allows you to make any HTTP request to the Box API. It will automatically use authentication and network configuration settings from the client. The method accepts a `FetchOptions` object as an argument and returns a `FetchResponse` object. ## JSON request The following example demonstrates how to make a custom POST request to create a new folder in the root folder. ``` string requestBodyPost = "{\"name\": \"newFolderName\", \"parent\": {\"id\": \"0\"}}"; FetchResponse response = await client.MakeRequestAsync(fetchOptions: new FetchOptions(method: "POST", url: "https://api.box.com/2.0/folders") { Data = JsonUtils.JsonToSerializedData(text: requestBodyPost) }); Console.WriteLine("Received status code: " + response.status); Console.WriteLine("Created folder name: " + response.data["name"]); ``` ## Multi-part request The following example demonstrates how to make a custom multipart request that uploads a file to a folder. ``` string multipartAttributes = "{\"name\": \"newFileName\", \"parent\": {\"id\": \"newFolderId\"}}"; FetchResponse response = await client.MakeRequestAsync(fetchOptions: new FetchOptions(method: "POST", url: "https://upload.box.com/api/2.0/files/content", contentType: "multipart/form-data") { FileStream = fileContentStream, MultipartData = Array.AsReadOnly(new [] {new MultipartItem(partName: "attributes") { Data = JsonUtils.JsonToSerializedData(text: multipartAttributes) },new MultipartItem(partName: "file") { FileStream = fileContentStream }}) }); Console.WriteLine("Received status code: " + response.status); ``` ## Binary response The following example demonstrates how to make a custom request that expects a binary response. It is required to specify the `responseFormat` parameter in the `FetchOptions` object to `Box.Sdk.Gen.ResponseFormat.Binary`. ``` string fileId = "123456789"; FetchResponse response = await client.MakeRequestAsync(fetchOptions: new FetchOptions(method: "GET", url: string.Concat("https://api.box.com/2.0/files/", fileId, "/content"), responseFormat: Box.Sdk.Gen.ResponseFormat.Binary)); Console.WriteLine("Received status code: " + response.status); string filePath = "output.txt"; using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { responseStream.CopyTo(response.content); } ``` # Additional headers BoxClient provides a convenient methods, which allow passing additional headers, which will be included in every API call made by the client. ## As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an As-User: USER-ID header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). The following example assume that the client has been instantiated with an access token belonging to an admin-level user or Service Account with appropriate privileges to make As-User calls. Calling the `client.WithAsUserHeader()` method creates a new client to impersonate user with the provided ID. All calls made with the new client will be made in context of the impersonated user, leaving the original client unmodified. ``` var userClient = client.WithAsUserHeader(useId: "1234567"); ``` ## Suppress notifications If you are making administrative API calls (that is, your application has “Manage an Enterprise” scope, and the user signing in is a co-admin with the correct "Edit settings for your company" permission) then you can suppress both email and webhook notifications. This can be used, for example, for a virus-scanning tool to download copies of everyone’s files in an enterprise, without every collaborator on the file getting an email. All actions will still appear in users' updates feed and audit logs. **Note:** This functionality is only available for approved applications. Calling the `client.WithSuppressedNotifications()` method creates a new client. For all calls made with the new client the notifications will be suppressed. ``` var newClient = client.WithSuppressedNotifications(); ``` ## Custom headers You can also specify the custom set of headers, which will be included in every API call made by client. Calling the `client.WithExtraHeaders()` method creates a new client, leaving the original client unmodified. ``` var extraHeaders = new Dictionary<string, string?>() { { "customHeader", "customValue" } }; var newClient = client.WithExtraHeaders(extraHeaders: extraHeaders); ``` # Custom Base URLs You can also specify the custom base URLs, which will be used for API calls made by client. Calling the `client.WithCustomBaseUrls()` method creates a new client, leaving the original client unmodified. ``` var newClient = client.WithCustomBaseUrls(new BaseUrls( baseUrl: "https://api.box2.com", uploadUrl: "https://upload.box.com/api", oauth2Url: "https://account.box.com/api/oauth2" )); ``` # Use Proxy for API calls In order to use a proxy for API calls, call the `client.WithProxy(proxyConfig)` method that creates a new client with proxy, leaving the original client unmodified. In config, you can specify the username, password and domain for the proxy server. Alternatively you can set 'UseDefaultCredentials' to true to use the credentials of the currently logged on user - `DefaultCredentials`. NOTE: Setting UseDefaultCredentials takes precedence over Username, Password and Domain fields. If UseDefaultCredentials is set to true, the Username, Password and Domain fields will be ignored. ``` var newClient = client.WithProxy(new ProxyConfig("http://proxy.com") { Username = "username", Password = "password", Domain = "example" }); ``` To use proxy with default credentials: ``` var newClient = client.WithProxy(new ProxyConfig("http://proxy.com") { UseDefaultCredentials = true }); ``` --- ## Untitled *Type: page* IChunkedUploadsManager Create upload session Create upload session for existing file Get upload session by URL Get upload session Upload… # IChunkedUploadsManager - [Create upload session](#create-upload-session) - [Create upload session for existing file](#create-upload-session-for-existing-file) - [Get upload session by URL](#get-upload-session-by-url) - [Get upload session](#get-upload-session) - [Upload part of file by URL](#upload-part-of-file-by-url) - [Upload part of file](#upload-part-of-file) - [Remove upload session by URL](#remove-upload-session-by-url) - [Remove upload session](#remove-upload-session) - [List parts by URL](#list-parts-by-url) - [List parts](#list-parts) - [Commit upload session by URL](#commit-upload-session-by-url) - [Commit upload session](#commit-upload-session) - [Upload big file](#upload-big-file) ## Create upload session Creates an upload session for a new file. This operation is performed by calling function `CreateFileUploadSession`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions/). ``` await client.ChunkedUploads.CreateFileUploadSessionAsync(requestBody: new CreateFileUploadSessionRequestBody(fileName: fileName, fileSize: fileSize, folderId: parentFolderId)); ``` ### Arguments requestBody `CreateFileUploadSessionRequestBody` - Request body of createFileUploadSession method headers `CreateFileUploadSessionHeaders` - Headers of createFileUploadSession method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Create upload session for existing file Creates an upload session for an existing file. This operation is performed by calling function `CreateFileUploadSessionForExistingFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-upload-sessions/). *Currently we don't have an example for calling `CreateFileUploadSessionForExistingFile` in integration tests* ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CreateFileUploadSessionForExistingFileRequestBody` - Request body of createFileUploadSessionForExistingFile method headers `CreateFileUploadSessionForExistingFileHeaders` - Headers of createFileUploadSessionForExistingFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Get upload session by URL Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `GetFileUploadSessionByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` await client.ChunkedUploads.GetFileUploadSessionByUrlAsync(url: statusUrl); ``` ### Arguments url `string` - URL of getFileUploadSessionById method headers `GetFileUploadSessionByUrlHeaders` - Headers of getFileUploadSessionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Get upload session Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `GetFileUploadSessionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` await client.ChunkedUploads.GetFileUploadSessionByIdAsync(uploadSessionId: uploadSessionId); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" headers `GetFileUploadSessionByIdHeaders` - Headers of getFileUploadSessionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Upload part of file by URL Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `UploadFilePartByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` await client.ChunkedUploads.UploadFilePartByUrlAsync(url: acc.UploadPartUrl, requestBody: Utils.GenerateByteStreamFromBuffer(buffer: chunkBuffer), headers: new UploadFilePartByUrlHeaders(digest: digest, contentRange: contentRange)); ``` ### Arguments url `string` - URL of uploadFilePart method requestBody `System.IO.Stream` - Request body of uploadFilePart method headers `UploadFilePartByUrlHeaders` - Headers of uploadFilePart method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Upload part of file Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `UploadFilePart`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` await client.ChunkedUploads.UploadFilePartAsync(uploadSessionId: acc.UploadSessionId, requestBody: Utils.GenerateByteStreamFromBuffer(buffer: chunkBuffer), headers: new UploadFilePartHeaders(digest: digest, contentRange: contentRange)); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" requestBody `System.IO.Stream` - Request body of uploadFilePart method headers `UploadFilePartHeaders` - Headers of uploadFilePart method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Remove upload session by URL Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `DeleteFileUploadSessionByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` await client.ChunkedUploads.DeleteFileUploadSessionByUrlAsync(url: abortUrl); ``` ### Arguments url `string` - URL of deleteFileUploadSessionById method headers `DeleteFileUploadSessionByUrlHeaders` - Headers of deleteFileUploadSessionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the session was successfully aborted. ## Remove upload session Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `DeleteFileUploadSessionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` await client.ChunkedUploads.DeleteFileUploadSessionByIdAsync(uploadSessionId: uploadSessionId); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" headers `DeleteFileUploadSessionByIdHeaders` - Headers of deleteFileUploadSessionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the session was successfully aborted. ## List parts by URL Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `GetFileUploadSessionPartsByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` await client.ChunkedUploads.GetFileUploadSessionPartsByUrlAsync(url: listPartsUrl); ``` ### Arguments url `string` - URL of getFileUploadSessionParts method queryParams `GetFileUploadSessionPartsByUrlQueryParams` - Query parameters of getFileUploadSessionParts method headers `GetFileUploadSessionPartsByUrlHeaders` - Headers of getFileUploadSessionParts method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## List parts Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `GetFileUploadSessionParts`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` await client.ChunkedUploads.GetFileUploadSessionPartsAsync(uploadSessionId: uploadSessionId); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" queryParams `GetFileUploadSessionPartsQueryParams` - Query parameters of getFileUploadSessionParts method headers `GetFileUploadSessionPartsHeaders` - Headers of getFileUploadSessionParts method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## Commit upload session by URL Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `CreateFileUploadSessionCommitByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` await client.ChunkedUploads.CreateFileUploadSessionCommitByUrlAsync(url: commitUrl, requestBody: new CreateFileUploadSessionCommitByUrlRequestBody(parts: parts), headers: new CreateFileUploadSessionCommitByUrlHeaders(digest: digest)); ``` ### Arguments url `string` - URL of createFileUploadSessionCommit method requestBody `CreateFileUploadSessionCommitByUrlRequestBody` - Request body of createFileUploadSessionCommit method headers `CreateFileUploadSessionCommitByUrlHeaders` - Headers of createFileUploadSessionCommit method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Files?`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Commit upload session Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `CreateFileUploadSessionCommit`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` await client.ChunkedUploads.CreateFileUploadSessionCommitAsync(uploadSessionId: uploadSessionId, requestBody: new CreateFileUploadSessionCommitRequestBody(parts: parts), headers: new CreateFileUploadSessionCommitHeaders(digest: digest)); ``` ### Arguments uploadSessionId `string` - The ID of the upload session. Example: "D5E3F7A" requestBody `CreateFileUploadSessionCommitRequestBody` - Request body of createFileUploadSessionCommit method headers `CreateFileUploadSessionCommitHeaders` - Headers of createFileUploadSessionCommit method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Files?`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Upload big file Starts the process of chunk uploading a big file. Should return a File object representing uploaded file. This operation is performed by calling function `UploadBigFile`. ``` await client.ChunkedUploads.UploadBigFileAsync(file: fileByteStream, fileName: fileName, fileSize: fileSize, parentFolderId: parentFolderId); ``` ### Arguments file `System.IO.Stream` - The stream of the file to upload. fileName `string` - The name of the file, which will be used for storage in Box. fileSize `long` - The total size of the file for the chunked upload in bytes. parentFolderId `string` - The ID of the folder where the file should be uploaded. cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. --- ## Untitled *Type: page* ICollaborationAllowlistEntriesManager List allowed collaboration domains Add domain to list of allowed collaboration domains Get allowed… # ICollaborationAllowlistEntriesManager - [List allowed collaboration domains](#list-allowed-collaboration-domains) - [Add domain to list of allowed collaboration domains](#add-domain-to-list-of-allowed-collaboration-domains) - [Get allowed collaboration domain](#get-allowed-collaboration-domain) - [Remove domain from list of allowed collaboration domains](#remove-domain-from-list-of-allowed-collaboration-domains) ## List allowed collaboration domains Returns the list domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `GetCollaborationWhitelistEntries`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries/). ``` await client.CollaborationAllowlistEntries.GetCollaborationWhitelistEntriesAsync(); ``` ### Arguments queryParams `GetCollaborationWhitelistEntriesQueryParams` - Query parameters of getCollaborationWhitelistEntries method headers `GetCollaborationWhitelistEntriesHeaders` - Headers of getCollaborationWhitelistEntries method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationAllowlistEntries`. Returns a collection of domains that are allowed for collaboration. ## Add domain to list of allowed collaboration domains Creates a new entry in the list of allowed domains to allow collaboration for. This operation is performed by calling function `CreateCollaborationWhitelistEntry`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-entries/). ``` await client.CollaborationAllowlistEntries.CreateCollaborationWhitelistEntryAsync(requestBody: new CreateCollaborationWhitelistEntryRequestBody(direction: CreateCollaborationWhitelistEntryRequestBodyDirectionField.Inbound, domain: domain)); ``` ### Arguments requestBody `CreateCollaborationWhitelistEntryRequestBody` - Request body of createCollaborationWhitelistEntry method headers `CreateCollaborationWhitelistEntryHeaders` - Headers of createCollaborationWhitelistEntry method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns a new entry on the list of allowed domains. ## Get allowed collaboration domain Returns a domain that has been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `GetCollaborationWhitelistEntryById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries-id/). ``` await client.CollaborationAllowlistEntries.GetCollaborationWhitelistEntryByIdAsync(collaborationWhitelistEntryId: NullableUtils.Unwrap(newEntry.Id)); ``` ### Arguments collaborationWhitelistEntryId `string` - The ID of the entry in the list. Example: "213123" headers `GetCollaborationWhitelistEntryByIdHeaders` - Headers of getCollaborationWhitelistEntryById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns an entry on the list of allowed domains. ## Remove domain from list of allowed collaboration domains Removes a domain from the list of domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `DeleteCollaborationWhitelistEntryById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-entries-id/). ``` await client.CollaborationAllowlistEntries.DeleteCollaborationWhitelistEntryByIdAsync(collaborationWhitelistEntryId: NullableUtils.Unwrap(entry.Id)); ``` ### Arguments collaborationWhitelistEntryId `string` - The ID of the entry in the list. Example: "213123" headers `DeleteCollaborationWhitelistEntryByIdHeaders` - Headers of deleteCollaborationWhitelistEntryById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the entry was successfully deleted. --- ## Untitled *Type: page* ICollaborationAllowlistExemptTargetsManager List users exempt from collaboration domain restrictions Create user exemption from… # ICollaborationAllowlistExemptTargetsManager - [List users exempt from collaboration domain restrictions](#list-users-exempt-from-collaboration-domain-restrictions) - [Create user exemption from collaboration domain restrictions](#create-user-exemption-from-collaboration-domain-restrictions) - [Get user exempt from collaboration domain restrictions](#get-user-exempt-from-collaboration-domain-restrictions) - [Remove user from list of users exempt from domain restrictions](#remove-user-from-list-of-users-exempt-from-domain-restrictions) ## List users exempt from collaboration domain restrictions Returns a list of users who have been exempt from the collaboration domain restrictions. This operation is performed by calling function `GetCollaborationWhitelistExemptTargets`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets/). ``` await client.CollaborationAllowlistExemptTargets.GetCollaborationWhitelistExemptTargetsAsync(); ``` ### Arguments queryParams `GetCollaborationWhitelistExemptTargetsQueryParams` - Query parameters of getCollaborationWhitelistExemptTargets method headers `GetCollaborationWhitelistExemptTargetsHeaders` - Headers of getCollaborationWhitelistExemptTargets method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationAllowlistExemptTargets`. Returns a collection of user exemptions. ## Create user exemption from collaboration domain restrictions Exempts a user from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `CreateCollaborationWhitelistExemptTarget`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-exempt-targets/). ``` await client.CollaborationAllowlistExemptTargets.CreateCollaborationWhitelistExemptTargetAsync(requestBody: new CreateCollaborationWhitelistExemptTargetRequestBody(user: new CreateCollaborationWhitelistExemptTargetRequestBodyUserField(id: user.Id))); ``` ### Arguments requestBody `CreateCollaborationWhitelistExemptTargetRequestBody` - Request body of createCollaborationWhitelistExemptTarget method headers `CreateCollaborationWhitelistExemptTargetHeaders` - Headers of createCollaborationWhitelistExemptTarget method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns a new exemption entry. ## Get user exempt from collaboration domain restrictions Returns a users who has been exempt from the collaboration domain restrictions. This operation is performed by calling function `GetCollaborationWhitelistExemptTargetById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets-id/). ``` await client.CollaborationAllowlistExemptTargets.GetCollaborationWhitelistExemptTargetByIdAsync(collaborationWhitelistExemptTargetId: NullableUtils.Unwrap(newExemptTarget.Id)); ``` ### Arguments collaborationWhitelistExemptTargetId `string` - The ID of the exemption to the list. Example: "984923" headers `GetCollaborationWhitelistExemptTargetByIdHeaders` - Headers of getCollaborationWhitelistExemptTargetById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns the user's exempted from the list of collaboration domains. ## Remove user from list of users exempt from domain restrictions Removes a user's exemption from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `DeleteCollaborationWhitelistExemptTargetById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-exempt-targets-id/). ``` await client.CollaborationAllowlistExemptTargets.DeleteCollaborationWhitelistExemptTargetByIdAsync(collaborationWhitelistExemptTargetId: NullableUtils.Unwrap(exemptTarget.Id)); ``` ### Arguments collaborationWhitelistExemptTargetId `string` - The ID of the exemption to the list. Example: "984923" headers `DeleteCollaborationWhitelistExemptTargetByIdHeaders` - Headers of deleteCollaborationWhitelistExemptTargetById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the exemption was successfully deleted. --- ## Untitled *Type: page* IDocgenManager Get Box Doc Gen job by ID List all Box Doc Gen jobs Get Box Doc Gen jobs by batch ID Generate document using Box Doc Gen… # IDocgenManager - [Get Box Doc Gen job by ID](#get-box-doc-gen-job-by-id) - [List all Box Doc Gen jobs](#list-all-box-doc-gen-jobs) - [Get Box Doc Gen jobs by batch ID](#get-box-doc-gen-jobs-by-batch-id) - [Generate document using Box Doc Gen template](#generate-document-using-box-doc-gen-template) ## Get Box Doc Gen job by ID Get details of the Box Doc Gen job. This operation is performed by calling function `GetDocgenJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs-id/). ``` await client.Docgen.GetDocgenJobByIdV2025R0Async(jobId: docgenJobItemFromList.Id); ``` ### Arguments jobId `string` - Box Doc Gen job ID. Example: 123 headers `GetDocgenJobByIdV2025R0Headers` - Headers of getDocgenJobByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenJobV2025R0`. Details of the Box Doc Gen job. ## List all Box Doc Gen jobs Lists all Box Doc Gen jobs for a user. This operation is performed by calling function `GetDocgenJobsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs/). ``` await client.Docgen.GetDocgenJobsV2025R0Async(queryParams: new GetDocgenJobsV2025R0QueryParams() { Limit = 500 }); ``` ### Arguments queryParams `GetDocgenJobsV2025R0QueryParams` - Query parameters of getDocgenJobsV2025R0 method headers `GetDocgenJobsV2025R0Headers` - Headers of getDocgenJobsV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenJobsFullV2025R0`. A list of Box Doc Gen jobs. ## Get Box Doc Gen jobs by batch ID Lists Box Doc Gen jobs in a batch. This operation is performed by calling function `GetDocgenBatchJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-batch-jobs-id/). ``` await client.Docgen.GetDocgenBatchJobByIdV2025R0Async(batchId: docgenBatch.Id); ``` ### Arguments batchId `string` - Box Doc Gen batch ID. Example: 123 queryParams `GetDocgenBatchJobByIdV2025R0QueryParams` - Query parameters of getDocgenBatchJobByIdV2025R0 method headers `GetDocgenBatchJobByIdV2025R0Headers` - Headers of getDocgenBatchJobByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenJobsV2025R0`. Returns a list of Box Doc Gen jobs in a Box Doc Gen batch. ## Generate document using Box Doc Gen template Generates a document using a Box Doc Gen template. This operation is performed by calling function `CreateDocgenBatchV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-batches/). ``` await client.Docgen.CreateDocgenBatchV2025R0Async(requestBody: new DocGenBatchCreateRequestV2025R0(file: new FileReferenceV2025R0(id: uploadedFile.Id), inputSource: "api", destinationFolder: new DocGenBatchCreateRequestV2025R0DestinationFolderField(id: folder.Id), outputType: "pdf", documentGenerationData: Array.AsReadOnly(new [] {new DocGenDocumentGenerationDataV2025R0(generatedFileName: "test", userInput: new Dictionary<string, object>() { { "abc", "xyz" } })}))); ``` ### Arguments requestBody `DocGenBatchCreateRequestV2025R0` - Request body of createDocgenBatchV2025R0 method headers `CreateDocgenBatchV2025R0Headers` - Headers of createDocgenBatchV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenBatchBaseV2025R0`. The created Batch ID. --- ## Untitled *Type: page* ICollectionsManager List all collections List collection items Get collection by ID List all collections Retrieves all collections for a… # ICollectionsManager - [List all collections](#list-all-collections) - [List collection items](#list-collection-items) - [Get collection by ID](#get-collection-by-id) ## List all collections Retrieves all collections for a given user. Currently, only the `favorites` collection is supported. This operation is performed by calling function `GetCollections`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections/). ``` await client.Collections.GetCollectionsAsync(); ``` ### Arguments queryParams `GetCollectionsQueryParams` - Query parameters of getCollections method headers `GetCollectionsHeaders` - Headers of getCollections method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Collections`. Returns all collections for the given user. ## List collection items Retrieves the files and/or folders contained within this collection. This operation is performed by calling function `GetCollectionItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id-items/). ``` await client.Collections.GetCollectionItemsAsync(collectionId: NullableUtils.Unwrap(favouriteCollection.Id)); ``` ### Arguments collectionId `string` - The ID of the collection. Example: "926489" queryParams `GetCollectionItemsQueryParams` - Query parameters of getCollectionItems method headers `GetCollectionItemsHeaders` - Headers of getCollectionItems method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ItemsOffsetPaginated`. Returns an array of items in the collection. ## Get collection by ID Retrieves a collection by its ID. This operation is performed by calling function `GetCollectionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id/). ``` await client.Collections.GetCollectionByIdAsync(collectionId: NullableUtils.Unwrap(NullableUtils.Unwrap(collections.Entries)[0].Id)); ``` ### Arguments collectionId `string` - The ID of the collection. Example: "926489" headers `GetCollectionByIdHeaders` - Headers of getCollectionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Collection`. Returns an array of items in the collection. --- ## Untitled *Type: page* IDevicePinnersManager Get device pin Remove device pin List enterprise device pins Get device pin Retrieves information about an individual… # IDevicePinnersManager - [Get device pin](#get-device-pin) - [Remove device pin](#remove-device-pin) - [List enterprise device pins](#list-enterprise-device-pins) ## Get device pin Retrieves information about an individual device pin. This operation is performed by calling function `GetDevicePinnerById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-device-pinners-id/). ``` await client.DevicePinners.GetDevicePinnerByIdAsync(devicePinnerId: devicePinnerId); ``` ### Arguments devicePinnerId `string` - The ID of the device pin. Example: "2324234" headers `GetDevicePinnerByIdHeaders` - Headers of getDevicePinnerById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DevicePinner`. Returns information about a single device pin. ## Remove device pin Deletes an individual device pin. This operation is performed by calling function `DeleteDevicePinnerById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-device-pinners-id/). ``` await client.DevicePinners.DeleteDevicePinnerByIdAsync(devicePinnerId: devicePinnerId); ``` ### Arguments devicePinnerId `string` - The ID of the device pin. Example: "2324234" headers `DeleteDevicePinnerByIdHeaders` - Headers of deleteDevicePinnerById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the pin has been deleted. ## List enterprise device pins Retrieves all the device pins within an enterprise. The user must have admin privileges, and the application needs the "manage enterprise" scope to make this call. This operation is performed by calling function `GetEnterpriseDevicePinners`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-enterprises-id-device-pinners/). ``` await client.DevicePinners.GetEnterpriseDevicePinnersAsync(enterpriseId: enterpriseId); ``` ### Arguments enterpriseId `string` - The ID of the enterprise. Example: "3442311" queryParams `GetEnterpriseDevicePinnersQueryParams` - Query parameters of getEnterpriseDevicePinners method headers `GetEnterpriseDevicePinnersHeaders` - Headers of getEnterpriseDevicePinners method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DevicePinners`. Returns a list of device pins for a given enterprise. --- ## Untitled *Type: page* ICommentsManager List file comments Get comment Update comment Remove comment Create comment List file comments Retrieves a list of comments… # ICommentsManager - [List file comments](#list-file-comments) - [Get comment](#get-comment) - [Update comment](#update-comment) - [Remove comment](#remove-comment) - [Create comment](#create-comment) ## List file comments Retrieves a list of comments for a file. This operation is performed by calling function `GetFileComments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-comments/). ``` await client.Comments.GetFileCommentsAsync(fileId: fileId); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileCommentsQueryParams` - Query parameters of getFileComments method headers `GetFileCommentsHeaders` - Headers of getFileComments method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Comments`. Returns a collection of comment objects. If there are no comments on this file an empty collection will be returned. ## Get comment Retrieves the message and metadata for a specific comment, as well as information on the user who created the comment. This operation is performed by calling function `GetCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-comments-id/). ``` await client.Comments.GetCommentByIdAsync(commentId: NullableUtils.Unwrap(newComment.Id)); ``` ### Arguments commentId `string` - The ID of the comment. Example: "12345" queryParams `GetCommentByIdQueryParams` - Query parameters of getCommentById method headers `GetCommentByIdHeaders` - Headers of getCommentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CommentFull`. Returns a full comment object. ## Update comment Update the message of a comment. This operation is performed by calling function `UpdateCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-comments-id/). ``` await client.Comments.UpdateCommentByIdAsync(commentId: NullableUtils.Unwrap(newReplyComment.Id), requestBody: new UpdateCommentByIdRequestBody() { Message = newMessage }); ``` ### Arguments commentId `string` - The ID of the comment. Example: "12345" requestBody `UpdateCommentByIdRequestBody` - Request body of updateCommentById method queryParams `UpdateCommentByIdQueryParams` - Query parameters of updateCommentById method headers `UpdateCommentByIdHeaders` - Headers of updateCommentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CommentFull`. Returns the updated comment object. ## Remove comment Permanently deletes a comment. This operation is performed by calling function `DeleteCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-comments-id/). ``` await client.Comments.DeleteCommentByIdAsync(commentId: NullableUtils.Unwrap(newComment.Id)); ``` ### Arguments commentId `string` - The ID of the comment. Example: "12345" headers `DeleteCommentByIdHeaders` - Headers of deleteCommentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the comment has been deleted. ## Create comment Adds a comment by the user to a specific file, or as a reply to an other comment. This operation is performed by calling function `CreateComment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-comments/). ``` await client.Comments.CreateCommentAsync(requestBody: new CreateCommentRequestBody(message: message, item: new CreateCommentRequestBodyItemField(id: fileId, type: CreateCommentRequestBodyItemTypeField.File))); ``` ### Arguments requestBody `CreateCommentRequestBody` - Request body of createComment method queryParams `CreateCommentQueryParams` - Query parameters of createComment method headers `CreateCommentHeaders` - Headers of createComment method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CommentFull`. Returns the newly created comment object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* IDocgenTemplateManager Create Box Doc Gen template List Box Doc Gen templates Delete Box Doc Gen template Get Box Doc Gen template by ID… # IDocgenTemplateManager - [Create Box Doc Gen template](#create-box-doc-gen-template) - [List Box Doc Gen templates](#list-box-doc-gen-templates) - [Delete Box Doc Gen template](#delete-box-doc-gen-template) - [Get Box Doc Gen template by ID](#get-box-doc-gen-template-by-id) - [List all Box Doc Gen template tags in template](#list-all-box-doc-gen-template-tags-in-template) - [Get list of all Box Doc Gen jobs for template](#get-list-of-all-box-doc-gen-jobs-for-template) ## Create Box Doc Gen template Marks a file as a Box Doc Gen template. This operation is performed by calling function `CreateDocgenTemplateV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-templates/). ``` await client.DocgenTemplate.CreateDocgenTemplateV2025R0Async(requestBody: new DocGenTemplateCreateRequestV2025R0(file: new FileReferenceV2025R0(id: file.Id))); ``` ### Arguments requestBody `DocGenTemplateCreateRequestV2025R0` - Request body of createDocgenTemplateV2025R0 method headers `CreateDocgenTemplateV2025R0Headers` - Headers of createDocgenTemplateV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenTemplateBaseV2025R0`. The file which has now been marked as a Box Doc Gen template. ## List Box Doc Gen templates Lists Box Doc Gen templates on which the user is a collaborator. This operation is performed by calling function `GetDocgenTemplatesV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates/). ``` await client.DocgenTemplate.GetDocgenTemplatesV2025R0Async(); ``` ### Arguments queryParams `GetDocgenTemplatesV2025R0QueryParams` - Query parameters of getDocgenTemplatesV2025R0 method headers `GetDocgenTemplatesV2025R0Headers` - Headers of getDocgenTemplatesV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenTemplatesV2025R0`. Returns a collection of templates. ## Delete Box Doc Gen template Unmarks file as Box Doc Gen template. This operation is performed by calling function `DeleteDocgenTemplateByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-docgen-templates-id/). ``` await client.DocgenTemplate.DeleteDocgenTemplateByIdV2025R0Async(templateId: NullableUtils.Unwrap(createdDocgenTemplate.File).Id); ``` ### Arguments templateId `string` - ID of the file which will no longer be marked as a Box Doc Gen template. Example: "123" headers `DeleteDocgenTemplateByIdV2025R0Headers` - Headers of deleteDocgenTemplateByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when a file is no longer marked as a Box Doc Gen template. ## Get Box Doc Gen template by ID Lists details of a specific Box Doc Gen template. This operation is performed by calling function `GetDocgenTemplateByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id/). ``` await client.DocgenTemplate.GetDocgenTemplateByIdV2025R0Async(templateId: NullableUtils.Unwrap(createdDocgenTemplate.File).Id); ``` ### Arguments templateId `string` - The ID of a Box Doc Gen template. Example: 123 headers `GetDocgenTemplateByIdV2025R0Headers` - Headers of getDocgenTemplateByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenTemplateV2025R0`. Returns a template. ## List all Box Doc Gen template tags in template Lists all tags in a Box Doc Gen template. This operation is performed by calling function `GetDocgenTemplateTagsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id-tags/). ``` await client.DocgenTemplate.GetDocgenTemplateTagsV2025R0Async(templateId: NullableUtils.Unwrap(fetchedDocgenTemplate.File).Id); ``` ### Arguments templateId `string` - ID of template. Example: 123 queryParams `GetDocgenTemplateTagsV2025R0QueryParams` - Query parameters of getDocgenTemplateTagsV2025R0 method headers `GetDocgenTemplateTagsV2025R0Headers` - Headers of getDocgenTemplateTagsV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenTagsV2025R0`. A list of document generation template tags.Processing tags for the file. ## Get list of all Box Doc Gen jobs for template Lists the users jobs which use this template. This operation is performed by calling function `GetDocgenTemplateJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-template-jobs-id/). ``` await client.DocgenTemplate.GetDocgenTemplateJobByIdV2025R0Async(templateId: NullableUtils.Unwrap(fetchedDocgenTemplate.File).Id); ``` ### Arguments templateId `string` - Id of template to fetch jobs for. Example: 123 queryParams `GetDocgenTemplateJobByIdV2025R0QueryParams` - Query parameters of getDocgenTemplateJobByIdV2025R0 method headers `GetDocgenTemplateJobByIdV2025R0Headers` - Headers of getDocgenTemplateJobByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `DocGenJobsV2025R0`. A single Box Doc Gen template. --- ## Untitled *Type: page* IDownloadsManager Download file URL Download file Download file URL Get the download URL without downloading the content. This operation is… # IDownloadsManager - [Download file URL](#download-file-url) - [Download file](#download-file) ## Download file URL Get the download URL without downloading the content. This operation is performed by calling function `GetDownloadFileUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-content/). ``` await client.Downloads.GetDownloadFileUrlAsync(fileId: uploadedFile.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetDownloadFileUrlQueryParams` - Query parameters of downloadFile method headers `GetDownloadFileUrlHeaders` - Headers of downloadFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `string`. Returns the requested file if the client has the follow redirects setting enabled to automatically follow HTTP `3xx` responses as redirects. If not, the request will return `302` instead. For details, see the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. ## Download file Returns the contents of a file in binary format. This operation is performed by calling function `DownloadFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-content/). ``` await client.Downloads.DownloadFileAsync(fileId: uploadedFile.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `DownloadFileQueryParams` - Query parameters of downloadFile method headers `DownloadFileHeaders` - Headers of downloadFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `System.IO.Stream?`. Returns the requested file if the client has the follow redirects setting enabled to automatically follow HTTP `3xx` responses as redirects. If not, the request will return `302` instead. For details, see the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. --- ## Untitled *Type: page* IEmailAliasesManager List user's email aliases Create email alias Remove email alias List user's email aliases Retrieves all email aliases… # IEmailAliasesManager - [List user's email aliases](#list-users-email-aliases) - [Create email alias](#create-email-alias) - [Remove email alias](#remove-email-alias) ## List user's email aliases Retrieves all email aliases for a user. The collection does not include the primary login for the user. This operation is performed by calling function `GetUserEmailAliases`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-email-aliases/). ``` await client.EmailAliases.GetUserEmailAliasesAsync(userId: newUser.Id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" headers `GetUserEmailAliasesHeaders` - Headers of getUserEmailAliases method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `EmailAliases`. Returns a collection of email aliases. ## Create email alias Adds a new email alias to a user account.. This operation is performed by calling function `CreateUserEmailAlias`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-email-aliases/). ``` await client.EmailAliases.CreateUserEmailAliasAsync(userId: newUser.Id, requestBody: new CreateUserEmailAliasRequestBody(email: newAliasEmail)); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" requestBody `CreateUserEmailAliasRequestBody` - Request body of createUserEmailAlias method headers `CreateUserEmailAliasHeaders` - Headers of createUserEmailAlias method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `EmailAlias`. Returns the newly created email alias object. ## Remove email alias Removes an email alias from a user. This operation is performed by calling function `DeleteUserEmailAliasById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-email-aliases-id/). ``` await client.EmailAliases.DeleteUserEmailAliasByIdAsync(userId: newUser.Id, emailAliasId: NullableUtils.Unwrap(newAlias.Id)); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" emailAliasId `string` - The ID of the email alias. Example: "23432" headers `DeleteUserEmailAliasByIdHeaders` - Headers of deleteUserEmailAliasById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Removes the alias and returns an empty response. --- ## Untitled *Type: page* IEventsManager Get events long poll endpoint List user and enterprise events Get events long poll endpoint Returns a list of real-time… # IEventsManager - [Get events long poll endpoint](#get-events-long-poll-endpoint) - [List user and enterprise events](#list-user-and-enterprise-events) ## Get events long poll endpoint Returns a list of real-time servers that can be used for long-polling updates to the [event stream](#get-events). Long polling is the concept where a HTTP request is kept open until the server sends a response, then repeating the process over and over to receive updated responses. Long polling the event stream can only be used for user events, not for enterprise events. To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next, make a long poll request to any of the provided URLs. When an event occurs in monitored account a response with the value `new_change` will be sent. The response contains no other details as it only serves as a prompt to take further action such as sending a request to the [events endpoint](#get-events) with the last known `stream_position`. After the server sends this response it closes the connection. You must now repeat the long poll process to begin listening for events again. If no events occur for a while and the connection times out you will receive a response with the value `reconnect`. When you receive this response you’ll make another call to this endpoint to restart the process. If you receive no events in `retry_timeout` seconds then you will need to make another request to the real-time server (one of the URLs in the response for this endpoint). This might be necessary due to network errors. Finally, if you receive a `max_retries` error when making a request to the real-time server, you should start over by making a call to this endpoint first. This operation is performed by calling function `GetEventsWithLongPolling`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-events/). ``` await client.Events.GetEventsWithLongPollingAsync(); ``` ### Arguments headers `GetEventsWithLongPollingHeaders` - Headers of getEventsWithLongPolling method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RealtimeServers`. Returns a paginated array of servers that can be used instead of the regular endpoints for long-polling events. ## List user and enterprise events Returns up to a year of past events for a given user or for the entire enterprise. By default this returns events for the authenticated user. To retrieve events for the entire enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events, or `admin_logs` for querying across historical events. The user making the API call will need to have admin privileges, and the application will need to have the scope `manage enterprise properties` checked. This operation is performed by calling function `GetEvents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-events/). ``` await client.Events.GetEventsAsync(); ``` ### Arguments queryParams `GetEventsQueryParams` - Query parameters of getEvents method headers `GetEventsHeaders` - Headers of getEvents method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Events`. Returns a list of event objects. Events objects are returned in pages, with each page (chunk) including a list of event objects. The response includes a `chunk_size` parameter indicating how many events were returned in this chunk, as well as the next `stream_position` that can be queried. --- ## Untitled *Type: page* IFileClassificationsManager Get classification on file Add classification to file Update classification on file Remove classification from… # IFileClassificationsManager - [Get classification on file](#get-classification-on-file) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Remove classification from file](#remove-classification-from-file) ## Get classification on file Retrieves the classification metadata instance that has been applied to a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `GetClassificationOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.FileClassifications.GetClassificationOnFileAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetClassificationOnFileHeaders` - Headers of getClassificationOnFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to file Adds a classification to a file by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `AddClassificationToFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.FileClassifications.AddClassificationToFileAsync(fileId: file.Id, requestBody: new AddClassificationToFileRequestBody() { BoxSecurityClassificationKey = classification.Key }); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `AddClassificationToFileRequestBody` - Request body of addClassificationToFile method headers `AddClassificationToFileHeaders` - Headers of addClassificationToFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the file. ## Update classification on file Updates a classification on a file. The classification can only be updated if a classification has already been applied to the file before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `UpdateClassificationOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.FileClassifications.UpdateClassificationOnFileAsync(fileId: file.Id, requestBody: Array.AsReadOnly(new [] {new UpdateClassificationOnFileRequestBody(value: secondClassification.Key)})); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `IReadOnlyList<UpdateClassificationOnFileRequestBody>` - Request body of updateClassificationOnFile method headers `UpdateClassificationOnFileHeaders` - Headers of updateClassificationOnFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from file Removes any classifications from a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `DeleteClassificationFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.FileClassifications.DeleteClassificationFromFileAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteClassificationFromFileHeaders` - Headers of deleteClassificationFromFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* IFileVersionLegalHoldsManager Get file version legal hold List file version legal holds Get file version legal hold Retrieves information… # IFileVersionLegalHoldsManager - [Get file version legal hold](#get-file-version-legal-hold) - [List file version legal holds](#list-file-version-legal-holds) ## Get file version legal hold Retrieves information about the legal hold policies assigned to a file version. This operation is performed by calling function `GetFileVersionLegalHoldById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds-id/). ``` await client.FileVersionLegalHolds.GetFileVersionLegalHoldByIdAsync(fileVersionLegalHoldId: fileVersionLegalHoldId); ``` ### Arguments fileVersionLegalHoldId `string` - The ID of the file version legal hold. Example: "2348213" headers `GetFileVersionLegalHoldByIdHeaders` - Headers of getFileVersionLegalHoldById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersionLegalHold`. Returns the legal hold policy assignments for the file version. ## List file version legal holds Get a list of file versions on legal hold for a legal hold assignment. Due to ongoing re-architecture efforts this API might not return all file versions for this policy ID. Instead, this API will only return file versions held in the legacy architecture. Two new endpoints will available to request any file versions held in the new architecture. For file versions held in the new architecture, the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API can be used to return all past file versions available for this policy assignment, and the `GET /legal_hold_policy_assignments/:id/files_on_hold` API can be used to return any current (latest) versions of a file under legal hold. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. Once the re-architecture is completed this API will be deprecated. This operation is performed by calling function `GetFileVersionLegalHolds`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds/). ``` await client.FileVersionLegalHolds.GetFileVersionLegalHoldsAsync(queryParams: new GetFileVersionLegalHoldsQueryParams(policyId: policyId)); ``` ### Arguments queryParams `GetFileVersionLegalHoldsQueryParams` - Query parameters of getFileVersionLegalHolds method headers `GetFileVersionLegalHoldsHeaders` - Headers of getFileVersionLegalHolds method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersionLegalHolds`. Returns the list of file version legal holds for a specific legal hold policy. --- ## Untitled *Type: page* IFileMetadataManager List metadata instances on file Get metadata instance on file Create metadata instance on file Update metadata instance… # IFileMetadataManager - [List metadata instances on file](#list-metadata-instances-on-file) - [Get metadata instance on file](#get-metadata-instance-on-file) - [Create metadata instance on file](#create-metadata-instance-on-file) - [Update metadata instance on file](#update-metadata-instance-on-file) - [Remove metadata instance from file](#remove-metadata-instance-from-file) ## List metadata instances on file Retrieves all metadata for a given file. This operation is performed by calling function `GetFileMetadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata/). ``` await client.FileMetadata.GetFileMetadataAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileMetadataHeaders` - Headers of getFileMetadata method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Get metadata instance on file Retrieves the instance of a metadata template that has been applied to a file. This operation is performed by calling function `GetFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-id-id/). ``` await client.FileMetadata.GetFileMetadataByIdAsync(fileId: file.Id, scope: GetFileMetadataByIdScope.Global, templateKey: "properties"); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `GetFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" headers `GetFileMetadataByIdHeaders` - Headers of getFileMetadataById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on file Applies an instance of a metadata template to a file. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. This operation is performed by calling function `CreateFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-id-id/). ``` await client.FileMetadata.CreateFileMetadataByIdAsync(fileId: file.Id, scope: CreateFileMetadataByIdScope.Enterprise, templateKey: templateKey, requestBody: new Dictionary<string, object>() { { "name", "John" }, { "age", 23 }, { "birthDate", "2001-01-03T02:20:50.520Z" }, { "countryCode", "US" }, { "sports", Array.AsReadOnly(new [] {"basketball","tennis"}) } }); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `CreateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `Dictionary<string, object>` - Request body of createFileMetadataById method headers `CreateFileMetadataByIdHeaders` - Headers of createFileMetadataById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update metadata instance on file Updates a piece of metadata on a file. The metadata instance can only be updated if the template has already been applied to the file before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `UpdateFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-id-id/). ``` await client.FileMetadata.UpdateFileMetadataByIdAsync(fileId: file.Id, scope: UpdateFileMetadataByIdScope.Enterprise, templateKey: templateKey, requestBody: Array.AsReadOnly(new [] {new UpdateFileMetadataByIdRequestBody() { Op = UpdateFileMetadataByIdRequestBodyOpField.Replace, Path = "/name", Value = "Jack" },new UpdateFileMetadataByIdRequestBody() { Op = UpdateFileMetadataByIdRequestBodyOpField.Replace, Path = "/age", Value = 24 },new UpdateFileMetadataByIdRequestBody() { Op = UpdateFileMetadataByIdRequestBodyOpField.Replace, Path = "/birthDate", Value = "2000-01-03T02:20:50.520Z" },new UpdateFileMetadataByIdRequestBody() { Op = UpdateFileMetadataByIdRequestBodyOpField.Replace, Path = "/countryCode", Value = "CA" },new UpdateFileMetadataByIdRequestBody() { Op = UpdateFileMetadataByIdRequestBodyOpField.Replace, Path = "/sports", Value = Array.AsReadOnly(new [] {"football"}) }})); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `UpdateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `IReadOnlyList<UpdateFileMetadataByIdRequestBody>` - Request body of updateFileMetadataById method headers `UpdateFileMetadataByIdHeaders` - Headers of updateFileMetadataById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from file Deletes a piece of file metadata. This operation is performed by calling function `DeleteFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-id-id/). ``` await client.FileMetadata.DeleteFileMetadataByIdAsync(fileId: file.Id, scope: DeleteFileMetadataByIdScope.Enterprise, templateKey: templateKey); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `DeleteFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" headers `DeleteFileMetadataByIdHeaders` - Headers of deleteFileMetadataById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* IFileRequestsManager Get file request Update file request Delete file request Copy file request Get file request Retrieves the information… # IFileRequestsManager - [Get file request](#get-file-request) - [Update file request](#update-file-request) - [Delete file request](#delete-file-request) - [Copy file request](#copy-file-request) ## Get file request Retrieves the information about a file request. This operation is performed by calling function `GetFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-requests-id/). ``` await client.FileRequests.GetFileRequestByIdAsync(fileRequestId: fileRequestId); ``` ### Arguments fileRequestId `string` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" headers `GetFileRequestByIdHeaders` - Headers of getFileRequestById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileRequest`. Returns a file request object. ## Update file request Updates a file request. This can be used to activate or deactivate a file request. This operation is performed by calling function `UpdateFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-file-requests-id/). ``` await client.FileRequests.UpdateFileRequestByIdAsync(fileRequestId: copiedFileRequest.Id, requestBody: new FileRequestUpdateRequest() { Title = "updated title", Description = "updated description" }); ``` ### Arguments fileRequestId `string` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" requestBody `FileRequestUpdateRequest` - Request body of updateFileRequestById method headers `UpdateFileRequestByIdHeaders` - Headers of updateFileRequestById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileRequest`. Returns the updated file request object. ## Delete file request Deletes a file request permanently. This operation is performed by calling function `DeleteFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-file-requests-id/). ``` await client.FileRequests.DeleteFileRequestByIdAsync(fileRequestId: updatedFileRequest.Id); ``` ### Arguments fileRequestId `string` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" headers `DeleteFileRequestByIdHeaders` - Headers of deleteFileRequestById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the file request has been successfully deleted. ## Copy file request Copies an existing file request that is already present on one folder, and applies it to another folder. This operation is performed by calling function `CreateFileRequestCopy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-file-requests-id-copy/). ``` await client.FileRequests.CreateFileRequestCopyAsync(fileRequestId: fileRequestId, requestBody: new FileRequestCopyRequest(folder: new FileRequestCopyRequestFolderField(id: fileRequest.Folder.Id) { Type = FileRequestCopyRequestFolderTypeField.Folder })); ``` ### Arguments fileRequestId `string` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" requestBody `FileRequestCopyRequest` - Request body of createFileRequestCopy method headers `CreateFileRequestCopyHeaders` - Headers of createFileRequestCopy method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileRequest`. Returns updated file request object. --- ## Untitled *Type: page* IFileWatermarksManager Get watermark on file Apply watermark to file Remove watermark from file Get watermark on file Retrieve the watermark… # IFileWatermarksManager - [Get watermark on file](#get-watermark-on-file) - [Apply watermark to file](#apply-watermark-to-file) - [Remove watermark from file](#remove-watermark-from-file) ## Get watermark on file Retrieve the watermark for a file. This operation is performed by calling function `GetFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-watermark/). ``` await client.FileWatermarks.GetFileWatermarkAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileWatermarkHeaders` - Headers of getFileWatermark method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this file. ## Apply watermark to file Applies or update a watermark on a file. This operation is performed by calling function `UpdateFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-watermark/). ``` await client.FileWatermarks.UpdateFileWatermarkAsync(fileId: file.Id, requestBody: new UpdateFileWatermarkRequestBody(watermark: new UpdateFileWatermarkRequestBodyWatermarkField(imprint: UpdateFileWatermarkRequestBodyWatermarkImprintField.Default))); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateFileWatermarkRequestBody` - Request body of updateFileWatermark method headers `UpdateFileWatermarkHeaders` - Headers of updateFileWatermark method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this file.Returns a new watermark if no watermark existed on this file yet. ## Remove watermark from file Removes the watermark from a file. This operation is performed by calling function `DeleteFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-watermark/). ``` await client.FileWatermarks.DeleteFileWatermarkAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteFileWatermarkHeaders` - Headers of deleteFileWatermark method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Removes the watermark and returns an empty response. --- ## Untitled *Type: page* IFileVersionRetentionsManager List file version retentions Get retention on file List file version retentions Retrieves all file version… # IFileVersionRetentionsManager - [List file version retentions](#list-file-version-retentions) - [Get retention on file](#get-retention-on-file) ## List file version retentions Retrieves all file version retentions for the given enterprise. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `GetFileVersionRetentions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions/). ``` await client.FileVersionRetentions.GetFileVersionRetentionsAsync(); ``` ### Arguments queryParams `GetFileVersionRetentionsQueryParams` - Query parameters of getFileVersionRetentions method headers `GetFileVersionRetentionsHeaders` - Headers of getFileVersionRetentions method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersionRetentions`. Returns a list of all file version retentions for the enterprise. ## Get retention on file Returns information about a file version retention. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `GetFileVersionRetentionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions-id/). ``` await client.FileVersionRetentions.GetFileVersionRetentionByIdAsync(fileVersionRetentionId: NullableUtils.Unwrap(fileVersionRetention.Id)); ``` ### Arguments fileVersionRetentionId `string` - The ID of the file version retention. Example: "3424234" headers `GetFileVersionRetentionByIdHeaders` - Headers of getFileVersionRetentionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersionRetention`. Returns a file version retention object. --- ## Untitled *Type: page* IFolderClassificationsManager Get classification on folder Add classification to folder Update classification on folder Remove… # IFolderClassificationsManager - [Get classification on folder](#get-classification-on-folder) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Get classification on folder Retrieves the classification metadata instance that has been applied to a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `GetClassificationOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.FolderClassifications.GetClassificationOnFolderAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetClassificationOnFolderHeaders` - Headers of getClassificationOnFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to folder Adds a classification to a folder by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `AddClassificationToFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.FolderClassifications.AddClassificationToFolderAsync(folderId: folder.Id, requestBody: new AddClassificationToFolderRequestBody() { BoxSecurityClassificationKey = classification.Key }); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `AddClassificationToFolderRequestBody` - Request body of addClassificationToFolder method headers `AddClassificationToFolderHeaders` - Headers of addClassificationToFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the folder. ## Update classification on folder Updates a classification on a folder. The classification can only be updated if a classification has already been applied to the folder before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `UpdateClassificationOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.FolderClassifications.UpdateClassificationOnFolderAsync(folderId: folder.Id, requestBody: Array.AsReadOnly(new [] {new UpdateClassificationOnFolderRequestBody(value: secondClassification.Key)})); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `IReadOnlyList<UpdateClassificationOnFolderRequestBody>` - Request body of updateClassificationOnFolder method headers `UpdateClassificationOnFolderHeaders` - Headers of updateClassificationOnFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from folder Removes any classifications from a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `DeleteClassificationFromFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` await client.FolderClassifications.DeleteClassificationFromFolderAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteClassificationFromFolderHeaders` - Headers of deleteClassificationFromFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* IFileVersionsManager List all file versions Get file version Remove file version Restore file version Promote file version List all file… # IFileVersionsManager - [List all file versions](#list-all-file-versions) - [Get file version](#get-file-version) - [Remove file version](#remove-file-version) - [Restore file version](#restore-file-version) - [Promote file version](#promote-file-version) ## List all file versions Retrieve a list of the past versions for a file. Versions are only tracked by Box users with premium accounts. To fetch the ID of the current version of a file, use the `GET /file/:id` API. This operation is performed by calling function `GetFileVersions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions/). ``` await client.FileVersions.GetFileVersionsAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileVersionsQueryParams` - Query parameters of getFileVersions method headers `GetFileVersionsHeaders` - Headers of getFileVersions method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersions`. Returns an array of past versions for this file. ## Get file version Retrieve a specific version of a file. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `GetFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions-id/). ``` await client.FileVersions.GetFileVersionByIdAsync(fileId: file.Id, fileVersionId: NullableUtils.Unwrap(fileVersions.Entries)[0].Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `string` - The ID of the file version. Example: "1234" queryParams `GetFileVersionByIdQueryParams` - Query parameters of getFileVersionById method headers `GetFileVersionByIdHeaders` - Headers of getFileVersionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersionFull`. Returns a specific version of a file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Remove file version Move a file version to the trash. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `DeleteFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-versions-id/). ``` await client.FileVersions.DeleteFileVersionByIdAsync(fileId: file.Id, fileVersionId: fileVersion.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `string` - The ID of the file version. Example: "1234" headers `DeleteFileVersionByIdHeaders` - Headers of deleteFileVersionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the file has been successfully deleted. ## Restore file version Restores a specific version of a file after it was deleted. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `UpdateFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-versions-id/). ``` await client.FileVersions.UpdateFileVersionByIdAsync(fileId: file.Id, fileVersionId: fileVersion.Id, requestBody: new UpdateFileVersionByIdRequestBody() { TrashedAt = null }); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `string` - The ID of the file version. Example: "1234" requestBody `UpdateFileVersionByIdRequestBody` - Request body of updateFileVersionById method headers `UpdateFileVersionByIdHeaders` - Headers of updateFileVersionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersionFull`. Returns a restored file version object. ## Promote file version Promote a specific version of a file. If previous versions exist, this method can be used to promote one of the older versions to the top of the version history. This creates a new copy of the old version and puts it at the top of the versions history. The file will have the exact same contents as the older version, with the the same hash digest, `etag`, and name as the original. Other properties such as comments do not get updated to their former values. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `PromoteFileVersion`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-versions-current/). ``` await client.FileVersions.PromoteFileVersionAsync(fileId: file.Id, requestBody: new PromoteFileVersionRequestBody() { Id = NullableUtils.Unwrap(fileVersions.Entries)[0].Id, Type = PromoteFileVersionRequestBodyTypeField.FileVersion }); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `PromoteFileVersionRequestBody` - Request body of promoteFileVersion method queryParams `PromoteFileVersionQueryParams` - Query parameters of promoteFileVersion method headers `PromoteFileVersionHeaders` - Headers of promoteFileVersion method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileVersionFull`. Returns a newly created file version object. --- ## Untitled *Type: page* IFilesManager Get file information Update file Delete file Copy file Get file thumbnail URL Get file thumbnail Get file information… # IFilesManager - [Get file information](#get-file-information) - [Update file](#update-file) - [Delete file](#delete-file) - [Copy file](#copy-file) - [Get file thumbnail URL](#get-file-thumbnail-url) - [Get file thumbnail](#get-file-thumbnail) ## Get file information Retrieves the details about a file. This operation is performed by calling function `GetFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id/). ``` await client.Files.GetFileByIdAsync(fileId: uploadedFile.Id, queryParams: new GetFileByIdQueryParams() { Fields = Array.AsReadOnly(new [] {"is_externally_owned","has_collaborations"}) }); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileByIdQueryParams` - Query parameters of getFileById method headers `GetFileByIdHeaders` - Headers of getFileById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update file Updates a file. This can be used to rename or move a file, create a shared link, or lock a file. This operation is performed by calling function `UpdateFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id/). ``` await client.Files.UpdateFileByIdAsync(fileId: fileToUpdate.Id, requestBody: new UpdateFileByIdRequestBody() { Name = updatedName, Description = "Updated description" }); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateFileByIdRequestBody` - Request body of updateFileById method queryParams `UpdateFileByIdQueryParams` - Query parameters of updateFileById method headers `UpdateFileByIdHeaders` - Headers of updateFileById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Delete file Deletes a file, either permanently or by moving it to the trash. The the enterprise settings determine whether the item will be permanently deleted from Box or moved to the trash. This operation is performed by calling function `DeleteFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id/). ``` await client.Files.DeleteFileByIdAsync(fileId: thumbnailFile.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteFileByIdHeaders` - Headers of deleteFileById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the file has been successfully deleted. ## Copy file Creates a copy of a file. This operation is performed by calling function `CopyFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-copy/). ``` await client.Files.CopyFileAsync(fileId: fileOrigin.Id, requestBody: new CopyFileRequestBody(parent: new CopyFileRequestBodyParentField(id: "0")) { Name = copiedFileName }); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CopyFileRequestBody` - Request body of copyFile method queryParams `CopyFileQueryParams` - Query parameters of copyFile method headers `CopyFileHeaders` - Headers of copyFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. Returns a new file object representing the copied file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Get file thumbnail URL Get the download URL without downloading the content. This operation is performed by calling function `GetFileThumbnailUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` await client.Files.GetFileThumbnailUrlAsync(fileId: thumbnailFile.Id, extension: GetFileThumbnailUrlExtension.Png); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension `GetFileThumbnailUrlExtension` - The file format for the thumbnail. Example: "png" queryParams `GetFileThumbnailUrlQueryParams` - Query parameters of getFileThumbnailById method headers `GetFileThumbnailUrlHeaders` - Headers of getFileThumbnailById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `string`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. ## Get file thumbnail Retrieves a thumbnail, or smaller image representation, of a file. Sizes of `32x32`,`64x64`, `128x128`, and `256x256` can be returned in the `.png` format and sizes of `32x32`, `160x160`, and `320x320` can be returned in the `.jpg` format. Thumbnails can be generated for the image and video file formats listed [found on our community site](https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327). This operation is performed by calling function `GetFileThumbnailById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` await client.Files.GetFileThumbnailByIdAsync(fileId: thumbnailFile.Id, extension: GetFileThumbnailByIdExtension.Png); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension `GetFileThumbnailByIdExtension` - The file format for the thumbnail. Example: "png" queryParams `GetFileThumbnailByIdQueryParams` - Query parameters of getFileThumbnailById method headers `GetFileThumbnailByIdHeaders` - Headers of getFileThumbnailById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `System.IO.Stream?`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. --- ## Untitled *Type: page* IFolderLocksManager List folder locks Create folder lock Delete folder lock List folder locks Retrieves folder lock details for a given… # IFolderLocksManager - [List folder locks](#list-folder-locks) - [Create folder lock](#create-folder-lock) - [Delete folder lock](#delete-folder-lock) ## List folder locks Retrieves folder lock details for a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `GetFolderLocks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folder-locks/). ``` await client.FolderLocks.GetFolderLocksAsync(queryParams: new GetFolderLocksQueryParams(folderId: folder.Id)); ``` ### Arguments queryParams `GetFolderLocksQueryParams` - Query parameters of getFolderLocks method headers `GetFolderLocksHeaders` - Headers of getFolderLocks method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderLocks`. Returns details for all folder locks applied to the folder, including the lock type and user that applied the lock. ## Create folder lock Creates a folder lock on a folder, preventing it from being moved and/or deleted. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `CreateFolderLock`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folder-locks/). ``` await client.FolderLocks.CreateFolderLockAsync(requestBody: new CreateFolderLockRequestBody(folder: new CreateFolderLockRequestBodyFolderField(id: folder.Id, type: "folder")) { LockedOperations = new CreateFolderLockRequestBodyLockedOperationsField(move: true, delete: true) }); ``` ### Arguments requestBody `CreateFolderLockRequestBody` - Request body of createFolderLock method headers `CreateFolderLockHeaders` - Headers of createFolderLock method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderLock`. Returns the instance of the folder lock that was applied to the folder, including the user that applied the lock and the operations set. ## Delete folder lock Deletes a folder lock on a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `DeleteFolderLockById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folder-locks-id/). ``` await client.FolderLocks.DeleteFolderLockByIdAsync(folderLockId: NullableUtils.Unwrap(folderLock.Id)); ``` ### Arguments folderLockId `string` - The ID of the folder lock. Example: "12345" headers `DeleteFolderLockByIdHeaders` - Headers of deleteFolderLockById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the folder lock is successfully deleted. --- ## Untitled *Type: page* IFolderWatermarksManager Get watermark for folder Apply watermark to folder Remove watermark from folder Get watermark for folder Retrieve… # IFolderWatermarksManager - [Get watermark for folder](#get-watermark-for-folder) - [Apply watermark to folder](#apply-watermark-to-folder) - [Remove watermark from folder](#remove-watermark-from-folder) ## Get watermark for folder Retrieve the watermark for a folder. This operation is performed by calling function `GetFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-watermark/). ``` await client.FolderWatermarks.GetFolderWatermarkAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetFolderWatermarkHeaders` - Headers of getFolderWatermark method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this folder. ## Apply watermark to folder Applies or update a watermark on a folder. This operation is performed by calling function `UpdateFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-watermark/). ``` await client.FolderWatermarks.UpdateFolderWatermarkAsync(folderId: folder.Id, requestBody: new UpdateFolderWatermarkRequestBody(watermark: new UpdateFolderWatermarkRequestBodyWatermarkField(imprint: UpdateFolderWatermarkRequestBodyWatermarkImprintField.Default))); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateFolderWatermarkRequestBody` - Request body of updateFolderWatermark method headers `UpdateFolderWatermarkHeaders` - Headers of updateFolderWatermark method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this folder.Returns a new watermark if no watermark existed on this folder yet. ## Remove watermark from folder Removes the watermark from a folder. This operation is performed by calling function `DeleteFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-watermark/). ``` await client.FolderWatermarks.DeleteFolderWatermarkAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteFolderWatermarkHeaders` - Headers of deleteFolderWatermark method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. An empty response will be returned when the watermark was successfully deleted. --- ## Untitled *Type: page* IFoldersManager Get folder information Update folder Delete folder List items in folder Create folder Copy folder Get folder information… # IFoldersManager - [Get folder information](#get-folder-information) - [Update folder](#update-folder) - [Delete folder](#delete-folder) - [List items in folder](#list-items-in-folder) - [Create folder](#create-folder) - [Copy folder](#copy-folder) ## Get folder information Retrieves details for a folder, including the first 100 entries in the folder. Passing `sort`, `direction`, `offset`, and `limit` parameters in query allows you to manage the list of returned [folder items](r://folder--full#param-item-collection). To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items) endpoint. This operation is performed by calling function `GetFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id/). ``` await client.Folders.GetFolderByIdAsync(folderId: "0"); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderByIdQueryParams` - Query parameters of getFolderById method headers `GetFolderByIdHeaders` - Headers of getFolderById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns a folder, including the first 100 entries in the folder. If you used query parameters like `sort`, `direction`, `offset`, or `limit` the *folder items list* will be affected accordingly. To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items)) endpoint. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update folder Updates a folder. This can be also be used to move the folder, create shared links, update collaborations, and more. This operation is performed by calling function `UpdateFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id/). ``` await client.Folders.UpdateFolderByIdAsync(folderId: folderToUpdate.Id, requestBody: new UpdateFolderByIdRequestBody() { Name = updatedName, Description = "Updated description" }); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateFolderByIdRequestBody` - Request body of updateFolderById method queryParams `UpdateFolderByIdQueryParams` - Query parameters of updateFolderById method headers `UpdateFolderByIdHeaders` - Headers of updateFolderById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns a folder object for the updated folder Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. If the user is moving folders with a large number of items in all of their descendants, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. ## Delete folder Deletes a folder, either permanently or by moving it to the trash. This operation is performed by calling function `DeleteFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id/). ``` await client.Folders.DeleteFolderByIdAsync(folderId: newFolder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `DeleteFolderByIdQueryParams` - Query parameters of deleteFolderById method headers `DeleteFolderByIdHeaders` - Headers of deleteFolderById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the folder is successfully deleted or moved to the trash. ## List items in folder Retrieves a page of items in a folder. These items can be files, folders, and web links. To request more information about the folder itself, like its size, use the [Get a folder](#get-folders-id) endpoint instead. This operation is performed by calling function `GetFolderItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-items/). ``` await client.Folders.GetFolderItemsAsync(folderId: folderOrigin.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderItemsQueryParams` - Query parameters of getFolderItems method headers `GetFolderItemsHeaders` - Headers of getFolderItems method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Items`. Returns a collection of files, folders, and web links contained in a folder. ## Create folder Creates a new empty folder within the specified parent folder. This operation is performed by calling function `CreateFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders/). ``` await client.Folders.CreateFolderAsync(requestBody: new CreateFolderRequestBody(name: newFolderName, parent: new CreateFolderRequestBodyParentField(id: "0"))); ``` ### Arguments requestBody `CreateFolderRequestBody` - Request body of createFolder method queryParams `CreateFolderQueryParams` - Query parameters of createFolder method headers `CreateFolderHeaders` - Headers of createFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns a folder object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Copy folder Creates a copy of a folder within a destination folder. The original folder will not be changed. This operation is performed by calling function `CopyFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-copy/). ``` await client.Folders.CopyFolderAsync(folderId: folderOrigin.Id, requestBody: new CopyFolderRequestBody(parent: new CopyFolderRequestBodyParentField(id: "0")) { Name = copiedFolderName }); ``` ### Arguments folderId `string` - The unique identifier of the folder to copy. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder with the ID `0` can not be copied. Example: "0" requestBody `CopyFolderRequestBody` - Request body of copyFolder method queryParams `CopyFolderQueryParams` - Query parameters of copyFolder method headers `CopyFolderHeaders` - Headers of copyFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns a new folder object representing the copied folder. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* IFolderMetadataManager List metadata instances on folder Get metadata instance on folder Create metadata instance on folder Update metadata… # IFolderMetadataManager - [List metadata instances on folder](#list-metadata-instances-on-folder) - [Get metadata instance on folder](#get-metadata-instance-on-folder) - [Create metadata instance on folder](#create-metadata-instance-on-folder) - [Update metadata instance on folder](#update-metadata-instance-on-folder) - [Remove metadata instance from folder](#remove-metadata-instance-from-folder) ## List metadata instances on folder Retrieves all metadata for a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `GetFolderMetadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata/). ``` await client.FolderMetadata.GetFolderMetadataAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetFolderMetadataHeaders` - Headers of getFolderMetadata method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a folder. This API does not support pagination and will therefore always return all of the metadata associated to the folder. ## Get metadata instance on folder Retrieves the instance of a metadata template that has been applied to a folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `GetFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-id-id/). ``` await client.FolderMetadata.GetFolderMetadataByIdAsync(folderId: folder.Id, scope: GetFolderMetadataByIdScope.Global, templateKey: "properties"); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `GetFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" headers `GetFolderMetadataByIdHeaders` - Headers of getFolderMetadataById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on folder Applies an instance of a metadata template to a folder. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. To display the metadata template in the Box web app the enterprise needs to be configured to enable **Cascading Folder Level Metadata** for the user in the admin console. This operation is performed by calling function `CreateFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-id-id/). ``` await client.FolderMetadata.CreateFolderMetadataByIdAsync(folderId: folder.Id, scope: CreateFolderMetadataByIdScope.Enterprise, templateKey: templateKey, requestBody: new Dictionary<string, object>() { { "name", "John" }, { "age", 23 }, { "birthDate", "2001-01-03T02:20:50.520Z" }, { "countryCode", "US" }, { "sports", Array.AsReadOnly(new [] {"basketball","tennis"}) } }); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `CreateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `Dictionary<string, object>` - Request body of createFolderMetadataById method headers `CreateFolderMetadataByIdHeaders` - Headers of createFolderMetadataById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the folder, including the data that was applied to the template. ## Update metadata instance on folder Updates a piece of metadata on a folder. The metadata instance can only be updated if the template has already been applied to the folder before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `UpdateFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-id-id/). ``` await client.FolderMetadata.UpdateFolderMetadataByIdAsync(folderId: folder.Id, scope: UpdateFolderMetadataByIdScope.Enterprise, templateKey: templateKey, requestBody: Array.AsReadOnly(new [] {new UpdateFolderMetadataByIdRequestBody() { Op = UpdateFolderMetadataByIdRequestBodyOpField.Replace, Path = "/name", Value = "Jack" },new UpdateFolderMetadataByIdRequestBody() { Op = UpdateFolderMetadataByIdRequestBodyOpField.Replace, Path = "/age", Value = 24 },new UpdateFolderMetadataByIdRequestBody() { Op = UpdateFolderMetadataByIdRequestBodyOpField.Replace, Path = "/birthDate", Value = "2000-01-03T02:20:50.520Z" },new UpdateFolderMetadataByIdRequestBody() { Op = UpdateFolderMetadataByIdRequestBodyOpField.Replace, Path = "/countryCode", Value = "CA" },new UpdateFolderMetadataByIdRequestBody() { Op = UpdateFolderMetadataByIdRequestBodyOpField.Replace, Path = "/sports", Value = Array.AsReadOnly(new [] {"football"}) }})); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `UpdateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `IReadOnlyList<UpdateFolderMetadataByIdRequestBody>` - Request body of updateFolderMetadataById method headers `UpdateFolderMetadataByIdHeaders` - Headers of updateFolderMetadataById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from folder Deletes a piece of folder metadata. This operation is performed by calling function `DeleteFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-id-id/). ``` await client.FolderMetadata.DeleteFolderMetadataByIdAsync(folderId: folder.Id, scope: DeleteFolderMetadataByIdScope.Enterprise, templateKey: templateKey); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `DeleteFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" headers `DeleteFolderMetadataByIdHeaders` - Headers of deleteFolderMetadataById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* IGroupsManager List groups for enterprise Create group Get group Update group Remove group List groups for enterprise Retrieves all of the… # IGroupsManager - [List groups for enterprise](#list-groups-for-enterprise) - [Create group](#create-group) - [Get group](#get-group) - [Update group](#update-group) - [Remove group](#remove-group) ## List groups for enterprise Retrieves all of the groups for a given enterprise. The user must have admin permissions to inspect enterprise's groups. This operation is performed by calling function `GetGroups`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups/). ``` await client.Groups.GetGroupsAsync(); ``` ### Arguments queryParams `GetGroupsQueryParams` - Query parameters of getGroups method headers `GetGroupsHeaders` - Headers of getGroups method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Groups`. Returns a collection of group objects. If there are no groups, an empty collection will be returned. ## Create group Creates a new group of users in an enterprise. Only users with admin permissions can create new groups. This operation is performed by calling function `CreateGroup`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups/). ``` await client.Groups.CreateGroupAsync(requestBody: new CreateGroupRequestBody(name: groupName) { Description = groupDescription }); ``` ### Arguments requestBody `CreateGroupRequestBody` - Request body of createGroup method queryParams `CreateGroupQueryParams` - Query parameters of createGroup method headers `CreateGroupHeaders` - Headers of createGroup method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `GroupFull`. Returns the new group object. ## Get group Retrieves information about a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `GetGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id/). ``` await client.Groups.GetGroupByIdAsync(groupId: group.Id, queryParams: new GetGroupByIdQueryParams() { Fields = Array.AsReadOnly(new [] {"id","name","description","group_type"}) }); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" queryParams `GetGroupByIdQueryParams` - Query parameters of getGroupById method headers `GetGroupByIdHeaders` - Headers of getGroupById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `GroupFull`. Returns the group object. ## Update group Updates a specific group. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `UpdateGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-groups-id/). ``` await client.Groups.UpdateGroupByIdAsync(groupId: group.Id, requestBody: new UpdateGroupByIdRequestBody() { Name = updatedGroupName }); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" requestBody `UpdateGroupByIdRequestBody` - Request body of updateGroupById method queryParams `UpdateGroupByIdQueryParams` - Query parameters of updateGroupById method headers `UpdateGroupByIdHeaders` - Headers of updateGroupById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `GroupFull`. Returns the updated group object. ## Remove group Permanently deletes a group. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `DeleteGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-groups-id/). ``` await client.Groups.DeleteGroupByIdAsync(groupId: group.Id); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" headers `DeleteGroupByIdHeaders` - Headers of deleteGroupById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the group was successfully deleted. --- ## Untitled *Type: page* IHubCollaborationsManager Get hub collaborations Create hub collaboration Get hub collaboration by collaboration ID Update hub collaboration… # IHubCollaborationsManager - [Get hub collaborations](#get-hub-collaborations) - [Create hub collaboration](#create-hub-collaboration) - [Get hub collaboration by collaboration ID](#get-hub-collaboration-by-collaboration-id) - [Update hub collaboration](#update-hub-collaboration) - [Remove hub collaboration](#remove-hub-collaboration) ## Get hub collaborations Retrieves all collaborations for a hub. This operation is performed by calling function `GetHubCollaborationsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations/). ``` await client.HubCollaborations.GetHubCollaborationsV2025R0Async(queryParams: new GetHubCollaborationsV2025R0QueryParams(hubId: hub.Id)); ``` ### Arguments queryParams `GetHubCollaborationsV2025R0QueryParams` - Query parameters of getHubCollaborationsV2025R0 method headers `GetHubCollaborationsV2025R0Headers` - Headers of getHubCollaborationsV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubCollaborationsV2025R0`. Retrieves the collaborations associated with the specified hub. ## Create hub collaboration Adds a collaboration for a single user or a single group to a hub. Collaborations can be created using email address, user IDs, or group IDs. This operation is performed by calling function `CreateHubCollaborationV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hub-collaborations/). ``` await client.HubCollaborations.CreateHubCollaborationV2025R0Async(requestBody: new HubCollaborationCreateRequestV2025R0(hub: new HubCollaborationCreateRequestV2025R0HubField(id: hub.Id), accessibleBy: new HubCollaborationCreateRequestV2025R0AccessibleByField(type: "user") { Id = user.Id }, role: "viewer")); ``` ### Arguments requestBody `HubCollaborationCreateRequestV2025R0` - Request body of createHubCollaborationV2025R0 method headers `CreateHubCollaborationV2025R0Headers` - Headers of createHubCollaborationV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a new hub collaboration object. ## Get hub collaboration by collaboration ID Retrieves details for a hub collaboration by collaboration ID. This operation is performed by calling function `GetHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations-id/). ``` await client.HubCollaborations.GetHubCollaborationByIdV2025R0Async(hubCollaborationId: createdCollaboration.Id); ``` ### Arguments hubCollaborationId `string` - The ID of the hub collaboration. Example: "1234" headers `GetHubCollaborationByIdV2025R0Headers` - Headers of getHubCollaborationByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a hub collaboration object. ## Update hub collaboration Updates a hub collaboration. Can be used to change the hub role. This operation is performed by calling function `UpdateHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hub-collaborations-id/). ``` await client.HubCollaborations.UpdateHubCollaborationByIdV2025R0Async(hubCollaborationId: createdCollaboration.Id, requestBody: new HubCollaborationUpdateRequestV2025R0() { Role = "editor" }); ``` ### Arguments hubCollaborationId `string` - The ID of the hub collaboration. Example: "1234" requestBody `HubCollaborationUpdateRequestV2025R0` - Request body of updateHubCollaborationByIdV2025R0 method headers `UpdateHubCollaborationByIdV2025R0Headers` - Headers of updateHubCollaborationByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns an updated hub collaboration object. ## Remove hub collaboration Deletes a single hub collaboration. This operation is performed by calling function `DeleteHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hub-collaborations-id/). ``` await client.HubCollaborations.DeleteHubCollaborationByIdV2025R0Async(hubCollaborationId: createdCollaboration.Id); ``` ### Arguments hubCollaborationId `string` - The ID of the hub collaboration. Example: "1234" headers `DeleteHubCollaborationByIdV2025R0Headers` - Headers of deleteHubCollaborationByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the hub collaboration was successfully deleted. --- ## Untitled *Type: page* IHubItemsManager Get hub items Manage hub items Get hub items Retrieves all items associated with a Hub. This operation is performed by… # IHubItemsManager - [Get hub items](#get-hub-items) - [Manage hub items](#manage-hub-items) ## Get hub items Retrieves all items associated with a Hub. This operation is performed by calling function `GetHubItemsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-items/). ``` await client.HubItems.GetHubItemsV2025R0Async(queryParams: new GetHubItemsV2025R0QueryParams(hubId: createdHub.Id)); ``` ### Arguments queryParams `GetHubItemsV2025R0QueryParams` - Query parameters of getHubItemsV2025R0 method headers `GetHubItemsV2025R0Headers` - Headers of getHubItemsV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubItemsV2025R0`. Retrieves the items associated with the specified Hub. ## Manage hub items Adds and/or removes Hub items from a Hub. This operation is performed by calling function `ManageHubItemsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-manage-items/). ``` await client.HubItems.ManageHubItemsV2025R0Async(hubId: createdHub.Id, requestBody: new HubItemsManageRequestV2025R0() { Operations = Array.AsReadOnly(new [] {new HubItemOperationV2025R0(action: HubItemOperationV2025R0ActionField.Add, item: new FolderReferenceV2025R0(id: folder.Id))}) }); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubItemsManageRequestV2025R0` - Request body of manageHubItemsV2025R0 method headers `ManageHubItemsV2025R0Headers` - Headers of manageHubItemsV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubItemsManageResponseV2025R0`. --- ## Untitled *Type: page* IHubsManager List all hubs Create hub List all hubs for requesting enterprise Get hub information by ID Update hub information by ID Delete… # IHubsManager - [List all hubs](#list-all-hubs) - [Create hub](#create-hub) - [List all hubs for requesting enterprise](#list-all-hubs-for-requesting-enterprise) - [Get hub information by ID](#get-hub-information-by-id) - [Update hub information by ID](#update-hub-information-by-id) - [Delete hub](#delete-hub) - [Copy hub](#copy-hub) ## List all hubs Retrieves all hubs for requesting user. This operation is performed by calling function `GetHubsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs/). ``` await client.Hubs.GetHubsV2025R0Async(queryParams: new GetHubsV2025R0QueryParams() { Scope = "all", Sort = "name", Direction = GetHubsV2025R0QueryParamsDirectionField.Asc }); ``` ### Arguments queryParams `GetHubsV2025R0QueryParams` - Query parameters of getHubsV2025R0 method headers `GetHubsV2025R0Headers` - Headers of getHubsV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Create hub Creates a new Hub. This operation is performed by calling function `CreateHubV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs/). ``` await client.Hubs.CreateHubV2025R0Async(requestBody: new HubCreateRequestV2025R0(title: hubTitle) { Description = hubDescription }); ``` ### Arguments requestBody `HubCreateRequestV2025R0` - Request body of createHubV2025R0 method headers `CreateHubV2025R0Headers` - Headers of createHubV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. ## List all hubs for requesting enterprise Retrieves all hubs for a given enterprise. Admins or Hub Co-admins of an enterprise with GCM scope can make this call. This operation is performed by calling function `GetEnterpriseHubsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-enterprise-hubs/). ``` await client.Hubs.GetEnterpriseHubsV2025R0Async(queryParams: new GetEnterpriseHubsV2025R0QueryParams() { Sort = "name", Direction = GetEnterpriseHubsV2025R0QueryParamsDirectionField.Asc }); ``` ### Arguments queryParams `GetEnterpriseHubsV2025R0QueryParams` - Query parameters of getEnterpriseHubsV2025R0 method headers `GetEnterpriseHubsV2025R0Headers` - Headers of getEnterpriseHubsV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Get hub information by ID Retrieves details for a hub by its ID. This operation is performed by calling function `GetHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs-id/). ``` await client.Hubs.GetHubByIdV2025R0Async(hubId: hubId); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" headers `GetHubByIdV2025R0Headers` - Headers of getHubByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubV2025R0`. Returns a hub object. ## Update hub information by ID Updates a Hub. Can be used to change title, description, or Hub settings. This operation is performed by calling function `UpdateHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hubs-id/). ``` await client.Hubs.UpdateHubByIdV2025R0Async(hubId: hubId, requestBody: new HubUpdateRequestV2025R0() { Title = newHubTitle, Description = newHubDescription }); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubUpdateRequestV2025R0` - Request body of updateHubByIdV2025R0 method headers `UpdateHubByIdV2025R0Headers` - Headers of updateHubByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubV2025R0`. Returns a Hub object. ## Delete hub Deletes a single hub. This operation is performed by calling function `DeleteHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hubs-id/). ``` await client.Hubs.DeleteHubByIdV2025R0Async(hubId: hubId); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" headers `DeleteHubByIdV2025R0Headers` - Headers of deleteHubByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the hub was successfully deleted. ## Copy hub Creates a copy of a Hub. The original Hub will not be modified. This operation is performed by calling function `CopyHubV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-copy/). ``` await client.Hubs.CopyHubV2025R0Async(hubId: createdHub.Id, requestBody: new HubCopyRequestV2025R0() { Title = copiedHubTitle, Description = copiedHubDescription }); ``` ### Arguments hubId `string` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubCopyRequestV2025R0` - Request body of copyHubV2025R0 method headers `CopyHubV2025R0Headers` - Headers of copyHubV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. --- ## Untitled *Type: page* IInvitesManager Create user invite Get user invite status Create user invite Invites an existing external user to join an enterprise. The… # IInvitesManager - [Create user invite](#create-user-invite) - [Get user invite status](#get-user-invite-status) ## Create user invite Invites an existing external user to join an enterprise. The existing user can not be part of another enterprise and must already have a Box account. Once invited, the user will receive an email and are prompted to accept the invitation within the Box web application. This method requires the "Manage An Enterprise" scope enabled for the application, which can be enabled within the developer console. This operation is performed by calling function `CreateInvite`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-invites/). ``` await client.Invites.CreateInviteAsync(requestBody: new CreateInviteRequestBody(enterprise: new CreateInviteRequestBodyEnterpriseField(id: NullableUtils.Unwrap(NullableUtils.Unwrap(currentUser.Enterprise).Id)), actionableBy: new CreateInviteRequestBodyActionableByField() { Login = email })); ``` ### Arguments requestBody `CreateInviteRequestBody` - Request body of createInvite method queryParams `CreateInviteQueryParams` - Query parameters of createInvite method headers `CreateInviteHeaders` - Headers of createInvite method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Invite`. Returns a new invite object. ## Get user invite status Returns the status of a user invite. This operation is performed by calling function `GetInviteById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-invites-id/). ``` await client.Invites.GetInviteByIdAsync(inviteId: invitation.Id); ``` ### Arguments inviteId `string` - The ID of an invite. Example: "213723" queryParams `GetInviteByIdQueryParams` - Query parameters of getInviteById method headers `GetInviteByIdHeaders` - Headers of getInviteById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Invite`. Returns an invite object. --- ## Untitled *Type: page* IIntegrationMappingsManager List Slack integration mappings Create Slack integration mapping Update Slack integration mapping Delete Slack… # IIntegrationMappingsManager - [List Slack integration mappings](#list-slack-integration-mappings) - [Create Slack integration mapping](#create-slack-integration-mapping) - [Update Slack integration mapping](#update-slack-integration-mapping) - [Delete Slack integration mapping](#delete-slack-integration-mapping) - [List Teams integration mappings](#list-teams-integration-mappings) - [Create Teams integration mapping](#create-teams-integration-mapping) - [Update Teams integration mapping](#update-teams-integration-mapping) - [Delete Teams integration mapping](#delete-teams-integration-mapping) ## List Slack integration mappings Lists [Slack integration mappings](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `GetSlackIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-slack/). ``` await userClient.IntegrationMappings.GetSlackIntegrationMappingAsync(); ``` ### Arguments queryParams `GetSlackIntegrationMappingQueryParams` - Query parameters of getSlackIntegrationMapping method headers `GetSlackIntegrationMappingHeaders` - Headers of getSlackIntegrationMapping method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `IntegrationMappings`. Returns a collection of integration mappings. ## Create Slack integration mapping Creates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) by mapping a Slack channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `CreateSlackIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-slack/). ``` await userClient.IntegrationMappings.CreateSlackIntegrationMappingAsync(requestBody: new IntegrationMappingSlackCreateRequest(partnerItem: new IntegrationMappingPartnerItemSlack(id: slackPartnerItemId) { SlackOrgId = slackOrgId }, boxItem: new IntegrationMappingBoxItemSlack(id: folder.Id))); ``` ### Arguments requestBody `IntegrationMappingSlackCreateRequest` - Request body of createSlackIntegrationMapping method headers `CreateSlackIntegrationMappingHeaders` - Headers of createSlackIntegrationMapping method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `IntegrationMapping`. Returns the created integration mapping. ## Update Slack integration mapping Updates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `UpdateSlackIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-slack-id/). ``` await userClient.IntegrationMappings.UpdateSlackIntegrationMappingByIdAsync(integrationMappingId: slackIntegrationMapping.Id, requestBody: new UpdateSlackIntegrationMappingByIdRequestBody() { BoxItem = new IntegrationMappingBoxItemSlack(id: folder.Id) }); ``` ### Arguments integrationMappingId `string` - An ID of an integration mapping. Example: "11235432" requestBody `UpdateSlackIntegrationMappingByIdRequestBody` - Request body of updateSlackIntegrationMappingById method headers `UpdateSlackIntegrationMappingByIdHeaders` - Headers of updateSlackIntegrationMappingById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `IntegrationMapping`. Returns the updated integration mapping object. ## Delete Slack integration mapping Deletes a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `DeleteSlackIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-slack-id/). ``` await userClient.IntegrationMappings.DeleteSlackIntegrationMappingByIdAsync(integrationMappingId: slackIntegrationMapping.Id); ``` ### Arguments integrationMappingId `string` - An ID of an integration mapping. Example: "11235432" headers `DeleteSlackIntegrationMappingByIdHeaders` - Headers of deleteSlackIntegrationMappingById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Empty body in response. ## List Teams integration mappings Lists [Teams integration mappings](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `GetTeamsIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-teams/). ``` await userClient.IntegrationMappings.GetTeamsIntegrationMappingAsync(); ``` ### Arguments queryParams `GetTeamsIntegrationMappingQueryParams` - Query parameters of getTeamsIntegrationMapping method headers `GetTeamsIntegrationMappingHeaders` - Headers of getTeamsIntegrationMapping method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `IntegrationMappingsTeams`. Returns a collection of integration mappings. ## Create Teams integration mapping Creates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) by mapping a Teams channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `CreateTeamsIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-teams/). ``` await userClient.IntegrationMappings.CreateTeamsIntegrationMappingAsync(requestBody: new IntegrationMappingTeamsCreateRequest(partnerItem: new IntegrationMappingPartnerItemTeamsCreateRequest(type: IntegrationMappingPartnerItemTeamsCreateRequestTypeField.Channel, id: partnerItemId, tenantId: tenantId, teamId: teamId), boxItem: new FolderReference(id: folder.Id))); ``` ### Arguments requestBody `IntegrationMappingTeamsCreateRequest` - Request body of createTeamsIntegrationMapping method headers `CreateTeamsIntegrationMappingHeaders` - Headers of createTeamsIntegrationMapping method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the created integration mapping. ## Update Teams integration mapping Updates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `UpdateTeamsIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-teams-id/). ``` await userClient.IntegrationMappings.UpdateTeamsIntegrationMappingByIdAsync(integrationMappingId: integrationMappingId, requestBody: new UpdateTeamsIntegrationMappingByIdRequestBody() { BoxItem = new FolderReference(id: "1234567") }); ``` ### Arguments integrationMappingId `string` - An ID of an integration mapping. Example: "11235432" requestBody `UpdateTeamsIntegrationMappingByIdRequestBody` - Request body of updateTeamsIntegrationMappingById method headers `UpdateTeamsIntegrationMappingByIdHeaders` - Headers of updateTeamsIntegrationMappingById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the updated integration mapping object. ## Delete Teams integration mapping Deletes a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `DeleteTeamsIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-teams-id/). ``` await userClient.IntegrationMappings.DeleteTeamsIntegrationMappingByIdAsync(integrationMappingId: integrationMappingId); ``` ### Arguments integrationMappingId `string` - An ID of an integration mapping. Example: "11235432" headers `DeleteTeamsIntegrationMappingByIdHeaders` - Headers of deleteTeamsIntegrationMappingById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Empty body in response. --- ## Untitled *Type: page* ILegalHoldPoliciesManager List all legal hold policies Create legal hold policy Get legal hold policy Update legal hold policy Remove legal… # ILegalHoldPoliciesManager - [List all legal hold policies](#list-all-legal-hold-policies) - [Create legal hold policy](#create-legal-hold-policy) - [Get legal hold policy](#get-legal-hold-policy) - [Update legal hold policy](#update-legal-hold-policy) - [Remove legal hold policy](#remove-legal-hold-policy) ## List all legal hold policies Retrieves a list of legal hold policies that belong to an enterprise. This operation is performed by calling function `GetLegalHoldPolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies/). ``` await client.LegalHoldPolicies.GetLegalHoldPoliciesAsync(); ``` ### Arguments queryParams `GetLegalHoldPoliciesQueryParams` - Query parameters of getLegalHoldPolicies method headers `GetLegalHoldPoliciesHeaders` - Headers of getLegalHoldPolicies method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `LegalHoldPolicies`. Returns a list of legal hold policies. ## Create legal hold policy Create a new legal hold policy. This operation is performed by calling function `CreateLegalHoldPolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policies/). ``` await client.LegalHoldPolicies.CreateLegalHoldPolicyAsync(requestBody: new CreateLegalHoldPolicyRequestBody(policyName: legalHoldPolicyName) { Description = legalHoldDescription, IsOngoing = false, FilterStartedAt = filterStartedAt, FilterEndedAt = filterEndedAt }); ``` ### Arguments requestBody `CreateLegalHoldPolicyRequestBody` - Request body of createLegalHoldPolicy method headers `CreateLegalHoldPolicyHeaders` - Headers of createLegalHoldPolicy method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Get legal hold policy Retrieve a legal hold policy. This operation is performed by calling function `GetLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies-id/). ``` await client.LegalHoldPolicies.GetLegalHoldPolicyByIdAsync(legalHoldPolicyId: legalHoldPolicyId); ``` ### Arguments legalHoldPolicyId `string` - The ID of the legal hold policy. Example: "324432" headers `GetLegalHoldPolicyByIdHeaders` - Headers of getLegalHoldPolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a legal hold policy object. ## Update legal hold policy Update legal hold policy. This operation is performed by calling function `UpdateLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-legal-hold-policies-id/). ``` await client.LegalHoldPolicies.UpdateLegalHoldPolicyByIdAsync(legalHoldPolicyId: legalHoldPolicyId, requestBody: new UpdateLegalHoldPolicyByIdRequestBody() { PolicyName = updatedLegalHoldPolicyName }); ``` ### Arguments legalHoldPolicyId `string` - The ID of the legal hold policy. Example: "324432" requestBody `UpdateLegalHoldPolicyByIdRequestBody` - Request body of updateLegalHoldPolicyById method headers `UpdateLegalHoldPolicyByIdHeaders` - Headers of updateLegalHoldPolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Remove legal hold policy Delete an existing legal hold policy. This is an asynchronous process. The policy will not be fully deleted yet when the response returns. This operation is performed by calling function `DeleteLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policies-id/). ``` await client.LegalHoldPolicies.DeleteLegalHoldPolicyByIdAsync(legalHoldPolicyId: legalHoldPolicy.Id); ``` ### Arguments legalHoldPolicyId `string` - The ID of the legal hold policy. Example: "324432" headers `DeleteLegalHoldPolicyByIdHeaders` - Headers of deleteLegalHoldPolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the policy was successfully deleted. --- ## Untitled *Type: page* IListCollaborationsManager List file collaborations List folder collaborations List pending collaborations List group collaborations List… # IListCollaborationsManager - [List file collaborations](#list-file-collaborations) - [List folder collaborations](#list-folder-collaborations) - [List pending collaborations](#list-pending-collaborations) - [List group collaborations](#list-group-collaborations) ## List file collaborations Retrieves a list of pending and active collaborations for a file. This returns all the users that have access to the file or have been invited to the file. This operation is performed by calling function `GetFileCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-collaborations/). ``` await client.ListCollaborations.GetFileCollaborationsAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileCollaborationsQueryParams` - Query parameters of getFileCollaborations method headers `GetFileCollaborationsHeaders` - Headers of getFileCollaborations method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this file an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List folder collaborations Retrieves a list of pending and active collaborations for a folder. This returns all the users that have access to the folder or have been invited to the folder. This operation is performed by calling function `GetFolderCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-collaborations/). ``` await client.ListCollaborations.GetFolderCollaborationsAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. Example: "12345" queryParams `GetFolderCollaborationsQueryParams` - Query parameters of getFolderCollaborations method headers `GetFolderCollaborationsHeaders` - Headers of getFolderCollaborations method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this folder an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List pending collaborations Retrieves all pending collaboration invites for this user. This operation is performed by calling function `GetCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations/). ``` await client.ListCollaborations.GetCollaborationsAsync(queryParams: new GetCollaborationsQueryParams(status: GetCollaborationsQueryParamsStatusField.Pending)); ``` ### Arguments queryParams `GetCollaborationsQueryParams` - Query parameters of getCollaborations method headers `GetCollaborationsHeaders` - Headers of getCollaborations method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of pending collaboration objects. If the user has no pending collaborations, the collection will be empty. ## List group collaborations Retrieves all the collaborations for a group. The user must have admin permissions to inspect enterprise's groups. Each collaboration object has details on which files or folders the group has access to and with what role. This operation is performed by calling function `GetGroupCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-collaborations/). ``` await client.ListCollaborations.GetGroupCollaborationsAsync(groupId: group.Id); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" queryParams `GetGroupCollaborationsQueryParams` - Query parameters of getGroupCollaborations method headers `GetGroupCollaborationsHeaders` - Headers of getGroupCollaborations method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of collaboration objects. If there are no collaborations, an empty collection will be returned. --- ## Untitled *Type: page* ILegalHoldPolicyAssignmentsManager List legal hold policy assignments Assign legal hold policy Get legal hold policy assignment Unassign… # ILegalHoldPolicyAssignmentsManager - [List legal hold policy assignments](#list-legal-hold-policy-assignments) - [Assign legal hold policy](#assign-legal-hold-policy) - [Get legal hold policy assignment](#get-legal-hold-policy-assignment) - [Unassign legal hold policy](#unassign-legal-hold-policy) - [List files with current file versions for legal hold policy assignment](#list-files-with-current-file-versions-for-legal-hold-policy-assignment) ## List legal hold policy assignments Retrieves a list of items a legal hold policy has been assigned to. This operation is performed by calling function `GetLegalHoldPolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments/). ``` await client.LegalHoldPolicyAssignments.GetLegalHoldPolicyAssignmentsAsync(queryParams: new GetLegalHoldPolicyAssignmentsQueryParams(policyId: legalHoldPolicyId)); ``` ### Arguments queryParams `GetLegalHoldPolicyAssignmentsQueryParams` - Query parameters of getLegalHoldPolicyAssignments method headers `GetLegalHoldPolicyAssignmentsHeaders` - Headers of getLegalHoldPolicyAssignments method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `LegalHoldPolicyAssignments`. Returns a list of legal hold policy assignments. ## Assign legal hold policy Assign a legal hold to a file, file version, folder, or user. This operation is performed by calling function `CreateLegalHoldPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policy-assignments/). ``` await client.LegalHoldPolicyAssignments.CreateLegalHoldPolicyAssignmentAsync(requestBody: new CreateLegalHoldPolicyAssignmentRequestBody(policyId: legalHoldPolicyId, assignTo: new CreateLegalHoldPolicyAssignmentRequestBodyAssignToField(type: CreateLegalHoldPolicyAssignmentRequestBodyAssignToTypeField.File, id: fileId))); ``` ### Arguments requestBody `CreateLegalHoldPolicyAssignmentRequestBody` - Request body of createLegalHoldPolicyAssignment method headers `CreateLegalHoldPolicyAssignmentHeaders` - Headers of createLegalHoldPolicyAssignment method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a new legal hold policy assignment. ## Get legal hold policy assignment Retrieve a legal hold policy assignment. This operation is performed by calling function `GetLegalHoldPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id/). ``` await client.LegalHoldPolicyAssignments.GetLegalHoldPolicyAssignmentByIdAsync(legalHoldPolicyAssignmentId: legalHoldPolicyAssignmentId); ``` ### Arguments legalHoldPolicyAssignmentId `string` - The ID of the legal hold policy assignment. Example: "753465" headers `GetLegalHoldPolicyAssignmentByIdHeaders` - Headers of getLegalHoldPolicyAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a legal hold policy object. ## Unassign legal hold policy Remove a legal hold from an item. This is an asynchronous process. The policy will not be fully removed yet when the response returns. This operation is performed by calling function `DeleteLegalHoldPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policy-assignments-id/). ``` await client.LegalHoldPolicyAssignments.DeleteLegalHoldPolicyAssignmentByIdAsync(legalHoldPolicyAssignmentId: legalHoldPolicyAssignmentId); ``` ### Arguments legalHoldPolicyAssignmentId `string` - The ID of the legal hold policy assignment. Example: "753465" headers `DeleteLegalHoldPolicyAssignmentByIdHeaders` - Headers of deleteLegalHoldPolicyAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the assignment was successfully deleted. ## List files with current file versions for legal hold policy assignment Get a list of files with current file versions for a legal hold assignment. In some cases you may want to get previous file versions instead. In these cases, use the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API instead to return any previous versions of a file for this legal hold policy assignment. Due to ongoing re-architecture efforts this API might not return all file versions held for this policy ID. Instead, this API will only return the latest file version held in the newly developed architecture. The `GET /file_version_legal_holds` API can be used to fetch current and past versions of files held within the legacy architecture. This endpoint does not support returning any content that is on hold due to a Custodian collaborating on a Hub. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. This operation is performed by calling function `GetLegalHoldPolicyAssignmentFileOnHold`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id-files-on-hold/). ``` await client.LegalHoldPolicyAssignments.GetLegalHoldPolicyAssignmentFileOnHoldAsync(legalHoldPolicyAssignmentId: legalHoldPolicyAssignmentId); ``` ### Arguments legalHoldPolicyAssignmentId `string` - The ID of the legal hold policy assignment. Example: "753465" queryParams `GetLegalHoldPolicyAssignmentFileOnHoldQueryParams` - Query parameters of getLegalHoldPolicyAssignmentFileOnHold method headers `GetLegalHoldPolicyAssignmentFileOnHoldHeaders` - Headers of getLegalHoldPolicyAssignmentFileOnHold method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FilesOnHold`. Returns the list of current file versions held under legal hold for a specific legal hold policy assignment. --- ## Untitled *Type: page* IMembershipsManager List user's groups List members of group Add user to group Get group membership Update group membership Remove user from… # IMembershipsManager - [List user's groups](#list-users-groups) - [List members of group](#list-members-of-group) - [Add user to group](#add-user-to-group) - [Get group membership](#get-group-membership) - [Update group membership](#update-group-membership) - [Remove user from group](#remove-user-from-group) ## List user's groups Retrieves all the groups for a user. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `GetUserMemberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-memberships/). ``` await client.Memberships.GetUserMembershipsAsync(userId: user.Id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" queryParams `GetUserMembershipsQueryParams` - Query parameters of getUserMemberships method headers `GetUserMembershipsHeaders` - Headers of getUserMemberships method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## List members of group Retrieves all the members for a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `GetGroupMemberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-memberships/). ``` await client.Memberships.GetGroupMembershipsAsync(groupId: group.Id); ``` ### Arguments groupId `string` - The ID of the group. Example: "57645" queryParams `GetGroupMembershipsQueryParams` - Query parameters of getGroupMemberships method headers `GetGroupMembershipsHeaders` - Headers of getGroupMemberships method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## Add user to group Creates a group membership. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `CreateGroupMembership`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-group-memberships/). ``` await client.Memberships.CreateGroupMembershipAsync(requestBody: new CreateGroupMembershipRequestBody(user: new CreateGroupMembershipRequestBodyUserField(id: user.Id), group: new CreateGroupMembershipRequestBodyGroupField(id: group.Id))); ``` ### Arguments requestBody `CreateGroupMembershipRequestBody` - Request body of createGroupMembership method queryParams `CreateGroupMembershipQueryParams` - Query parameters of createGroupMembership method headers `CreateGroupMembershipHeaders` - Headers of createGroupMembership method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Get group membership Retrieves a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `GetGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-group-memberships-id/). ``` await client.Memberships.GetGroupMembershipByIdAsync(groupMembershipId: NullableUtils.Unwrap(groupMembership.Id)); ``` ### Arguments groupMembershipId `string` - The ID of the group membership. Example: "434534" queryParams `GetGroupMembershipByIdQueryParams` - Query parameters of getGroupMembershipById method headers `GetGroupMembershipByIdHeaders` - Headers of getGroupMembershipById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `GroupMembership`. Returns the group membership object. ## Update group membership Updates a user's group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `UpdateGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-group-memberships-id/). ``` await client.Memberships.UpdateGroupMembershipByIdAsync(groupMembershipId: NullableUtils.Unwrap(groupMembership.Id), requestBody: new UpdateGroupMembershipByIdRequestBody() { Role = UpdateGroupMembershipByIdRequestBodyRoleField.Admin }); ``` ### Arguments groupMembershipId `string` - The ID of the group membership. Example: "434534" requestBody `UpdateGroupMembershipByIdRequestBody` - Request body of updateGroupMembershipById method queryParams `UpdateGroupMembershipByIdQueryParams` - Query parameters of updateGroupMembershipById method headers `UpdateGroupMembershipByIdHeaders` - Headers of updateGroupMembershipById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Remove user from group Deletes a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `DeleteGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-group-memberships-id/). ``` await client.Memberships.DeleteGroupMembershipByIdAsync(groupMembershipId: NullableUtils.Unwrap(groupMembership.Id)); ``` ### Arguments groupMembershipId `string` - The ID of the group membership. Example: "434534" headers `DeleteGroupMembershipByIdHeaders` - Headers of deleteGroupMembershipById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the membership was successfully deleted. --- ## Untitled *Type: page* IMetadataCascadePoliciesManager List metadata cascade policies Create metadata cascade policy Get metadata cascade policy Remove metadata… # IMetadataCascadePoliciesManager - [List metadata cascade policies](#list-metadata-cascade-policies) - [Create metadata cascade policy](#create-metadata-cascade-policy) - [Get metadata cascade policy](#get-metadata-cascade-policy) - [Remove metadata cascade policy](#remove-metadata-cascade-policy) - [Force-apply metadata cascade policy to folder](#force-apply-metadata-cascade-policy-to-folder) ## List metadata cascade policies Retrieves a list of all the metadata cascade policies that are applied to a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `GetMetadataCascadePolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies/). ``` await client.MetadataCascadePolicies.GetMetadataCascadePoliciesAsync(queryParams: new GetMetadataCascadePoliciesQueryParams(folderId: folder.Id)); ``` ### Arguments queryParams `GetMetadataCascadePoliciesQueryParams` - Query parameters of getMetadataCascadePolicies method headers `GetMetadataCascadePoliciesHeaders` - Headers of getMetadataCascadePolicies method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataCascadePolicies`. Returns a list of metadata cascade policies. ## Create metadata cascade policy Creates a new metadata cascade policy that applies a given metadata template to a given folder and automatically cascades it down to any files within that folder. In order for the policy to be applied a metadata instance must first be applied to the folder the policy is to be applied to. This operation is performed by calling function `CreateMetadataCascadePolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies/). ``` await client.MetadataCascadePolicies.CreateMetadataCascadePolicyAsync(requestBody: new CreateMetadataCascadePolicyRequestBody(folderId: folder.Id, scope: CreateMetadataCascadePolicyRequestBodyScopeField.Enterprise, templateKey: templateKey)); ``` ### Arguments requestBody `CreateMetadataCascadePolicyRequestBody` - Request body of createMetadataCascadePolicy method headers `CreateMetadataCascadePolicyHeaders` - Headers of createMetadataCascadePolicy method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a new of metadata cascade policy. ## Get metadata cascade policy Retrieve a specific metadata cascade policy assigned to a folder. This operation is performed by calling function `GetMetadataCascadePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies-id/). ``` await client.MetadataCascadePolicies.GetMetadataCascadePolicyByIdAsync(metadataCascadePolicyId: cascadePolicyId); ``` ### Arguments metadataCascadePolicyId `string` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" headers `GetMetadataCascadePolicyByIdHeaders` - Headers of getMetadataCascadePolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a metadata cascade policy. ## Remove metadata cascade policy Deletes a metadata cascade policy. This operation is performed by calling function `DeleteMetadataCascadePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-cascade-policies-id/). ``` await client.MetadataCascadePolicies.DeleteMetadataCascadePolicyByIdAsync(metadataCascadePolicyId: cascadePolicyId); ``` ### Arguments metadataCascadePolicyId `string` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" headers `DeleteMetadataCascadePolicyByIdHeaders` - Headers of deleteMetadataCascadePolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the policy is successfully deleted. ## Force-apply metadata cascade policy to folder Force the metadata on a folder with a metadata cascade policy to be applied to all of its children. This can be used after creating a new cascade policy to enforce the metadata to be cascaded down to all existing files within that folder. This operation is performed by calling function `ApplyMetadataCascadePolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies-id-apply/). ``` await client.MetadataCascadePolicies.ApplyMetadataCascadePolicyAsync(metadataCascadePolicyId: cascadePolicyId, requestBody: new ApplyMetadataCascadePolicyRequestBody(conflictResolution: ApplyMetadataCascadePolicyRequestBodyConflictResolutionField.Overwrite)); ``` ### Arguments metadataCascadePolicyId `string` - The ID of the cascade policy to force-apply. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" requestBody `ApplyMetadataCascadePolicyRequestBody` - Request body of applyMetadataCascadePolicy method headers `ApplyMetadataCascadePolicyHeaders` - Headers of applyMetadataCascadePolicy method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the API call was successful. The metadata cascade operation will be performed asynchronously. The API call will return directly, before the cascade operation is complete. There is currently no API to check for the status of this operation. --- ## Untitled *Type: page* Documentation High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available… # Documentation ## High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available by topic: - [Ai](https://developer.box.com/9c54c8a9e7d617c8142f8d7218ae7de6/Ai.md) - [Ai studio](https://developer.box.com/7ec7f79b698d7091f3981cc181ae6f2e/AiStudio.md) - [App item associations](https://developer.box.com/747dbfc211ee16fedd3463095b4f3d73/AppItemAssociations.md) - [Archives](https://developer.box.com/68363b6a5902f6336758e607b491218a/Archives.md) - [Authorization](https://developer.box.com/d0a0c38e6569699d1e89e8a61ac9364c/Authorization.md) - [Avatars](https://developer.box.com/3f6c1c9ef77384881ea43a9031b053df/Avatars.md) - [Chunked uploads](https://developer.box.com/168397dd0a28531ceb91fae9a6ba6683/ChunkedUploads.md) - [Classifications](https://developer.box.com/bad50bfefaa4ff6b2711f458120f340e/Classifications.md) - [Collaboration allowlist entries](https://developer.box.com/662f28c2244f02b000d59a07fa07611d/CollaborationAllowlistEntries.md) - [Collaboration allowlist exempt targets](https://developer.box.com/42f060472f4271149debcfa17f461d43/CollaborationAllowlistExemptTargets.md) - [Collections](https://developer.box.com/f5cdcd229ee876cf05b4e22fc5dec07b/Collections.md) - [Comments](https://developer.box.com/254597f2dce8280d2a4abb74cb0a6d66/Comments.md) - [Device pinners](https://developer.box.com/254830ff33e310766a56f197531bc5af/DevicePinners.md) - [Docgen](https://developer.box.com/86f07ae5afdda6f43561e0f35ef27032/Docgen.md) - [Docgen template](https://developer.box.com/badb81e071c9a0b7feb232e0cdaf7146/DocgenTemplate.md) - [Downloads](https://developer.box.com/6ce06f0d62fa68d89e1813f578ff2540/Downloads.md) - [Email aliases](https://developer.box.com/4658210ba0c7761d578c3f5823a06d35/EmailAliases.md) - [Events](https://developer.box.com/8dd34d4c1b76e5cc254ac017ceb3b6f2/Events.md) - [File classifications](https://developer.box.com/1f3f9f04590b2e101f25dd47250e3edf/FileClassifications.md) - [File metadata](https://developer.box.com/c6bf7f682acb8bddad748d54c468859f/FileMetadata.md) - [File requests](https://developer.box.com/949897e145c5a6ed40f9b4b8995ec102/FileRequests.md) - [File version legal holds](https://developer.box.com/17f50a574b39c87d0175bf0b65352f73/FileVersionLegalHolds.md) - [File version retentions](https://developer.box.com/aa22736bc5050e37a08fce5c8aeb4c15/FileVersionRetentions.md) - [File versions](https://developer.box.com/0000158b67b7ecaaed5e28da59de5a95/FileVersions.md) - [File watermarks](https://developer.box.com/6dc698be58eba864fa0da8aff4754dd7/FileWatermarks.md) - [Files](https://developer.box.com/a2f1d8382c641f489e31d3274303ab58/Files.md) - [Folder classifications](https://developer.box.com/bbcc2bdfb9e45ba4f2c1c50d1c083e76/FolderClassifications.md) - [Folder locks](https://developer.box.com/4bbaf513cdeb7e6dad6b0232ce7ce2f0/FolderLocks.md) - [Folder metadata](https://developer.box.com/506b6d6a02cce2665e62964deb674dd8/FolderMetadata.md) - [Folder watermarks](https://developer.box.com/af0d2c0fd49cb12eaaeabb947f0cc973/FolderWatermarks.md) - [Folders](https://developer.box.com/2066cdd4e1d1228c9ddd8b3bbffb51a9/Folders.md) - [Groups](https://developer.box.com/a37e64a2a67bec61a90aa22548bbcd10/Groups.md) - [Hub collaborations](https://developer.box.com/c178b0d27ec978ccb68a14298f78bd8d/HubCollaborations.md) - [Hub items](https://developer.box.com/dc396a70c2e75eca8b46262a7fa76fb3/HubItems.md) - [Hubs](https://developer.box.com/2ba3c9b781e0ce88dc400abbd9c5dda2/Hubs.md) - [Integration mappings](https://developer.box.com/1555bc9e12479eaf3058df376ee790dd/IntegrationMappings.md) - [Invites](https://developer.box.com/8f95eb52c4fee68cf65ee65ff741548b/Invites.md) - [Legal hold policies](https://developer.box.com/4e5743178eb437f048b35b87c49f7fa1/LegalHoldPolicies.md) - [Legal hold policy assignments](https://developer.box.com/628e7b43a5d4d10ef6613020d658f915/LegalHoldPolicyAssignments.md) - [List collaborations](https://developer.box.com/15e4850545eca9890d3f3a0ac9ef1bdc/ListCollaborations.md) - [Memberships](https://developer.box.com/5d7e3bbe50b84444f739b981aa7a90ec/Memberships.md) - [Metadata cascade policies](https://developer.box.com/c57554bdaf0d44c3b59f2f977c10a3fb/MetadataCascadePolicies.md) - [Metadata templates](https://developer.box.com/11b6140f794c573a66e8e18807e4cd4f/MetadataTemplates.md) - [Recent items](https://developer.box.com/3edd4dc632bab6c9b51780ddb364cc22/RecentItems.md) - [Retention policies](https://developer.box.com/757f3b6f7ada00444e869362def63c35/RetentionPolicies.md) - [Retention policy assignments](https://developer.box.com/77cea9a333b25c448076ef9c8a27e6fb/RetentionPolicyAssignments.md) - [Search](https://developer.box.com/28b956bd31d54689d233cf3c2565a3bb/Search.md) - [Session termination](https://developer.box.com/7c8ce1945ad61320b6723b30c0155f45/SessionTermination.md) - [Shared links app items](https://developer.box.com/4f83387f849ef80390aabc5a69aeeb88/SharedLinksAppItems.md) - [Shared links files](https://developer.box.com/bdf2e7eec1d554cf65b60a162ff45322/SharedLinksFiles.md) - [Shared links folders](https://developer.box.com/0846e2de2e792948afcdb45152220d45/SharedLinksFolders.md) - [Shared links web links](https://developer.box.com/e1a04ef46c5992998c4535230d9141e5/SharedLinksWebLinks.md) - [Shield information barrier reports](https://developer.box.com/901ea0b205bbefb6332637c066296cf1/ShieldInformationBarrierReports.md) - [Shield information barrier segment members](https://developer.box.com/81721dae7f613dbf72af9963acd9fbdd/ShieldInformationBarrierSegmentMembers.md) - [Shield information barrier segment restrictions](https://developer.box.com/cfbfe82062910f0c73af42469cd81972/ShieldInformationBarrierSegmentRestrictions.md) - [Shield information barrier segments](https://developer.box.com/0da2a4792fff2d699ae7f48de535aa64/ShieldInformationBarrierSegments.md) - [Shield information barriers](https://developer.box.com/32766871c6c3347a5e264f7872f5769d/ShieldInformationBarriers.md) - [Shield lists](https://developer.box.com/92f0095d02c82ba410ed288f49e93b59/ShieldLists.md) - [Sign requests](https://developer.box.com/89d4065f43b84a7c9238334bc9b7b1b3/SignRequests.md) - [Sign templates](https://developer.box.com/ada0deab883578a1700240437684b295/SignTemplates.md) - [Skills](https://developer.box.com/8d9aa74b7eaf4a027accd670284a6a1d/Skills.md) - [Storage policies](https://developer.box.com/bedd4519d96757189bc0ca855d278c14/StoragePolicies.md) - [Storage policy assignments](https://developer.box.com/418d00ab16ce6e8d031ed2b7806f1425/StoragePolicyAssignments.md) - [Task assignments](https://developer.box.com/dbaa6892870b466f9ebcee31578c963a/TaskAssignments.md) - [Tasks](https://developer.box.com/7a492aae73ab17cac5341acd8c15114b/Tasks.md) - [Terms of service user statuses](https://developer.box.com/33514073546e1c822cd0dcc8a40f5b66/TermsOfServiceUserStatuses.md) - [Terms of services](https://developer.box.com/bd83b1fdc2d3074bb154841004e322bb/TermsOfServices.md) - [Transfer](https://developer.box.com/ae8bc2a5dc0f360509150755da9f9d82/Transfer.md) - [Trashed files](https://developer.box.com/49cffe9600e3331b4e8ce7adeefcf3f4/TrashedFiles.md) - [Trashed folders](https://developer.box.com/54096a5f84173e0d286e1fd5039c88b8/TrashedFolders.md) - [Trashed items](https://developer.box.com/bc07421c01fd50a38981853c003dbdec/TrashedItems.md) - [Trashed web links](https://developer.box.com/d4ad7b7835366e06a935680e53896873/TrashedWebLinks.md) - [Uploads](https://developer.box.com/f9db97938b2f5c81a71257eba2d9c4ca/Uploads.md) - [User collaborations](https://developer.box.com/e06e8d09f643cc3acd54c2cffc9522d1/UserCollaborations.md) - [Users](https://developer.box.com/1a66d4c3c9e49421937828b798a2ccce/Users.md) - [Web links](https://developer.box.com/99e23c4c2b872f87a6a2c45ee7055c18/WebLinks.md) - [Webhooks](https://developer.box.com/5de24e652a33902fbdf953d0581a7c4a/Webhooks.md) - [Workflows](https://developer.box.com/14410c56df80410ba7099312b5830a61/Workflows.md) - [Zip downloads](https://developer.box.com/ff49054385b96efdc423c1860310a469/ZipDownloads.md) --- ## Untitled *Type: page* IMetadataTemplatesManager Find metadata template by instance ID Get metadata template by name Update metadata template Remove metadata… # IMetadataTemplatesManager - [Find metadata template by instance ID](#find-metadata-template-by-instance-id) - [Get metadata template by name](#get-metadata-template-by-name) - [Update metadata template](#update-metadata-template) - [Remove metadata template](#remove-metadata-template) - [Get metadata template by ID](#get-metadata-template-by-id) - [List all global metadata templates](#list-all-global-metadata-templates) - [List all metadata templates for enterprise](#list-all-metadata-templates-for-enterprise) - [Create metadata template](#create-metadata-template) ## Find metadata template by instance ID Finds a metadata template by searching for the ID of an instance of the template. This operation is performed by calling function `GetMetadataTemplatesByInstanceId`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates/). ``` await client.MetadataTemplates.GetMetadataTemplatesByInstanceIdAsync(queryParams: new GetMetadataTemplatesByInstanceIdQueryParams(metadataInstanceId: NullableUtils.Unwrap(createdMetadataInstance.Id))); ``` ### Arguments queryParams `GetMetadataTemplatesByInstanceIdQueryParams` - Query parameters of getMetadataTemplatesByInstanceId method headers `GetMetadataTemplatesByInstanceIdHeaders` - Headers of getMetadataTemplatesByInstanceId method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplates`. Returns a list containing the 1 metadata template that matches the instance ID. ## Get metadata template by name Retrieves a metadata template by its `scope` and `templateKey` values. To find the `scope` and `templateKey` for a template, list all templates for an enterprise or globally, or list all templates applied to a file or folder. This operation is performed by calling function `GetMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id-id-schema/). ``` await client.MetadataTemplates.GetMetadataTemplateAsync(scope: GetMetadataTemplateScope.Enterprise, templateKey: NullableUtils.Unwrap(template.TemplateKey)); ``` ### Arguments scope `GetMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" headers `GetMetadataTemplateHeaders` - Headers of getMetadataTemplate method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template matching the `scope` and `template` name. ## Update metadata template Updates a metadata template. The metadata template can only be updated if the template already exists. The update is applied atomically. If any errors occur during the application of the operations, the metadata template will not be changed. This operation is performed by calling function `UpdateMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-id-id-schema/). ``` await client.MetadataTemplates.UpdateMetadataTemplateAsync(scope: UpdateMetadataTemplateScope.Enterprise, templateKey: templateKey, requestBody: Array.AsReadOnly(new [] {new UpdateMetadataTemplateRequestBody(op: UpdateMetadataTemplateRequestBodyOpField.AddField) { FieldKey = "newfieldname", Data = new Dictionary<string, object>() { { "type", "string" }, { "displayName", "newFieldName" } } }})); ``` ### Arguments scope `UpdateMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" requestBody `IReadOnlyList<UpdateMetadataTemplateRequestBody>` - Request body of updateMetadataTemplate method headers `UpdateMetadataTemplateHeaders` - Headers of updateMetadataTemplate method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplate`. Returns the updated metadata template, with the custom template data included. ## Remove metadata template Delete a metadata template and its instances. This deletion is permanent and can not be reversed. This operation is performed by calling function `DeleteMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-templates-id-id-schema/). ``` await client.MetadataTemplates.DeleteMetadataTemplateAsync(scope: DeleteMetadataTemplateScope.Enterprise, templateKey: NullableUtils.Unwrap(template.TemplateKey)); ``` ### Arguments scope `DeleteMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `string` - The name of the metadata template. Example: "properties" headers `DeleteMetadataTemplateHeaders` - Headers of deleteMetadataTemplate method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the metadata template is successfully deleted. ## Get metadata template by ID Retrieves a metadata template by its ID. This operation is performed by calling function `GetMetadataTemplateById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id/). ``` await client.MetadataTemplates.GetMetadataTemplateByIdAsync(templateId: template.Id); ``` ### Arguments templateId `string` - The ID of the template. Example: "f7a9891f" headers `GetMetadataTemplateByIdHeaders` - Headers of getMetadataTemplateById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template that matches the ID. ## List all global metadata templates Used to retrieve all generic, global metadata templates available to all enterprises using Box. This operation is performed by calling function `GetGlobalMetadataTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-global/). ``` await client.MetadataTemplates.GetGlobalMetadataTemplatesAsync(); ``` ### Arguments queryParams `GetGlobalMetadataTemplatesQueryParams` - Query parameters of getGlobalMetadataTemplates method headers `GetGlobalMetadataTemplatesHeaders` - Headers of getGlobalMetadataTemplates method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates available to all enterprises and their corresponding schema. ## List all metadata templates for enterprise Used to retrieve all metadata templates created to be used specifically within the user's enterprise. This operation is performed by calling function `GetEnterpriseMetadataTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise/). ``` await client.MetadataTemplates.GetEnterpriseMetadataTemplatesAsync(); ``` ### Arguments queryParams `GetEnterpriseMetadataTemplatesQueryParams` - Query parameters of getEnterpriseMetadataTemplates method headers `GetEnterpriseMetadataTemplatesHeaders` - Headers of getEnterpriseMetadataTemplates method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates within an enterprise and their corresponding schema. ## Create metadata template Creates a new metadata template that can be applied to files and folders. This operation is performed by calling function `CreateMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema/). ``` await client.MetadataTemplates.CreateMetadataTemplateAsync(requestBody: new CreateMetadataTemplateRequestBody(scope: "enterprise", displayName: templateKey) { TemplateKey = templateKey, Fields = Array.AsReadOnly(new [] {new CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.String, key: "testName", displayName: "testName"),new CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.Float, key: "age", displayName: "age"),new CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.Date, key: "birthDate", displayName: "birthDate"),new CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.Enum, key: "countryCode", displayName: "countryCode") { Options = Array.AsReadOnly(new [] {new CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "US"),new CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "CA")}) },new CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.MultiSelect, key: "sports", displayName: "sports") { Options = Array.AsReadOnly(new [] {new CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "basketball"),new CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "football"),new CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "tennis")}) }}) }); ``` ### Arguments requestBody `CreateMetadataTemplateRequestBody` - Request body of createMetadataTemplate method headers `CreateMetadataTemplateHeaders` - Headers of createMetadataTemplate method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataTemplate`. The schema representing the metadata template created. --- ## Untitled *Type: page* IRecentItemsManager List recently accessed items List recently accessed items Returns information about the recent items accessed by a user… # IRecentItemsManager - [List recently accessed items](#list-recently-accessed-items) ## List recently accessed items Returns information about the recent items accessed by a user, either in the last 90 days or up to the last 1000 items accessed. This operation is performed by calling function `GetRecentItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-recent-items/). ``` await client.RecentItems.GetRecentItemsAsync(); ``` ### Arguments queryParams `GetRecentItemsQueryParams` - Query parameters of getRecentItems method headers `GetRecentItemsHeaders` - Headers of getRecentItems method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RecentItems`. Returns a list recent items access by a user. --- ## Untitled *Type: page* IRetentionPolicyAssignmentsManager List retention policy assignments Assign retention policy Get retention policy assignment Remove… # IRetentionPolicyAssignmentsManager - [List retention policy assignments](#list-retention-policy-assignments) - [Assign retention policy](#assign-retention-policy) - [Get retention policy assignment](#get-retention-policy-assignment) - [Remove retention policy assignment](#remove-retention-policy-assignment) - [Get files under retention](#get-files-under-retention) ## List retention policy assignments Returns a list of all retention policy assignments associated with a specified retention policy. This operation is performed by calling function `GetRetentionPolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id-assignments/). ``` await client.RetentionPolicyAssignments.GetRetentionPolicyAssignmentsAsync(retentionPolicyId: retentionPolicy.Id); ``` ### Arguments retentionPolicyId `string` - The ID of the retention policy. Example: "982312" queryParams `GetRetentionPolicyAssignmentsQueryParams` - Query parameters of getRetentionPolicyAssignments method headers `GetRetentionPolicyAssignmentsHeaders` - Headers of getRetentionPolicyAssignments method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RetentionPolicyAssignments`. Returns a list of the retention policy assignments associated with the specified retention policy. ## Assign retention policy Assigns a retention policy to an item. This operation is performed by calling function `CreateRetentionPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policy-assignments/). ``` await client.RetentionPolicyAssignments.CreateRetentionPolicyAssignmentAsync(requestBody: new CreateRetentionPolicyAssignmentRequestBody(policyId: retentionPolicy.Id, assignTo: new CreateRetentionPolicyAssignmentRequestBodyAssignToField(type: CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField.Folder) { Id = folder.Id })); ``` ### Arguments requestBody `CreateRetentionPolicyAssignmentRequestBody` - Request body of createRetentionPolicyAssignment method headers `CreateRetentionPolicyAssignmentHeaders` - Headers of createRetentionPolicyAssignment method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns a new retention policy assignment object. ## Get retention policy assignment Retrieves a retention policy assignment. This operation is performed by calling function `GetRetentionPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id/). ``` await client.RetentionPolicyAssignments.GetRetentionPolicyAssignmentByIdAsync(retentionPolicyAssignmentId: retentionPolicyAssignment.Id); ``` ### Arguments retentionPolicyAssignmentId `string` - The ID of the retention policy assignment. Example: "1233123" queryParams `GetRetentionPolicyAssignmentByIdQueryParams` - Query parameters of getRetentionPolicyAssignmentById method headers `GetRetentionPolicyAssignmentByIdHeaders` - Headers of getRetentionPolicyAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns the retention policy assignment object. ## Remove retention policy assignment Removes a retention policy assignment applied to content. This operation is performed by calling function `DeleteRetentionPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policy-assignments-id/). ``` await client.RetentionPolicyAssignments.DeleteRetentionPolicyAssignmentByIdAsync(retentionPolicyAssignmentId: retentionPolicyAssignment.Id); ``` ### Arguments retentionPolicyAssignmentId `string` - The ID of the retention policy assignment. Example: "1233123" headers `DeleteRetentionPolicyAssignmentByIdHeaders` - Headers of deleteRetentionPolicyAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the policy assignment is successfully deleted. ## Get files under retention Returns a list of files under retention for a retention policy assignment. This operation is performed by calling function `GetFilesUnderRetentionPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention/). ``` await client.RetentionPolicyAssignments.GetFilesUnderRetentionPolicyAssignmentAsync(retentionPolicyAssignmentId: retentionPolicyAssignment.Id); ``` ### Arguments retentionPolicyAssignmentId `string` - The ID of the retention policy assignment. Example: "1233123" queryParams `GetFilesUnderRetentionPolicyAssignmentQueryParams` - Query parameters of getFilesUnderRetentionPolicyAssignment method headers `GetFilesUnderRetentionPolicyAssignmentHeaders` - Headers of getFilesUnderRetentionPolicyAssignment method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FilesUnderRetention`. Returns a list of files under retention that are associated with the specified retention policy assignment. --- ## Untitled *Type: page* IRetentionPoliciesManager List retention policies Create retention policy Get retention policy Update retention policy Delete retention… # IRetentionPoliciesManager - [List retention policies](#list-retention-policies) - [Create retention policy](#create-retention-policy) - [Get retention policy](#get-retention-policy) - [Update retention policy](#update-retention-policy) - [Delete retention policy](#delete-retention-policy) ## List retention policies Retrieves all of the retention policies for an enterprise. This operation is performed by calling function `GetRetentionPolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies/). ``` await client.RetentionPolicies.GetRetentionPoliciesAsync(); ``` ### Arguments queryParams `GetRetentionPoliciesQueryParams` - Query parameters of getRetentionPolicies method headers `GetRetentionPoliciesHeaders` - Headers of getRetentionPolicies method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RetentionPolicies`. Returns a list retention policies in the enterprise. ## Create retention policy Creates a retention policy. This operation is performed by calling function `CreateRetentionPolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policies/). ``` await client.RetentionPolicies.CreateRetentionPolicyAsync(requestBody: new CreateRetentionPolicyRequestBody(policyName: retentionPolicyName, policyType: CreateRetentionPolicyRequestBodyPolicyTypeField.Finite, dispositionAction: CreateRetentionPolicyRequestBodyDispositionActionField.RemoveRetention) { AreOwnersNotified = true, CanOwnerExtendRetention = true, Description = retentionDescription, RetentionLength = "1", RetentionType = CreateRetentionPolicyRequestBodyRetentionTypeField.Modifiable }); ``` ### Arguments requestBody `CreateRetentionPolicyRequestBody` - Request body of createRetentionPolicy method headers `CreateRetentionPolicyHeaders` - Headers of createRetentionPolicy method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RetentionPolicy`. Returns a new retention policy object. ## Get retention policy Retrieves a retention policy. This operation is performed by calling function `GetRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id/). ``` await client.RetentionPolicies.GetRetentionPolicyByIdAsync(retentionPolicyId: retentionPolicy.Id); ``` ### Arguments retentionPolicyId `string` - The ID of the retention policy. Example: "982312" queryParams `GetRetentionPolicyByIdQueryParams` - Query parameters of getRetentionPolicyById method headers `GetRetentionPolicyByIdHeaders` - Headers of getRetentionPolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RetentionPolicy`. Returns the retention policy object. ## Update retention policy Updates a retention policy. This operation is performed by calling function `UpdateRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-retention-policies-id/). ``` await client.RetentionPolicies.UpdateRetentionPolicyByIdAsync(retentionPolicyId: retentionPolicy.Id, requestBody: new UpdateRetentionPolicyByIdRequestBody() { PolicyName = updatedRetentionPolicyName }); ``` ### Arguments retentionPolicyId `string` - The ID of the retention policy. Example: "982312" requestBody `UpdateRetentionPolicyByIdRequestBody` - Request body of updateRetentionPolicyById method headers `UpdateRetentionPolicyByIdHeaders` - Headers of updateRetentionPolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `RetentionPolicy`. Returns the updated retention policy object. ## Delete retention policy Permanently deletes a retention policy. This operation is performed by calling function `DeleteRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policies-id/). ``` await client.RetentionPolicies.DeleteRetentionPolicyByIdAsync(retentionPolicyId: retentionPolicy.Id); ``` ### Arguments retentionPolicyId `string` - The ID of the retention policy. Example: "982312" headers `DeleteRetentionPolicyByIdHeaders` - Headers of deleteRetentionPolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the policy has been deleted. --- ## Untitled *Type: page* ISearchManager Query files/folders by metadata Search for content Query files/folders by metadata Create a search using SQL-like syntax to… # ISearchManager - [Query files/folders by metadata](#query-files-folders-by-metadata) - [Search for content](#search-for-content) ## Query files/folders by metadata Create a search using SQL-like syntax to return items that match specific metadata. By default, this endpoint returns only the most basic info about the items for which the query matches. To get additional fields for each item, including any of the metadata, use the `fields` attribute in the query. This operation is performed by calling function `SearchByMetadataQuery`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-queries-execute-read/). ``` await client.Search.SearchByMetadataQueryAsync(requestBody: new MetadataQuery(ancestorFolderId: "0", from: searchFrom) { Query = "name = :name AND age < :age AND birthDate >= :birthDate AND countryCode = :countryCode AND sports = :sports", QueryParams = new Dictionary<string, object>() { { "name", "John" }, { "age", 50 }, { "birthDate", "2001-01-01T02:20:10.120Z" }, { "countryCode", "US" }, { "sports", Array.AsReadOnly(new [] {"basketball","tennis"}) } } }); ``` ### Arguments requestBody `MetadataQuery` - Request body of searchByMetadataQuery method headers `SearchByMetadataQueryHeaders` - Headers of searchByMetadataQuery method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `MetadataQueryResults`. Returns a list of files and folders that match this metadata query. ## Search for content Searches for files, folders, web links, and shared files across the users content or across the entire enterprise. This operation is performed by calling function `SearchForContent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-search/). *Currently we don't have an example for calling `SearchForContent` in integration tests* ### Arguments queryParams `SearchForContentQueryParams` - Query parameters of searchForContent method headers `SearchForContentHeaders` - Headers of searchForContent method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SearchResultsOrSearchResultsWithSharedLinks`. Returns a collection of search results. If there are no matching search results, the `entries` array will be empty. --- ## Untitled *Type: page* ISessionTerminationManager Create jobs to terminate users session Create jobs to terminate user group session Create jobs to terminate users… # ISessionTerminationManager - [Create jobs to terminate users session](#create-jobs-to-terminate-users-session) - [Create jobs to terminate user group session](#create-jobs-to-terminate-user-group-session) ## Create jobs to terminate users session Validates the roles and permissions of the user, and creates asynchronous jobs to terminate the user's sessions. Returns the status for the POST request. This operation is performed by calling function `TerminateUsersSessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-terminate-sessions/). ``` await client.SessionTermination.TerminateUsersSessionsAsync(requestBody: new TerminateUsersSessionsRequestBody(userIds: Array.AsReadOnly(new [] {Utils.GetEnvVar("USER_ID")}), userLogins: Array.AsReadOnly(new [] {NullableUtils.Unwrap(user.Login)}))); ``` ### Arguments requestBody `TerminateUsersSessionsRequestBody` - Request body of terminateUsersSessions method headers `TerminateUsersSessionsHeaders` - Headers of terminateUsersSessions method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. ## Create jobs to terminate user group session Validates the roles and permissions of the group, and creates asynchronous jobs to terminate the group's sessions. Returns the status for the POST request. This operation is performed by calling function `TerminateGroupsSessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups-terminate-sessions/). ``` await client.SessionTermination.TerminateGroupsSessionsAsync(requestBody: new TerminateGroupsSessionsRequestBody(groupIds: Array.AsReadOnly(new [] {group.Id}))); ``` ### Arguments requestBody `TerminateGroupsSessionsRequestBody` - Request body of terminateGroupsSessions method headers `TerminateGroupsSessionsHeaders` - Headers of terminateGroupsSessions method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. --- ## Untitled *Type: page* ISharedLinksAppItemsManager Find app item for shared link Find app item for shared link Returns the app item represented by a shared link… # ISharedLinksAppItemsManager - [Find app item for shared link](#find-app-item-for-shared-link) ## Find app item for shared link Returns the app item represented by a shared link. The link can originate from the current enterprise or another. This operation is performed by calling function `FindAppItemForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--app-items/). ``` await client.SharedLinksAppItems.FindAppItemForSharedLinkAsync(headers: new FindAppItemForSharedLinkHeaders(boxapi: string.Concat("shared_link=", appItemSharedLink))); ``` ### Arguments headers `FindAppItemForSharedLinkHeaders` - Headers of findAppItemForSharedLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `AppItem`. Returns a full app item resource if the shared link is valid and the user has access to it. --- ## Untitled *Type: page* ISharedLinksFoldersManager Find folder for shared link Get shared link for folder Add shared link to folder Update shared link on folder… # ISharedLinksFoldersManager - [Find folder for shared link](#find-folder-for-shared-link) - [Get shared link for folder](#get-shared-link-for-folder) - [Add shared link to folder](#add-shared-link-to-folder) - [Update shared link on folder](#update-shared-link-on-folder) - [Remove shared link from folder](#remove-shared-link-from-folder) ## Find folder for shared link Return the folder represented by a shared link. A shared folder can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared folder when only given a shared link. This operation is performed by calling function `FindFolderForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--folders/). ``` await userClient.SharedLinksFolders.FindFolderForSharedLinkAsync(queryParams: new FindFolderForSharedLinkQueryParams(), headers: new FindFolderForSharedLinkHeaders(boxapi: string.Concat("shared_link=", NullableUtils.Unwrap(folderFromApi.SharedLink).Url, "&shared_link_password=Secret123@"))); ``` ### Arguments queryParams `FindFolderForSharedLinkQueryParams` - Query parameters of findFolderForSharedLink method headers `FindFolderForSharedLinkHeaders` - Headers of findFolderForSharedLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns a full folder resource if the shared link is valid and the user has access to it. ## Get shared link for folder Gets the information for a shared link on a folder. This operation is performed by calling function `GetSharedLinkForFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id--get-shared-link/). ``` await client.SharedLinksFolders.GetSharedLinkForFolderAsync(folderId: folder.Id, queryParams: new GetSharedLinkForFolderQueryParams(fields: "shared_link")); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetSharedLinkForFolderQueryParams` - Query parameters of getSharedLinkForFolder method headers `GetSharedLinkForFolderHeaders` - Headers of getSharedLinkForFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with the additional shared link information. ## Add shared link to folder Adds a shared link to a folder. This operation is performed by calling function `AddShareLinkToFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--add-shared-link/). ``` await client.SharedLinksFolders.AddShareLinkToFolderAsync(folderId: folder.Id, requestBody: new AddShareLinkToFolderRequestBody() { SharedLink = new AddShareLinkToFolderRequestBodySharedLinkField() { Access = AddShareLinkToFolderRequestBodySharedLinkAccessField.Open, Password = "Secret123@" } }, queryParams: new AddShareLinkToFolderQueryParams(fields: "shared_link")); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `AddShareLinkToFolderRequestBody` - Request body of addShareLinkToFolder method queryParams `AddShareLinkToFolderQueryParams` - Query parameters of addShareLinkToFolder method headers `AddShareLinkToFolderHeaders` - Headers of addShareLinkToFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with a new shared link attached. ## Update shared link on folder Updates a shared link on a folder. This operation is performed by calling function `UpdateSharedLinkOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--update-shared-link/). ``` await client.SharedLinksFolders.UpdateSharedLinkOnFolderAsync(folderId: folder.Id, requestBody: new UpdateSharedLinkOnFolderRequestBody() { SharedLink = new UpdateSharedLinkOnFolderRequestBodySharedLinkField() { Access = UpdateSharedLinkOnFolderRequestBodySharedLinkAccessField.Collaborators } }, queryParams: new UpdateSharedLinkOnFolderQueryParams(fields: "shared_link")); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateSharedLinkOnFolderRequestBody` - Request body of updateSharedLinkOnFolder method queryParams `UpdateSharedLinkOnFolderQueryParams` - Query parameters of updateSharedLinkOnFolder method headers `UpdateSharedLinkOnFolderHeaders` - Headers of updateSharedLinkOnFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of the folder, with the updated shared link attached. ## Remove shared link from folder Removes a shared link from a folder. This operation is performed by calling function `RemoveSharedLinkFromFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--remove-shared-link/). ``` await client.SharedLinksFolders.RemoveSharedLinkFromFolderAsync(folderId: folder.Id, requestBody: new RemoveSharedLinkFromFolderRequestBody() { SharedLink = null }, queryParams: new RemoveSharedLinkFromFolderQueryParams(fields: "shared_link")); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `RemoveSharedLinkFromFolderRequestBody` - Request body of removeSharedLinkFromFolder method queryParams `RemoveSharedLinkFromFolderQueryParams` - Query parameters of removeSharedLinkFromFolder method headers `RemoveSharedLinkFromFolderHeaders` - Headers of removeSharedLinkFromFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of a folder, with the shared link removed. --- ## Untitled *Type: page* ISharedLinksFilesManager Find file for shared link Get shared link for file Add shared link to file Update shared link on file Remove shared… # ISharedLinksFilesManager - [Find file for shared link](#find-file-for-shared-link) - [Get shared link for file](#get-shared-link-for-file) - [Add shared link to file](#add-shared-link-to-file) - [Update shared link on file](#update-shared-link-on-file) - [Remove shared link from file](#remove-shared-link-from-file) ## Find file for shared link Returns the file represented by a shared link. A shared file can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared file when only given a shared link. The `shared_link_permission_options` array field can be returned by requesting it in the `fields` query parameter. This operation is performed by calling function `FindFileForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items/). ``` await userClient.SharedLinksFiles.FindFileForSharedLinkAsync(queryParams: new FindFileForSharedLinkQueryParams(), headers: new FindFileForSharedLinkHeaders(boxapi: string.Concat("shared_link=", NullableUtils.Unwrap(fileFromApi.SharedLink).Url, "&shared_link_password=Secret123@"))); ``` ### Arguments queryParams `FindFileForSharedLinkQueryParams` - Query parameters of findFileForSharedLink method headers `FindFileForSharedLinkHeaders` - Headers of findFileForSharedLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. Returns a full file resource if the shared link is valid and the user has access to it. ## Get shared link for file Gets the information for a shared link on a file. This operation is performed by calling function `GetSharedLinkForFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id--get-shared-link/). ``` await client.SharedLinksFiles.GetSharedLinkForFileAsync(fileId: fileId, queryParams: new GetSharedLinkForFileQueryParams(fields: "shared_link")); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetSharedLinkForFileQueryParams` - Query parameters of getSharedLinkForFile method headers `GetSharedLinkForFileHeaders` - Headers of getSharedLinkForFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with the additional shared link information. ## Add shared link to file Adds a shared link to a file. This operation is performed by calling function `AddShareLinkToFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--add-shared-link/). ``` await client.SharedLinksFiles.AddShareLinkToFileAsync(fileId: fileId, requestBody: new AddShareLinkToFileRequestBody() { SharedLink = new AddShareLinkToFileRequestBodySharedLinkField() { Access = AddShareLinkToFileRequestBodySharedLinkAccessField.Open, Password = "Secret123@" } }, queryParams: new AddShareLinkToFileQueryParams(fields: "shared_link")); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `AddShareLinkToFileRequestBody` - Request body of addShareLinkToFile method queryParams `AddShareLinkToFileQueryParams` - Query parameters of addShareLinkToFile method headers `AddShareLinkToFileHeaders` - Headers of addShareLinkToFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with a new shared link attached. ## Update shared link on file Updates a shared link on a file. This operation is performed by calling function `UpdateSharedLinkOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--update-shared-link/). ``` await client.SharedLinksFiles.UpdateSharedLinkOnFileAsync(fileId: fileId, requestBody: new UpdateSharedLinkOnFileRequestBody() { SharedLink = new UpdateSharedLinkOnFileRequestBodySharedLinkField() { Access = UpdateSharedLinkOnFileRequestBodySharedLinkAccessField.Collaborators } }, queryParams: new UpdateSharedLinkOnFileQueryParams(fields: "shared_link")); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateSharedLinkOnFileRequestBody` - Request body of updateSharedLinkOnFile method queryParams `UpdateSharedLinkOnFileQueryParams` - Query parameters of updateSharedLinkOnFile method headers `UpdateSharedLinkOnFileHeaders` - Headers of updateSharedLinkOnFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. Returns a basic representation of the file, with the updated shared link attached. ## Remove shared link from file Removes a shared link from a file. This operation is performed by calling function `RemoveSharedLinkFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--remove-shared-link/). ``` await client.SharedLinksFiles.RemoveSharedLinkFromFileAsync(fileId: fileId, requestBody: new RemoveSharedLinkFromFileRequestBody() { SharedLink = null }, queryParams: new RemoveSharedLinkFromFileQueryParams(fields: "shared_link")); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `RemoveSharedLinkFromFileRequestBody` - Request body of removeSharedLinkFromFile method queryParams `RemoveSharedLinkFromFileQueryParams` - Query parameters of removeSharedLinkFromFile method headers `RemoveSharedLinkFromFileHeaders` - Headers of removeSharedLinkFromFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FileFull`. Returns a basic representation of a file, with the shared link removed. --- ## Untitled *Type: page* IShieldInformationBarrierReportsManager List shield information barrier reports Create shield information barrier report Get shield… # IShieldInformationBarrierReportsManager - [List shield information barrier reports](#list-shield-information-barrier-reports) - [Create shield information barrier report](#create-shield-information-barrier-report) - [Get shield information barrier report by ID](#get-shield-information-barrier-report-by-id) ## List shield information barrier reports Lists shield information barrier reports. This operation is performed by calling function `GetShieldInformationBarrierReports`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports/). ``` await client.ShieldInformationBarrierReports.GetShieldInformationBarrierReportsAsync(queryParams: new GetShieldInformationBarrierReportsQueryParams(shieldInformationBarrierId: barrierId)); ``` ### Arguments queryParams `GetShieldInformationBarrierReportsQueryParams` - Query parameters of getShieldInformationBarrierReports method headers `GetShieldInformationBarrierReportsHeaders` - Headers of getShieldInformationBarrierReports method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierReports`. Returns a paginated list of shield information barrier report objects. ## Create shield information barrier report Creates a shield information barrier report for a given barrier. This operation is performed by calling function `CreateShieldInformationBarrierReport`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-reports/). ``` await client.ShieldInformationBarrierReports.CreateShieldInformationBarrierReportAsync(requestBody: new ShieldInformationBarrierReference() { ShieldInformationBarrier = new ShieldInformationBarrierBase() { Id = barrierId, Type = ShieldInformationBarrierBaseTypeField.ShieldInformationBarrier } }); ``` ### Arguments requestBody `ShieldInformationBarrierReference` - Request body of createShieldInformationBarrierReport method headers `CreateShieldInformationBarrierReportHeaders` - Headers of createShieldInformationBarrierReport method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report information object. ## Get shield information barrier report by ID Retrieves a shield information barrier report by its ID. This operation is performed by calling function `GetShieldInformationBarrierReportById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports-id/). ``` await client.ShieldInformationBarrierReports.GetShieldInformationBarrierReportByIdAsync(shieldInformationBarrierReportId: NullableUtils.Unwrap(createdReport.Id)); ``` ### Arguments shieldInformationBarrierReportId `string` - The ID of the shield information barrier Report. Example: "3423" headers `GetShieldInformationBarrierReportByIdHeaders` - Headers of getShieldInformationBarrierReportById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report object. --- ## Untitled *Type: page* IShieldInformationBarrierSegmentMembersManager Get shield information barrier segment member by ID Delete shield information barrier segment… # IShieldInformationBarrierSegmentMembersManager - [Get shield information barrier segment member by ID](#get-shield-information-barrier-segment-member-by-id) - [Delete shield information barrier segment member by ID](#delete-shield-information-barrier-segment-member-by-id) - [List shield information barrier segment members](#list-shield-information-barrier-segment-members) - [Create shield information barrier segment member](#create-shield-information-barrier-segment-member) ## Get shield information barrier segment member by ID Retrieves a shield information barrier segment member by its ID. This operation is performed by calling function `GetShieldInformationBarrierSegmentMemberById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members-id/). ``` await client.ShieldInformationBarrierSegmentMembers.GetShieldInformationBarrierSegmentMemberByIdAsync(shieldInformationBarrierSegmentMemberId: NullableUtils.Unwrap(segmentMember.Id)); ``` ### Arguments shieldInformationBarrierSegmentMemberId `string` - The ID of the shield information barrier segment Member. Example: "7815" headers `GetShieldInformationBarrierSegmentMemberByIdHeaders` - Headers of getShieldInformationBarrierSegmentMemberById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns the shield information barrier segment member object. ## Delete shield information barrier segment member by ID Deletes a shield information barrier segment member based on provided ID. This operation is performed by calling function `DeleteShieldInformationBarrierSegmentMemberById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-members-id/). ``` await client.ShieldInformationBarrierSegmentMembers.DeleteShieldInformationBarrierSegmentMemberByIdAsync(shieldInformationBarrierSegmentMemberId: NullableUtils.Unwrap(segmentMember.Id)); ``` ### Arguments shieldInformationBarrierSegmentMemberId `string` - The ID of the shield information barrier segment Member. Example: "7815" headers `DeleteShieldInformationBarrierSegmentMemberByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentMemberById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response if the segment member was deleted successfully. ## List shield information barrier segment members Lists shield information barrier segment members based on provided segment IDs. This operation is performed by calling function `GetShieldInformationBarrierSegmentMembers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members/). ``` await client.ShieldInformationBarrierSegmentMembers.GetShieldInformationBarrierSegmentMembersAsync(queryParams: new GetShieldInformationBarrierSegmentMembersQueryParams(shieldInformationBarrierSegmentId: NullableUtils.Unwrap(segment.Id))); ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentMembersQueryParams` - Query parameters of getShieldInformationBarrierSegmentMembers method headers `GetShieldInformationBarrierSegmentMembersHeaders` - Headers of getShieldInformationBarrierSegmentMembers method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMembers`. Returns a paginated list of shield information barrier segment member objects. ## Create shield information barrier segment member Creates a new shield information barrier segment member. This operation is performed by calling function `CreateShieldInformationBarrierSegmentMember`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-members/). ``` await client.ShieldInformationBarrierSegmentMembers.CreateShieldInformationBarrierSegmentMemberAsync(requestBody: new CreateShieldInformationBarrierSegmentMemberRequestBody(shieldInformationBarrierSegment: new CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentField() { Id = NullableUtils.Unwrap(segment.Id), Type = CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentTypeField.ShieldInformationBarrierSegment }, user: new UserBase(id: Utils.GetEnvVar(name: "USER_ID")))); ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentMemberRequestBody` - Request body of createShieldInformationBarrierSegmentMember method headers `CreateShieldInformationBarrierSegmentMemberHeaders` - Headers of createShieldInformationBarrierSegmentMember method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns a new shield information barrier segment member object. --- ## Untitled *Type: page* ISharedLinksWebLinksManager Find web link for shared link Get shared link for web link Add shared link to web link Update shared link on web… # ISharedLinksWebLinksManager - [Find web link for shared link](#find-web-link-for-shared-link) - [Get shared link for web link](#get-shared-link-for-web-link) - [Add shared link to web link](#add-shared-link-to-web-link) - [Update shared link on web link](#update-shared-link-on-web-link) - [Remove shared link from web link](#remove-shared-link-from-web-link) ## Find web link for shared link Returns the web link represented by a shared link. A shared web link can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared web link when only given a shared link. This operation is performed by calling function `FindWebLinkForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--web-links/). ``` await userClient.SharedLinksWebLinks.FindWebLinkForSharedLinkAsync(queryParams: new FindWebLinkForSharedLinkQueryParams(), headers: new FindWebLinkForSharedLinkHeaders(boxapi: string.Concat("shared_link=", NullableUtils.Unwrap(webLinkFromApi.SharedLink).Url, "&shared_link_password=Secret123@"))); ``` ### Arguments queryParams `FindWebLinkForSharedLinkQueryParams` - Query parameters of findWebLinkForSharedLink method headers `FindWebLinkForSharedLinkHeaders` - Headers of findWebLinkForSharedLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `WebLink`. Returns a full web link resource if the shared link is valid and the user has access to it. ## Get shared link for web link Gets the information for a shared link on a web link. This operation is performed by calling function `GetSharedLinkForWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id--get-shared-link/). ``` await client.SharedLinksWebLinks.GetSharedLinkForWebLinkAsync(webLinkId: webLinkId, queryParams: new GetSharedLinkForWebLinkQueryParams(fields: "shared_link")); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" queryParams `GetSharedLinkForWebLinkQueryParams` - Query parameters of getSharedLinkForWebLink method headers `GetSharedLinkForWebLinkHeaders` - Headers of getSharedLinkForWebLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with the additional shared link information. ## Add shared link to web link Adds a shared link to a web link. This operation is performed by calling function `AddShareLinkToWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--add-shared-link/). ``` await client.SharedLinksWebLinks.AddShareLinkToWebLinkAsync(webLinkId: webLinkId, requestBody: new AddShareLinkToWebLinkRequestBody() { SharedLink = new AddShareLinkToWebLinkRequestBodySharedLinkField() { Access = AddShareLinkToWebLinkRequestBodySharedLinkAccessField.Open, Password = "Secret123@" } }, queryParams: new AddShareLinkToWebLinkQueryParams(fields: "shared_link")); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" requestBody `AddShareLinkToWebLinkRequestBody` - Request body of addShareLinkToWebLink method queryParams `AddShareLinkToWebLinkQueryParams` - Query parameters of addShareLinkToWebLink method headers `AddShareLinkToWebLinkHeaders` - Headers of addShareLinkToWebLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with a new shared link attached. ## Update shared link on web link Updates a shared link on a web link. This operation is performed by calling function `UpdateSharedLinkOnWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--update-shared-link/). ``` await client.SharedLinksWebLinks.UpdateSharedLinkOnWebLinkAsync(webLinkId: webLinkId, requestBody: new UpdateSharedLinkOnWebLinkRequestBody() { SharedLink = new UpdateSharedLinkOnWebLinkRequestBodySharedLinkField() { Access = UpdateSharedLinkOnWebLinkRequestBodySharedLinkAccessField.Collaborators } }, queryParams: new UpdateSharedLinkOnWebLinkQueryParams(fields: "shared_link")); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" requestBody `UpdateSharedLinkOnWebLinkRequestBody` - Request body of updateSharedLinkOnWebLink method queryParams `UpdateSharedLinkOnWebLinkQueryParams` - Query parameters of updateSharedLinkOnWebLink method headers `UpdateSharedLinkOnWebLinkHeaders` - Headers of updateSharedLinkOnWebLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `WebLink`. Returns a basic representation of the web link, with the updated shared link attached. ## Remove shared link from web link Removes a shared link from a web link. This operation is performed by calling function `RemoveSharedLinkFromWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--remove-shared-link/). ``` await client.SharedLinksWebLinks.RemoveSharedLinkFromWebLinkAsync(webLinkId: webLinkId, requestBody: new RemoveSharedLinkFromWebLinkRequestBody() { SharedLink = null }, queryParams: new RemoveSharedLinkFromWebLinkQueryParams(fields: "shared_link")); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" requestBody `RemoveSharedLinkFromWebLinkRequestBody` - Request body of removeSharedLinkFromWebLink method queryParams `RemoveSharedLinkFromWebLinkQueryParams` - Query parameters of removeSharedLinkFromWebLink method headers `RemoveSharedLinkFromWebLinkHeaders` - Headers of removeSharedLinkFromWebLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `WebLink`. Returns a basic representation of a web link, with the shared link removed. --- ## Untitled *Type: page* IShieldInformationBarrierSegmentRestrictionsManager Get shield information barrier segment restriction by ID Delete shield information… # IShieldInformationBarrierSegmentRestrictionsManager - [Get shield information barrier segment restriction by ID](#get-shield-information-barrier-segment-restriction-by-id) - [Delete shield information barrier segment restriction by ID](#delete-shield-information-barrier-segment-restriction-by-id) - [List shield information barrier segment restrictions](#list-shield-information-barrier-segment-restrictions) - [Create shield information barrier segment restriction](#create-shield-information-barrier-segment-restriction) ## Get shield information barrier segment restriction by ID Retrieves a shield information barrier segment restriction based on provided ID. This operation is performed by calling function `GetShieldInformationBarrierSegmentRestrictionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions-id/). ``` await client.ShieldInformationBarrierSegmentRestrictions.GetShieldInformationBarrierSegmentRestrictionByIdAsync(shieldInformationBarrierSegmentRestrictionId: segmentRestrictionId); ``` ### Arguments shieldInformationBarrierSegmentRestrictionId `string` - The ID of the shield information barrier segment Restriction. Example: "4563" headers `GetShieldInformationBarrierSegmentRestrictionByIdHeaders` - Headers of getShieldInformationBarrierSegmentRestrictionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the shield information barrier segment restriction object. ## Delete shield information barrier segment restriction by ID Delete shield information barrier segment restriction based on provided ID. This operation is performed by calling function `DeleteShieldInformationBarrierSegmentRestrictionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-restrictions-id/). ``` await client.ShieldInformationBarrierSegmentRestrictions.DeleteShieldInformationBarrierSegmentRestrictionByIdAsync(shieldInformationBarrierSegmentRestrictionId: segmentRestrictionId); ``` ### Arguments shieldInformationBarrierSegmentRestrictionId `string` - The ID of the shield information barrier segment Restriction. Example: "4563" headers `DeleteShieldInformationBarrierSegmentRestrictionByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentRestrictionById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Empty body in response. ## List shield information barrier segment restrictions Lists shield information barrier segment restrictions based on provided segment ID. This operation is performed by calling function `GetShieldInformationBarrierSegmentRestrictions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions/). ``` await client.ShieldInformationBarrierSegmentRestrictions.GetShieldInformationBarrierSegmentRestrictionsAsync(queryParams: new GetShieldInformationBarrierSegmentRestrictionsQueryParams(shieldInformationBarrierSegmentId: segmentId)); ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentRestrictionsQueryParams` - Query parameters of getShieldInformationBarrierSegmentRestrictions method headers `GetShieldInformationBarrierSegmentRestrictionsHeaders` - Headers of getShieldInformationBarrierSegmentRestrictions method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestrictions`. Returns a paginated list of shield information barrier segment restriction objects. ## Create shield information barrier segment restriction Creates a shield information barrier segment restriction object. This operation is performed by calling function `CreateShieldInformationBarrierSegmentRestriction`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-restrictions/). ``` await client.ShieldInformationBarrierSegmentRestrictions.CreateShieldInformationBarrierSegmentRestrictionAsync(requestBody: new CreateShieldInformationBarrierSegmentRestrictionRequestBody(restrictedSegment: new CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentField() { Id = segmentToRestrictId, Type = CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentTypeField.ShieldInformationBarrierSegment }, shieldInformationBarrierSegment: new CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentField() { Id = segmentId, Type = CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentTypeField.ShieldInformationBarrierSegment }, type: CreateShieldInformationBarrierSegmentRestrictionRequestBodyTypeField.ShieldInformationBarrierSegmentRestriction)); ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentRestrictionRequestBody` - Request body of createShieldInformationBarrierSegmentRestriction method headers `CreateShieldInformationBarrierSegmentRestrictionHeaders` - Headers of createShieldInformationBarrierSegmentRestriction method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the newly created Shield Information Barrier Segment Restriction object. --- ## Untitled *Type: page* IShieldInformationBarrierSegmentsManager Get shield information barrier segment with specified ID Delete shield information barrier segment… # IShieldInformationBarrierSegmentsManager - [Get shield information barrier segment with specified ID](#get-shield-information-barrier-segment-with-specified-id) - [Delete shield information barrier segment](#delete-shield-information-barrier-segment) - [Update shield information barrier segment with specified ID](#update-shield-information-barrier-segment-with-specified-id) - [List shield information barrier segments](#list-shield-information-barrier-segments) - [Create shield information barrier segment](#create-shield-information-barrier-segment) ## Get shield information barrier segment with specified ID Retrieves shield information barrier segment based on provided ID.. This operation is performed by calling function `GetShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments-id/). ``` await client.ShieldInformationBarrierSegments.GetShieldInformationBarrierSegmentByIdAsync(shieldInformationBarrierSegmentId: segmentId); ``` ### Arguments shieldInformationBarrierSegmentId `string` - The ID of the shield information barrier segment. Example: "3423" headers `GetShieldInformationBarrierSegmentByIdHeaders` - Headers of getShieldInformationBarrierSegmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the shield information barrier segment object. ## Delete shield information barrier segment Deletes the shield information barrier segment based on provided ID. This operation is performed by calling function `DeleteShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segments-id/). ``` await client.ShieldInformationBarrierSegments.DeleteShieldInformationBarrierSegmentByIdAsync(shieldInformationBarrierSegmentId: segmentId); ``` ### Arguments shieldInformationBarrierSegmentId `string` - The ID of the shield information barrier segment. Example: "3423" headers `DeleteShieldInformationBarrierSegmentByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Empty body in response. ## Update shield information barrier segment with specified ID Updates the shield information barrier segment based on provided ID.. This operation is performed by calling function `UpdateShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-shield-information-barrier-segments-id/). ``` await client.ShieldInformationBarrierSegments.UpdateShieldInformationBarrierSegmentByIdAsync(shieldInformationBarrierSegmentId: segmentId, requestBody: new UpdateShieldInformationBarrierSegmentByIdRequestBody() { Description = updatedSegmentDescription }); ``` ### Arguments shieldInformationBarrierSegmentId `string` - The ID of the shield information barrier segment. Example: "3423" requestBody `UpdateShieldInformationBarrierSegmentByIdRequestBody` - Request body of updateShieldInformationBarrierSegmentById method headers `UpdateShieldInformationBarrierSegmentByIdHeaders` - Headers of updateShieldInformationBarrierSegmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the updated shield information barrier segment object. ## List shield information barrier segments Retrieves a list of shield information barrier segment objects for the specified Information Barrier ID. This operation is performed by calling function `GetShieldInformationBarrierSegments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments/). ``` await client.ShieldInformationBarrierSegments.GetShieldInformationBarrierSegmentsAsync(queryParams: new GetShieldInformationBarrierSegmentsQueryParams(shieldInformationBarrierId: barrierId)); ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentsQueryParams` - Query parameters of getShieldInformationBarrierSegments method headers `GetShieldInformationBarrierSegmentsHeaders` - Headers of getShieldInformationBarrierSegments method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegments`. Returns a paginated list of shield information barrier segment objects. ## Create shield information barrier segment Creates a shield information barrier segment. This operation is performed by calling function `CreateShieldInformationBarrierSegment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segments/). ``` await client.ShieldInformationBarrierSegments.CreateShieldInformationBarrierSegmentAsync(requestBody: new CreateShieldInformationBarrierSegmentRequestBody(shieldInformationBarrier: new ShieldInformationBarrierBase() { Id = barrierId, Type = ShieldInformationBarrierBaseTypeField.ShieldInformationBarrier }, name: segmentName) { Description = segmentDescription }); ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentRequestBody` - Request body of createShieldInformationBarrierSegment method headers `CreateShieldInformationBarrierSegmentHeaders` - Headers of createShieldInformationBarrierSegment method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns a new shield information barrier segment object. --- ## Untitled *Type: page* IShieldInformationBarriersManager Get shield information barrier with specified ID Add changed status of shield information barrier with… # IShieldInformationBarriersManager - [Get shield information barrier with specified ID](#get-shield-information-barrier-with-specified-id) - [Add changed status of shield information barrier with specified ID](#add-changed-status-of-shield-information-barrier-with-specified-id) - [List shield information barriers](#list-shield-information-barriers) - [Create shield information barrier](#create-shield-information-barrier) ## Get shield information barrier with specified ID Get shield information barrier based on provided ID. This operation is performed by calling function `GetShieldInformationBarrierById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers-id/). ``` await client.ShieldInformationBarriers.GetShieldInformationBarrierByIdAsync(shieldInformationBarrierId: barrierId); ``` ### Arguments shieldInformationBarrierId `string` - The ID of the shield information barrier. Example: "1910967" headers `GetShieldInformationBarrierByIdHeaders` - Headers of getShieldInformationBarrierById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the shield information barrier object. ## Add changed status of shield information barrier with specified ID Change status of shield information barrier with the specified ID. This operation is performed by calling function `UpdateShieldInformationBarrierStatus`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers-change-status/). ``` await client.ShieldInformationBarriers.UpdateShieldInformationBarrierStatusAsync(requestBody: new UpdateShieldInformationBarrierStatusRequestBody(id: barrierId, status: UpdateShieldInformationBarrierStatusRequestBodyStatusField.Disabled)); ``` ### Arguments requestBody `UpdateShieldInformationBarrierStatusRequestBody` - Request body of updateShieldInformationBarrierStatus method headers `UpdateShieldInformationBarrierStatusHeaders` - Headers of updateShieldInformationBarrierStatus method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the updated shield information barrier object. ## List shield information barriers Retrieves a list of shield information barrier objects for the enterprise of JWT. This operation is performed by calling function `GetShieldInformationBarriers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers/). ``` await client.ShieldInformationBarriers.GetShieldInformationBarriersAsync(); ``` ### Arguments queryParams `GetShieldInformationBarriersQueryParams` - Query parameters of getShieldInformationBarriers method headers `GetShieldInformationBarriersHeaders` - Headers of getShieldInformationBarriers method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarriers`. Returns a paginated list of shield information barrier objects, empty list if currently no barrier. ## Create shield information barrier Creates a shield information barrier to separate individuals/groups within the same firm and prevents confidential information passing between them. This operation is performed by calling function `CreateShieldInformationBarrier`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers/). ``` await client.ShieldInformationBarriers.CreateShieldInformationBarrierAsync(requestBody: new CreateShieldInformationBarrierRequestBody(enterprise: new EnterpriseBase() { Id = enterpriseId })); ``` ### Arguments requestBody `CreateShieldInformationBarrierRequestBody` - Request body of createShieldInformationBarrier method headers `CreateShieldInformationBarrierHeaders` - Headers of createShieldInformationBarrier method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns a new shield information barrier object. --- ## Untitled *Type: page* IShieldListsManager Get all shield lists in enterprise Create shield list Get single shield list by shield list id Delete single shield list… # IShieldListsManager - [Get all shield lists in enterprise](#get-all-shield-lists-in-enterprise) - [Create shield list](#create-shield-list) - [Get single shield list by shield list id](#get-single-shield-list-by-shield-list-id) - [Delete single shield list by shield list id](#delete-single-shield-list-by-shield-list-id) - [Update shield list](#update-shield-list) ## Get all shield lists in enterprise Retrieves all shield lists in the enterprise. This operation is performed by calling function `GetShieldListsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists/). ``` await client.ShieldLists.GetShieldListsV2025R0Async(); ``` ### Arguments headers `GetShieldListsV2025R0Headers` - Headers of getShieldListsV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldListsV2025R0`. Returns the list of shield list objects. ## Create shield list Creates a shield list. This operation is performed by calling function `CreateShieldListV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-shield-lists/). ``` await client.ShieldLists.CreateShieldListV2025R0Async(requestBody: new ShieldListsCreateV2025R0(name: shieldListCountryName, content: new ShieldListContentCountryV2025R0(type: ShieldListContentCountryV2025R0TypeField.Country, countryCodes: Array.AsReadOnly(new [] {"US","PL"}))) { Description = "A list of things that are shielded" }); ``` ### Arguments requestBody `ShieldListsCreateV2025R0` - Request body of createShieldListV2025R0 method headers `CreateShieldListV2025R0Headers` - Headers of createShieldListV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Get single shield list by shield list id Retrieves a single shield list by its ID. This operation is performed by calling function `GetShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists-id/). ``` await client.ShieldLists.GetShieldListByIdV2025R0Async(shieldListId: shieldListCountry.Id); ``` ### Arguments shieldListId `string` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " headers `GetShieldListByIdV2025R0Headers` - Headers of getShieldListByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Delete single shield list by shield list id Delete a single shield list by its ID. This operation is performed by calling function `DeleteShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-shield-lists-id/). ``` await client.ShieldLists.DeleteShieldListByIdV2025R0Async(shieldListId: shieldListCountry.Id); ``` ### Arguments shieldListId `string` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " headers `DeleteShieldListByIdV2025R0Headers` - Headers of deleteShieldListByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Shield List correctly removed. No content in response. ## Update shield list Updates a shield list. This operation is performed by calling function `UpdateShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-shield-lists-id/). ``` await client.ShieldLists.UpdateShieldListByIdV2025R0Async(shieldListId: shieldListCountry.Id, requestBody: new ShieldListsUpdateV2025R0(name: shieldListCountryName, content: new ShieldListContentCountryV2025R0(type: ShieldListContentCountryV2025R0TypeField.Country, countryCodes: Array.AsReadOnly(new [] {"US"}))) { Description = "Updated description" }); ``` ### Arguments shieldListId `string` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " requestBody `ShieldListsUpdateV2025R0` - Request body of updateShieldListByIdV2025R0 method headers `UpdateShieldListByIdV2025R0Headers` - Headers of updateShieldListByIdV2025R0 method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. --- ## Untitled *Type: page* ISignRequestsManager Cancel Box Sign request Resend Box Sign request Get Box Sign request by ID List Box Sign requests Create Box Sign… # ISignRequestsManager - [Cancel Box Sign request](#cancel-box-sign-request) - [Resend Box Sign request](#resend-box-sign-request) - [Get Box Sign request by ID](#get-box-sign-request-by-id) - [List Box Sign requests](#list-box-sign-requests) - [Create Box Sign request](#create-box-sign-request) ## Cancel Box Sign request Cancels a sign request. This operation is performed by calling function `CancelSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-cancel/). ``` await client.SignRequests.CancelSignRequestAsync(signRequestId: NullableUtils.Unwrap(createdSignRequest.Id)); ``` ### Arguments signRequestId `string` - The ID of the signature request. Example: "33243242" headers `CancelSignRequestHeaders` - Headers of cancelSignRequest method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SignRequest`. Returns a Sign Request object. ## Resend Box Sign request Resends a signature request email to all outstanding signers. This operation is performed by calling function `ResendSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-resend/). *Currently we don't have an example for calling `ResendSignRequest` in integration tests* ### Arguments signRequestId `string` - The ID of the signature request. Example: "33243242" headers `ResendSignRequestHeaders` - Headers of resendSignRequest method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the API call was successful. The email notifications will be sent asynchronously. ## Get Box Sign request by ID Gets a sign request by ID. This operation is performed by calling function `GetSignRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests-id/). ``` await client.SignRequests.GetSignRequestByIdAsync(signRequestId: NullableUtils.Unwrap(createdSignRequest.Id)); ``` ### Arguments signRequestId `string` - The ID of the signature request. Example: "33243242" headers `GetSignRequestByIdHeaders` - Headers of getSignRequestById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SignRequest`. Returns a signature request. ## List Box Sign requests Gets signature requests created by a user. If the `sign_files` and/or `parent_folder` are deleted, the signature request will not return in the list. This operation is performed by calling function `GetSignRequests`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests/). ``` await client.SignRequests.GetSignRequestsAsync(); ``` ### Arguments queryParams `GetSignRequestsQueryParams` - Query parameters of getSignRequests method headers `GetSignRequestsHeaders` - Headers of getSignRequests method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SignRequests`. Returns a collection of sign requests. ## Create Box Sign request Creates a signature request. This involves preparing a document for signing and sending the signature request to signers. This operation is performed by calling function `CreateSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests/). ``` await client.SignRequests.CreateSignRequestAsync(requestBody: new SignRequestCreateRequest(signers: Array.AsReadOnly(new [] {new SignRequestCreateSigner() { Email = signerEmail, SuppressNotifications = true, DeclinedRedirectUrl = "https://www.box.com", EmbedUrlExternalUserId = "123", IsInPerson = false, LoginRequired = false, Password = "password", Role = SignRequestCreateSignerRoleField.Signer }}), areRemindersEnabled: true, areTextSignaturesEnabled: true, daysValid: 30, declinedRedirectUrl: "https://www.box.com", emailMessage: "Please sign this document", emailSubject: "Sign this document", externalId: "123", externalSystemName: "BoxSignIntegration", isDocumentPreparationNeeded: false, name: "Sign Request", parentFolder: new FolderMini(id: destinationFolder.Id), redirectUrl: "https://www.box.com", prefillTags: Array.AsReadOnly(new [] {new SignRequestPrefillTag() { DateValue = Utils.DateFromString(date: "2035-01-01"), DocumentTagId = "0" }}), sourceFiles: Array.AsReadOnly(new [] {new FileBase(id: fileToSign.Id)}))); ``` ### Arguments requestBody `SignRequestCreateRequest` - Request body of createSignRequest method headers `CreateSignRequestHeaders` - Headers of createSignRequest method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SignRequest`. Returns a Box Sign request object. --- ## Untitled *Type: page* ISignTemplatesManager List Box Sign templates Get Box Sign template by ID List Box Sign templates Gets Box Sign templates created by a user… # ISignTemplatesManager - [List Box Sign templates](#list-box-sign-templates) - [Get Box Sign template by ID](#get-box-sign-template-by-id) ## List Box Sign templates Gets Box Sign templates created by a user. This operation is performed by calling function `GetSignTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates/). ``` await client.SignTemplates.GetSignTemplatesAsync(queryParams: new GetSignTemplatesQueryParams() { Limit = 2 }); ``` ### Arguments queryParams `GetSignTemplatesQueryParams` - Query parameters of getSignTemplates method headers `GetSignTemplatesHeaders` - Headers of getSignTemplates method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SignTemplates`. Returns a collection of templates. ## Get Box Sign template by ID Fetches details of a specific Box Sign template. This operation is performed by calling function `GetSignTemplateById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates-id/). ``` await client.SignTemplates.GetSignTemplateByIdAsync(templateId: NullableUtils.Unwrap(NullableUtils.Unwrap(signTemplates.Entries)[0].Id)); ``` ### Arguments templateId `string` - The ID of a Box Sign template. Example: "123075213-7d117509-8f05-42e4-a5ef-5190a319d41d" headers `GetSignTemplateByIdHeaders` - Headers of getSignTemplateById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SignTemplate`. Returns details of a template. --- ## Untitled *Type: page* ISkillsManager List Box Skill cards on file Create Box Skill cards on file Update Box Skill cards on file Remove Box Skill cards from file… # ISkillsManager - [List Box Skill cards on file](#list-box-skill-cards-on-file) - [Create Box Skill cards on file](#create-box-skill-cards-on-file) - [Update Box Skill cards on file](#update-box-skill-cards-on-file) - [Remove Box Skill cards from file](#remove-box-skill-cards-from-file) - [Update all Box Skill cards on file](#update-all-box-skill-cards-on-file) ## List Box Skill cards on file List the Box Skills metadata cards that are attached to a file. This operation is performed by calling function `GetBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-global-boxSkillsCards/). *Currently we don't have an example for calling `GetBoxSkillCardsOnFile` in integration tests* ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetBoxSkillCardsOnFileHeaders` - Headers of getBoxSkillCardsOnFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SkillCardsMetadata`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Create Box Skill cards on file Applies one or more Box Skills metadata cards to a file. This operation is performed by calling function `CreateBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-global-boxSkillsCards/). *Currently we don't have an example for calling `CreateBoxSkillCardsOnFile` in integration tests* ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CreateBoxSkillCardsOnFileRequestBody` - Request body of createBoxSkillCardsOnFile method headers `CreateBoxSkillCardsOnFileHeaders` - Headers of createBoxSkillCardsOnFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update Box Skill cards on file Updates one or more Box Skills metadata cards to a file. This operation is performed by calling function `UpdateBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-global-boxSkillsCards/). *Currently we don't have an example for calling `UpdateBoxSkillCardsOnFile` in integration tests* ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `IReadOnlyList<UpdateBoxSkillCardsOnFileRequestBody>` - Request body of updateBoxSkillCardsOnFile method headers `UpdateBoxSkillCardsOnFileHeaders` - Headers of updateBoxSkillCardsOnFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the updated metadata template, with the custom template data included. ## Remove Box Skill cards from file Removes any Box Skills cards metadata from a file. This operation is performed by calling function `DeleteBoxSkillCardsFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-global-boxSkillsCards/). *Currently we don't have an example for calling `DeleteBoxSkillCardsFromFile` in integration tests* ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteBoxSkillCardsFromFileHeaders` - Headers of deleteBoxSkillCardsFromFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the cards are successfully deleted. ## Update all Box Skill cards on file An alternative method that can be used to overwrite and update all Box Skill metadata cards on a file. This operation is performed by calling function `UpdateAllSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-skill-invocations-id/). *Currently we don't have an example for calling `UpdateAllSkillCardsOnFile` in integration tests* ### Arguments skillId `string` - The ID of the skill to apply this metadata for. Example: "33243242" requestBody `UpdateAllSkillCardsOnFileRequestBody` - Request body of updateAllSkillCardsOnFile method headers `UpdateAllSkillCardsOnFileHeaders` - Headers of updateAllSkillCardsOnFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the card has been successfully updated. --- ## Untitled *Type: page* IStoragePoliciesManager List storage policies Get storage policy List storage policies Fetches all the storage policies in the enterprise… # IStoragePoliciesManager - [List storage policies](#list-storage-policies) - [Get storage policy](#get-storage-policy) ## List storage policies Fetches all the storage policies in the enterprise. This operation is performed by calling function `GetStoragePolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies/). ``` await client.StoragePolicies.GetStoragePoliciesAsync(); ``` ### Arguments queryParams `GetStoragePoliciesQueryParams` - Query parameters of getStoragePolicies method headers `GetStoragePoliciesHeaders` - Headers of getStoragePolicies method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `StoragePolicies`. Returns a collection of storage policies. ## Get storage policy Fetches a specific storage policy. This operation is performed by calling function `GetStoragePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies-id/). ``` await client.StoragePolicies.GetStoragePolicyByIdAsync(storagePolicyId: storagePolicy.Id); ``` ### Arguments storagePolicyId `string` - The ID of the storage policy. Example: "34342" headers `GetStoragePolicyByIdHeaders` - Headers of getStoragePolicyById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `StoragePolicy`. Returns a storage policy object. --- ## Untitled *Type: page* IStoragePolicyAssignmentsManager List storage policy assignments Assign storage policy Get storage policy assignment Update storage policy… # IStoragePolicyAssignmentsManager - [List storage policy assignments](#list-storage-policy-assignments) - [Assign storage policy](#assign-storage-policy) - [Get storage policy assignment](#get-storage-policy-assignment) - [Update storage policy assignment](#update-storage-policy-assignment) - [Unassign storage policy](#unassign-storage-policy) ## List storage policy assignments Fetches all the storage policy assignment for an enterprise or user. This operation is performed by calling function `GetStoragePolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments/). ``` await client.StoragePolicyAssignments.GetStoragePolicyAssignmentsAsync(queryParams: new GetStoragePolicyAssignmentsQueryParams(resolvedForType: GetStoragePolicyAssignmentsQueryParamsResolvedForTypeField.User, resolvedForId: userId)); ``` ### Arguments queryParams `GetStoragePolicyAssignmentsQueryParams` - Query parameters of getStoragePolicyAssignments method headers `GetStoragePolicyAssignmentsHeaders` - Headers of getStoragePolicyAssignments method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `StoragePolicyAssignments`. Returns a collection of storage policies for the enterprise or user. ## Assign storage policy Creates a storage policy assignment for an enterprise or user. This operation is performed by calling function `CreateStoragePolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-storage-policy-assignments/). ``` await client.StoragePolicyAssignments.CreateStoragePolicyAssignmentAsync(requestBody: new CreateStoragePolicyAssignmentRequestBody(storagePolicy: new CreateStoragePolicyAssignmentRequestBodyStoragePolicyField(id: policyId), assignedTo: new CreateStoragePolicyAssignmentRequestBodyAssignedToField(id: userId, type: CreateStoragePolicyAssignmentRequestBodyAssignedToTypeField.User))); ``` ### Arguments requestBody `CreateStoragePolicyAssignmentRequestBody` - Request body of createStoragePolicyAssignment method headers `CreateStoragePolicyAssignmentHeaders` - Headers of createStoragePolicyAssignment method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns the new storage policy assignment created. ## Get storage policy assignment Fetches a specific storage policy assignment. This operation is performed by calling function `GetStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments-id/). ``` await client.StoragePolicyAssignments.GetStoragePolicyAssignmentByIdAsync(storagePolicyAssignmentId: storagePolicyAssignment.Id); ``` ### Arguments storagePolicyAssignmentId `string` - The ID of the storage policy assignment. Example: "932483" headers `GetStoragePolicyAssignmentByIdHeaders` - Headers of getStoragePolicyAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns a storage policy assignment object. ## Update storage policy assignment Updates a specific storage policy assignment. This operation is performed by calling function `UpdateStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-storage-policy-assignments-id/). ``` await client.StoragePolicyAssignments.UpdateStoragePolicyAssignmentByIdAsync(storagePolicyAssignmentId: storagePolicyAssignment.Id, requestBody: new UpdateStoragePolicyAssignmentByIdRequestBody(storagePolicy: new UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyField(id: storagePolicy2.Id))); ``` ### Arguments storagePolicyAssignmentId `string` - The ID of the storage policy assignment. Example: "932483" requestBody `UpdateStoragePolicyAssignmentByIdRequestBody` - Request body of updateStoragePolicyAssignmentById method headers `UpdateStoragePolicyAssignmentByIdHeaders` - Headers of updateStoragePolicyAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns an updated storage policy assignment object. ## Unassign storage policy Delete a storage policy assignment. Deleting a storage policy assignment on a user will have the user inherit the enterprise's default storage policy. There is a rate limit for calling this endpoint of only twice per user in a 24 hour time frame. This operation is performed by calling function `DeleteStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-storage-policy-assignments-id/). ``` await client.StoragePolicyAssignments.DeleteStoragePolicyAssignmentByIdAsync(storagePolicyAssignmentId: storagePolicyAssignment.Id); ``` ### Arguments storagePolicyAssignmentId `string` - The ID of the storage policy assignment. Example: "932483" headers `DeleteStoragePolicyAssignmentByIdHeaders` - Headers of deleteStoragePolicyAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the storage policy assignment is successfully deleted. --- ## Untitled *Type: page* ITasksManager List tasks on file Create task Get task Update task Remove task List tasks on file Retrieves a list of all the tasks for a… # ITasksManager - [List tasks on file](#list-tasks-on-file) - [Create task](#create-task) - [Get task](#get-task) - [Update task](#update-task) - [Remove task](#remove-task) ## List tasks on file Retrieves a list of all the tasks for a file. This endpoint does not support pagination. This operation is performed by calling function `GetFileTasks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-tasks/). ``` await client.Tasks.GetFileTasksAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileTasksHeaders` - Headers of getFileTasks method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Tasks`. Returns a list of tasks on a file. If there are no tasks on this file an empty collection is returned instead. ## Create task Creates a single task on a file. This task is not assigned to any user and will need to be assigned separately. This operation is performed by calling function `CreateTask`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-tasks/). ``` await client.Tasks.CreateTaskAsync(requestBody: new CreateTaskRequestBody(item: new CreateTaskRequestBodyItemField() { Type = CreateTaskRequestBodyItemTypeField.File, Id = file.Id }) { Message = "test message", DueAt = dateTime, Action = CreateTaskRequestBodyActionField.Review, CompletionRule = CreateTaskRequestBodyCompletionRuleField.AllAssignees }); ``` ### Arguments requestBody `CreateTaskRequestBody` - Request body of createTask method headers `CreateTaskHeaders` - Headers of createTask method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Task`. Returns the newly created task. ## Get task Retrieves information about a specific task. This operation is performed by calling function `GetTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id/). ``` await client.Tasks.GetTaskByIdAsync(taskId: NullableUtils.Unwrap(task.Id)); ``` ### Arguments taskId `string` - The ID of the task. Example: "12345" headers `GetTaskByIdHeaders` - Headers of getTaskById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Task`. Returns a task object. ## Update task Updates a task. This can be used to update a task's configuration, or to update its completion state. This operation is performed by calling function `UpdateTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-tasks-id/). ``` await client.Tasks.UpdateTaskByIdAsync(taskId: NullableUtils.Unwrap(task.Id), requestBody: new UpdateTaskByIdRequestBody() { Message = "updated message" }); ``` ### Arguments taskId `string` - The ID of the task. Example: "12345" requestBody `UpdateTaskByIdRequestBody` - Request body of updateTaskById method headers `UpdateTaskByIdHeaders` - Headers of updateTaskById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Task`. Returns the updated task object. ## Remove task Removes a task from a file. This operation is performed by calling function `DeleteTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-tasks-id/). ``` await client.Tasks.DeleteTaskByIdAsync(taskId: NullableUtils.Unwrap(task.Id)); ``` ### Arguments taskId `string` - The ID of the task. Example: "12345" headers `DeleteTaskByIdHeaders` - Headers of deleteTaskById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the task was successfully deleted. --- ## Untitled *Type: page* ITermsOfServiceUserStatusesManager List terms of service user statuses Create terms of service status for new user Update terms of service… # ITermsOfServiceUserStatusesManager - [List terms of service user statuses](#list-terms-of-service-user-statuses) - [Create terms of service status for new user](#create-terms-of-service-status-for-new-user) - [Update terms of service status for existing user](#update-terms-of-service-status-for-existing-user) ## List terms of service user statuses Retrieves an overview of users and their status for a terms of service, including Whether they have accepted the terms and when. This operation is performed by calling function `GetTermsOfServiceUserStatuses`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-service-user-statuses/). ``` await client.TermsOfServiceUserStatuses.GetTermsOfServiceUserStatusesAsync(queryParams: new GetTermsOfServiceUserStatusesQueryParams(tosId: tos.Id) { UserId = user.Id }); ``` ### Arguments queryParams `GetTermsOfServiceUserStatusesQueryParams` - Query parameters of getTermsOfServiceUserStatuses method headers `GetTermsOfServiceUserStatusesHeaders` - Headers of getTermsOfServiceUserStatuses method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TermsOfServiceUserStatuses`. Returns a list of terms of service statuses. ## Create terms of service status for new user Sets the status for a terms of service for a user. This operation is performed by calling function `CreateTermsOfServiceStatusForUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-service-user-statuses/). ``` await client.TermsOfServiceUserStatuses.CreateTermsOfServiceStatusForUserAsync(requestBody: new CreateTermsOfServiceStatusForUserRequestBody(tos: new CreateTermsOfServiceStatusForUserRequestBodyTosField(id: tos.Id), user: new CreateTermsOfServiceStatusForUserRequestBodyUserField(id: user.Id), isAccepted: false)); ``` ### Arguments requestBody `CreateTermsOfServiceStatusForUserRequestBody` - Request body of createTermsOfServiceStatusForUser method headers `CreateTermsOfServiceStatusForUserHeaders` - Headers of createTermsOfServiceStatusForUser method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns a terms of service status object. ## Update terms of service status for existing user Updates the status for a terms of service for a user. This operation is performed by calling function `UpdateTermsOfServiceStatusForUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-service-user-statuses-id/). ``` await client.TermsOfServiceUserStatuses.UpdateTermsOfServiceStatusForUserByIdAsync(termsOfServiceUserStatusId: createdTosUserStatus.Id, requestBody: new UpdateTermsOfServiceStatusForUserByIdRequestBody(isAccepted: true)); ``` ### Arguments termsOfServiceUserStatusId `string` - The ID of the terms of service status. Example: "324234" requestBody `UpdateTermsOfServiceStatusForUserByIdRequestBody` - Request body of updateTermsOfServiceStatusForUserById method headers `UpdateTermsOfServiceStatusForUserByIdHeaders` - Headers of updateTermsOfServiceStatusForUserById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns the updated terms of service status object. --- ## Untitled *Type: page* ITermsOfServicesManager List terms of services Create terms of service Get terms of service Update terms of service List terms of services… # ITermsOfServicesManager - [List terms of services](#list-terms-of-services) - [Create terms of service](#create-terms-of-service) - [Get terms of service](#get-terms-of-service) - [Update terms of service](#update-terms-of-service) ## List terms of services Returns the current terms of service text and settings for the enterprise. This operation is performed by calling function `GetTermsOfService`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services/). ``` await client.TermsOfServices.GetTermsOfServiceAsync(); ``` ### Arguments queryParams `GetTermsOfServiceQueryParams` - Query parameters of getTermsOfService method headers `GetTermsOfServiceHeaders` - Headers of getTermsOfService method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TermsOfServices`. Returns a collection of terms of service text and settings for the enterprise. ## Create terms of service Creates a terms of service for a given enterprise and type of user. This operation is performed by calling function `CreateTermsOfService`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-services/). ``` await client.TermsOfServices.CreateTermsOfServiceAsync(requestBody: new CreateTermsOfServiceRequestBody(status: CreateTermsOfServiceRequestBodyStatusField.Disabled, text: "Test TOS") { TosType = CreateTermsOfServiceRequestBodyTosTypeField.Managed }); ``` ### Arguments requestBody `CreateTermsOfServiceRequestBody` - Request body of createTermsOfService method headers `CreateTermsOfServiceHeaders` - Headers of createTermsOfService method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TermsOfService`. Returns a new task object. ## Get terms of service Fetches a specific terms of service. This operation is performed by calling function `GetTermsOfServiceById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services-id/). *Currently we don't have an example for calling `GetTermsOfServiceById` in integration tests* ### Arguments termsOfServiceId `string` - The ID of the terms of service. Example: "324234" headers `GetTermsOfServiceByIdHeaders` - Headers of getTermsOfServiceById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TermsOfService`. Returns a terms of service object. ## Update terms of service Updates a specific terms of service. This operation is performed by calling function `UpdateTermsOfServiceById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-services-id/). ``` await client.TermsOfServices.UpdateTermsOfServiceByIdAsync(termsOfServiceId: tos.Id, requestBody: new UpdateTermsOfServiceByIdRequestBody(status: UpdateTermsOfServiceByIdRequestBodyStatusField.Disabled, text: "TOS")); ``` ### Arguments termsOfServiceId `string` - The ID of the terms of service. Example: "324234" requestBody `UpdateTermsOfServiceByIdRequestBody` - Request body of updateTermsOfServiceById method headers `UpdateTermsOfServiceByIdHeaders` - Headers of updateTermsOfServiceById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TermsOfService`. Returns an updated terms of service object. --- ## Untitled *Type: page* ITaskAssignmentsManager List task assignments Assign task Get task assignment Update task assignment Unassign task List task assignments… # ITaskAssignmentsManager - [List task assignments](#list-task-assignments) - [Assign task](#assign-task) - [Get task assignment](#get-task-assignment) - [Update task assignment](#update-task-assignment) - [Unassign task](#unassign-task) ## List task assignments Lists all of the assignments for a given task. This operation is performed by calling function `GetTaskAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id-assignments/). ``` await client.TaskAssignments.GetTaskAssignmentsAsync(taskId: NullableUtils.Unwrap(task.Id)); ``` ### Arguments taskId `string` - The ID of the task. Example: "12345" headers `GetTaskAssignmentsHeaders` - Headers of getTaskAssignments method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TaskAssignments`. Returns a collection of task assignment defining what task on a file has been assigned to which users and by who. ## Assign task Assigns a task to a user. A task can be assigned to more than one user by creating multiple assignments. This operation is performed by calling function `CreateTaskAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-task-assignments/). ``` await client.TaskAssignments.CreateTaskAssignmentAsync(requestBody: new CreateTaskAssignmentRequestBody(task: new CreateTaskAssignmentRequestBodyTaskField(type: CreateTaskAssignmentRequestBodyTaskTypeField.Task, id: NullableUtils.Unwrap(task.Id)), assignTo: new CreateTaskAssignmentRequestBodyAssignToField() { Id = currentUser.Id })); ``` ### Arguments requestBody `CreateTaskAssignmentRequestBody` - Request body of createTaskAssignment method headers `CreateTaskAssignmentHeaders` - Headers of createTaskAssignment method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TaskAssignment`. Returns a new task assignment object. ## Get task assignment Retrieves information about a task assignment. This operation is performed by calling function `GetTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-task-assignments-id/). ``` await client.TaskAssignments.GetTaskAssignmentByIdAsync(taskAssignmentId: NullableUtils.Unwrap(taskAssignment.Id)); ``` ### Arguments taskAssignmentId `string` - The ID of the task assignment. Example: "12345" headers `GetTaskAssignmentByIdHeaders` - Headers of getTaskAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TaskAssignment`. Returns a task assignment, specifying who the task has been assigned to and by whom. ## Update task assignment Updates a task assignment. This endpoint can be used to update the state of a task assigned to a user. This operation is performed by calling function `UpdateTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-task-assignments-id/). ``` await client.TaskAssignments.UpdateTaskAssignmentByIdAsync(taskAssignmentId: NullableUtils.Unwrap(taskAssignment.Id), requestBody: new UpdateTaskAssignmentByIdRequestBody() { Message = "updated message", ResolutionState = UpdateTaskAssignmentByIdRequestBodyResolutionStateField.Approved }); ``` ### Arguments taskAssignmentId `string` - The ID of the task assignment. Example: "12345" requestBody `UpdateTaskAssignmentByIdRequestBody` - Request body of updateTaskAssignmentById method headers `UpdateTaskAssignmentByIdHeaders` - Headers of updateTaskAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TaskAssignment`. Returns the updated task assignment object. ## Unassign task Deletes a specific task assignment. This operation is performed by calling function `DeleteTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-task-assignments-id/). ``` await client.TaskAssignments.DeleteTaskAssignmentByIdAsync(taskAssignmentId: NullableUtils.Unwrap(taskAssignment.Id)); ``` ### Arguments taskAssignmentId `string` - The ID of the task assignment. Example: "12345" headers `DeleteTaskAssignmentByIdHeaders` - Headers of deleteTaskAssignmentById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the task assignment was successfully deleted. --- ## Untitled *Type: page* ITransferManager Transfer owned folders Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into… # ITransferManager - [Transfer owned folders](#transfer-owned-folders) ## Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into another user's account Only the root folder (`0`) can be transferred. Folders can only be moved across users by users with administrative permissions. All existing shared links and folder-level collaborations are transferred during the operation. Please note that while collaborations at the individual file-level are transferred during the operation, the collaborations are deleted when the original user is deleted. If the user has a large number of items across all folders, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. If the destination path has a metadata cascade policy attached to any of the parent folders, a metadata cascade operation will be kicked off asynchronously. There is currently no way to check for when this operation is finished. The destination folder's name will be in the format `{User}'s Files and Folders`, where `{User}` is the display name of the user. To make this API call your application will need to have the "Read and write all files and folders stored in Box" scope enabled. Please make sure the destination user has access to `Relay` or `Relay Lite`, and has access to the files and folders involved in the workflows being transferred. Admins will receive an email when the operation is completed. This operation is performed by calling function `TransferOwnedFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id-folders-0/). ``` await client.Transfer.TransferOwnedFolderAsync(userId: sourceUser.Id, requestBody: new TransferOwnedFolderRequestBody(ownedBy: new TransferOwnedFolderRequestBodyOwnedByField(id: targetUser.Id)), queryParams: new TransferOwnedFolderQueryParams() { Notify = false }); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" requestBody `TransferOwnedFolderRequestBody` - Request body of transferOwnedFolder method queryParams `TransferOwnedFolderQueryParams` - Query parameters of transferOwnedFolder method headers `TransferOwnedFolderHeaders` - Headers of transferOwnedFolder method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `FolderFull`. Returns the information for the newly created destination folder. --- ## Untitled *Type: page* ITrashedFoldersManager Restore folder Get trashed folder Permanently remove folder Restore folder Restores a folder that has been moved to… # ITrashedFoldersManager - [Restore folder](#restore-folder) - [Get trashed folder](#get-trashed-folder) - [Permanently remove folder](#permanently-remove-folder) ## Restore folder Restores a folder that has been moved to the trash. An optional new parent ID can be provided to restore the folder to in case the original folder has been deleted. During this operation, part of the file tree will be locked, mainly the source folder and all of its descendants, as well as the destination folder. For the duration of the operation, no other move, copy, delete, or restore operation can performed on any of the locked folders. This operation is performed by calling function `RestoreFolderFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id/). ``` await client.TrashedFolders.RestoreFolderFromTrashAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `RestoreFolderFromTrashRequestBody` - Request body of restoreFolderFromTrash method queryParams `RestoreFolderFromTrashQueryParams` - Query parameters of restoreFolderFromTrash method headers `RestoreFolderFromTrashHeaders` - Headers of restoreFolderFromTrash method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TrashFolderRestored`. Returns a folder object when the folder has been restored. ## Get trashed folder Retrieves a folder that has been moved to the trash. Please note that only if the folder itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `GetTrashedFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-trash/). ``` await client.TrashedFolders.GetTrashedFolderByIdAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetTrashedFolderByIdQueryParams` - Query parameters of getTrashedFolderById method headers `GetTrashedFolderByIdHeaders` - Headers of getTrashedFolderById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TrashFolder`. Returns the folder that was trashed, including information about when the it was moved to the trash. ## Permanently remove folder Permanently deletes a folder that is in the trash. This action cannot be undone. This operation is performed by calling function `DeleteTrashedFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-trash/). ``` await client.TrashedFolders.DeleteTrashedFolderByIdAsync(folderId: folder.Id); ``` ### Arguments folderId `string` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteTrashedFolderByIdHeaders` - Headers of deleteTrashedFolderById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the folder was permanently deleted. --- ## Untitled *Type: page* ITrashedFilesManager Restore file Get trashed file Permanently remove file Restore file Restores a file that has been moved to the trash. An… # ITrashedFilesManager - [Restore file](#restore-file) - [Get trashed file](#get-trashed-file) - [Permanently remove file](#permanently-remove-file) ## Restore file Restores a file that has been moved to the trash. An optional new parent ID can be provided to restore the file to in case the original folder has been deleted. This operation is performed by calling function `RestoreFileFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id/). ``` await client.TrashedFiles.RestoreFileFromTrashAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `RestoreFileFromTrashRequestBody` - Request body of restoreFileFromTrash method queryParams `RestoreFileFromTrashQueryParams` - Query parameters of restoreFileFromTrash method headers `RestoreFileFromTrashHeaders` - Headers of restoreFileFromTrash method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TrashFileRestored`. Returns a file object when the file has been restored. ## Get trashed file Retrieves a file that has been moved to the trash. Please note that only if the file itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `GetTrashedFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-trash/). ``` await client.TrashedFiles.GetTrashedFileByIdAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetTrashedFileByIdQueryParams` - Query parameters of getTrashedFileById method headers `GetTrashedFileByIdHeaders` - Headers of getTrashedFileById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TrashFile`. Returns the file that was trashed, including information about when the it was moved to the trash. ## Permanently remove file Permanently deletes a file that is in the trash. This action cannot be undone. This operation is performed by calling function `DeleteTrashedFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-trash/). ``` await client.TrashedFiles.DeleteTrashedFileByIdAsync(fileId: file.Id); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteTrashedFileByIdHeaders` - Headers of deleteTrashedFileById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the file was permanently deleted. --- ## Untitled *Type: page* ITrashedItemsManager List trashed items List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute… # ITrashedItemsManager - [List trashed items](#list-trashed-items) ## List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute in the full files or folders objects can be passed in with the `fields` parameter to retrieve those specific attributes that are not returned by default. This endpoint defaults to use offset-based pagination, yet also supports marker-based pagination using the `marker` parameter. This operation is performed by calling function `GetTrashedItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-trash-items/). ``` await client.TrashedItems.GetTrashedItemsAsync(); ``` ### Arguments queryParams `GetTrashedItemsQueryParams` - Query parameters of getTrashedItems method headers `GetTrashedItemsHeaders` - Headers of getTrashedItems method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Items`. Returns a list of items that have been deleted. --- ## Untitled *Type: page* ITrashedWebLinksManager Restore web link Get trashed web link Permanently remove web link Restore web link Restores a web link that has been… # ITrashedWebLinksManager - [Restore web link](#restore-web-link) - [Get trashed web link](#get-trashed-web-link) - [Permanently remove web link](#permanently-remove-web-link) ## Restore web link Restores a web link that has been moved to the trash. An optional new parent ID can be provided to restore the web link to in case the original folder has been deleted. This operation is performed by calling function `RestoreWeblinkFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links-id/). ``` await client.TrashedWebLinks.RestoreWeblinkFromTrashAsync(webLinkId: weblink.Id); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" requestBody `RestoreWeblinkFromTrashRequestBody` - Request body of restoreWeblinkFromTrash method queryParams `RestoreWeblinkFromTrashQueryParams` - Query parameters of restoreWeblinkFromTrash method headers `RestoreWeblinkFromTrashHeaders` - Headers of restoreWeblinkFromTrash method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TrashWebLinkRestored`. Returns a web link object when it has been restored. ## Get trashed web link Retrieves a web link that has been moved to the trash. This operation is performed by calling function `GetTrashedWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id-trash/). ``` await client.TrashedWebLinks.GetTrashedWebLinkByIdAsync(webLinkId: weblink.Id); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" queryParams `GetTrashedWebLinkByIdQueryParams` - Query parameters of getTrashedWebLinkById method headers `GetTrashedWebLinkByIdHeaders` - Headers of getTrashedWebLinkById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `TrashWebLink`. Returns the web link that was trashed, including information about when the it was moved to the trash. ## Permanently remove web link Permanently deletes a web link that is in the trash. This action cannot be undone. This operation is performed by calling function `DeleteTrashedWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id-trash/). ``` await client.TrashedWebLinks.DeleteTrashedWebLinkByIdAsync(webLinkId: weblink.Id); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" headers `DeleteTrashedWebLinkByIdHeaders` - Headers of deleteTrashedWebLinkById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Returns an empty response when the web link was permanently deleted. --- ## Untitled *Type: page* IUploadsManager Upload file version Preflight check before upload Upload file Upload a file with a preflight check Upload file version… # IUploadsManager - [Upload file version](#upload-file-version) - [Preflight check before upload](#preflight-check-before-upload) - [Upload file](#upload-file) - [Upload a file with a preflight check](#upload-a-file-with-a-preflight-check) ## Upload file version Update a file's content. For file sizes over 50MB we recommend using the Chunk Upload APIs. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. This operation is performed by calling function `UploadFileVersion`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-content/). ``` await client.Uploads.UploadFileVersionAsync(fileId: uploadedFile.Id, requestBody: new UploadFileVersionRequestBody(attributes: new UploadFileVersionRequestBodyAttributesField(name: newFileVersionName), file: newFileContentStream)); ``` ### Arguments fileId `string` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UploadFileVersionRequestBody` - Request body of uploadFileVersion method queryParams `UploadFileVersionQueryParams` - Query parameters of uploadFileVersion method headers `UploadFileVersionHeaders` - Headers of uploadFileVersion method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Files`. Returns the new file object in a list. ## Preflight check before upload Performs a check to verify that a file will be accepted by Box before you upload the entire file. This operation is performed by calling function `PreflightFileUploadCheck`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-files-content/). ``` await client.Uploads.PreflightFileUploadCheckAsync(requestBody: new PreflightFileUploadCheckRequestBody() { Name = newFileName, Size = 1024 * 1024, Parent = new PreflightFileUploadCheckRequestBodyParentField() { Id = "0" } }); ``` ### Arguments requestBody `PreflightFileUploadCheckRequestBody` - Request body of preflightFileUploadCheck method headers `PreflightFileUploadCheckHeaders` - Headers of preflightFileUploadCheck method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UploadUrl`. If the check passed, the response will include a session URL that can be used to upload the file to. ## Upload file Uploads a small file to Box. For file sizes over 50MB we recommend using the Chunk Upload APIs. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. This operation is performed by calling function `UploadFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-content/). ``` await client.Uploads.UploadFileAsync(requestBody: new UploadFileRequestBody(attributes: new UploadFileRequestBodyAttributesField(name: newFileName, parent: new UploadFileRequestBodyAttributesParentField(id: "0")), file: fileContentStream)); ``` ### Arguments requestBody `UploadFileRequestBody` - Request body of uploadFile method queryParams `UploadFileQueryParams` - Query parameters of uploadFile method headers `UploadFileHeaders` - Headers of uploadFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Files`. Returns the new file object in a list. ## Upload a file with a preflight check Upload a file with a preflight check This operation is performed by calling function `UploadWithPreflightCheck`. ``` await client.Uploads.UploadWithPreflightCheckAsync(requestBody: new UploadWithPreflightCheckRequestBody(attributes: new UploadWithPreflightCheckRequestBodyAttributesField(name: newFileName, size: -1, parent: new UploadWithPreflightCheckRequestBodyAttributesParentField(id: "0")), file: fileContentStream)); ``` ### Arguments requestBody `UploadWithPreflightCheckRequestBody` queryParams `UploadWithPreflightCheckQueryParams` - Query parameters of uploadFile method headers `UploadWithPreflightCheckHeaders` - Headers of uploadFile method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Files`. --- ## Untitled *Type: page* IUserCollaborationsManager Get collaboration Update collaboration Remove collaboration Create collaboration Get collaboration Retrieves a… # IUserCollaborationsManager - [Get collaboration](#get-collaboration) - [Update collaboration](#update-collaboration) - [Remove collaboration](#remove-collaboration) - [Create collaboration](#create-collaboration) ## Get collaboration Retrieves a single collaboration. This operation is performed by calling function `GetCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations-id/). ``` await client.UserCollaborations.GetCollaborationByIdAsync(collaborationId: collaborationId); ``` ### Arguments collaborationId `string` - The ID of the collaboration. Example: "1234" queryParams `GetCollaborationByIdQueryParams` - Query parameters of getCollaborationById method headers `GetCollaborationByIdHeaders` - Headers of getCollaborationById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Collaboration`. Returns a collaboration object. ## Update collaboration Updates a collaboration. Can be used to change the owner of an item, or to accept collaboration invites. This operation is performed by calling function `UpdateCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-collaborations-id/). ``` await client.UserCollaborations.UpdateCollaborationByIdAsync(collaborationId: collaborationId, requestBody: new UpdateCollaborationByIdRequestBody(role: UpdateCollaborationByIdRequestBodyRoleField.Viewer)); ``` ### Arguments collaborationId `string` - The ID of the collaboration. Example: "1234" requestBody `UpdateCollaborationByIdRequestBody` - Request body of updateCollaborationById method headers `UpdateCollaborationByIdHeaders` - Headers of updateCollaborationById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Collaboration?`. Returns an updated collaboration object unless the owner has changed.If the role is changed to `owner`, the collaboration is deleted and a new collaboration is created. The previous `owner` of the old collaboration will be a `co-owner` on the new collaboration. ## Remove collaboration Deletes a single collaboration. This operation is performed by calling function `DeleteCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaborations-id/). ``` await client.UserCollaborations.DeleteCollaborationByIdAsync(collaborationId: collaborationId); ``` ### Arguments collaborationId `string` - The ID of the collaboration. Example: "1234" headers `DeleteCollaborationByIdHeaders` - Headers of deleteCollaborationById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. A blank response is returned if the collaboration was successfully deleted. ## Create collaboration Adds a collaboration for a single user or a single group to a file or folder. Collaborations can be created using email address, user IDs, or a group IDs. If a collaboration is being created with a group, access to this endpoint is dependent on the group's ability to be invited. If collaboration is in `pending` status, the following fields are redacted: - `login` and `name` are hidden if a collaboration was created using `user_id`, - `name` is hidden if a collaboration was created using `login`. This operation is performed by calling function `CreateCollaboration`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaborations/). ``` await client.UserCollaborations.CreateCollaborationAsync(requestBody: new CreateCollaborationRequestBody(item: new CreateCollaborationRequestBodyItemField() { Type = CreateCollaborationRequestBodyItemTypeField.Folder, Id = folder.Id }, accessibleBy: new CreateCollaborationRequestBodyAccessibleByField(type: CreateCollaborationRequestBodyAccessibleByTypeField.User) { Id = user.Id }, role: CreateCollaborationRequestBodyRoleField.Editor)); ``` ### Arguments requestBody `CreateCollaborationRequestBody` - Request body of createCollaboration method queryParams `CreateCollaborationQueryParams` - Query parameters of createCollaboration method headers `CreateCollaborationHeaders` - Headers of createCollaboration method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Collaboration`. Returns a new collaboration object. --- ## Untitled *Type: page* IUsersManager List enterprise users Create user Get current user Get user Update user Delete user List enterprise users Returns a list of… # IUsersManager - [List enterprise users](#list-enterprise-users) - [Create user](#create-user) - [Get current user](#get-current-user) - [Get user](#get-user) - [Update user](#update-user) - [Delete user](#delete-user) ## List enterprise users Returns a list of all users for the Enterprise along with their `user_id`, `public_name`, and `login`. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This operation is performed by calling function `GetUsers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users/). ``` await client.Users.GetUsersAsync(); ``` ### Arguments queryParams `GetUsersQueryParams` - Query parameters of getUsers method headers `GetUsersHeaders` - Headers of getUsers method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Users`. Returns all of the users in the enterprise. ## Create user Creates a new managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `CreateUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users/). ``` await client.Users.CreateUserAsync(requestBody: new CreateUserRequestBody(name: userName) { Login = userLogin, IsPlatformAccessOnly = true }); ``` ### Arguments requestBody `CreateUserRequestBody` - Request body of createUser method queryParams `CreateUserQueryParams` - Query parameters of createUser method headers `CreateUserHeaders` - Headers of createUser method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UserFull`. Returns a user object for the newly created user. ## Get current user Retrieves information about the user who is currently authenticated. In the case of a client-side authenticated OAuth 2.0 application this will be the user who authorized the app. In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default. Use the `As-User` header to change who this API call is made on behalf of. This operation is performed by calling function `GetUserMe`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-me/). ``` await client.Users.GetUserMeAsync(); ``` ### Arguments queryParams `GetUserMeQueryParams` - Query parameters of getUserMe method headers `GetUserMeHeaders` - Headers of getUserMe method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UserFull`. Returns a single user object. ## Get user Retrieves information about a user in the enterprise. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This endpoint also returns a limited set of information for external users who are collaborated on content owned by the enterprise for authenticated users with the right scopes. In this case, disallowed fields will return null instead. This operation is performed by calling function `GetUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id/). ``` await client.Users.GetUserByIdAsync(userId: user.Id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" queryParams `GetUserByIdQueryParams` - Query parameters of getUserById method headers `GetUserByIdHeaders` - Headers of getUserById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UserFull`. Returns a single user object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields using the [fields](#get-users-id--request--fields) parameter. ## Update user Updates a managed or app user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `UpdateUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id/). ``` await client.Users.UpdateUserByIdAsync(userId: user.Id, requestBody: new UpdateUserByIdRequestBody() { Name = updatedUserName }); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" requestBody `UpdateUserByIdRequestBody` - Request body of updateUserById method queryParams `UpdateUserByIdQueryParams` - Query parameters of updateUserById method headers `UpdateUserByIdHeaders` - Headers of updateUserById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `UserFull`. Returns the updated user object. ## Delete user Deletes a user. By default this will fail if the user still owns any content. Move their owned content first before proceeding, or use the `force` field to delete the user and their files. This operation is performed by calling function `DeleteUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id/). ``` await client.Users.DeleteUserByIdAsync(userId: user.Id); ``` ### Arguments userId `string` - The ID of the user. Example: "12345" queryParams `DeleteUserByIdQueryParams` - Query parameters of deleteUserById method headers `DeleteUserByIdHeaders` - Headers of deleteUserById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Removes the user and returns an empty response. --- ## Untitled *Type: page* IWebLinksManager Create web link Get web link Update web link Remove web link Create web link Creates a web link object within a folder… # IWebLinksManager - [Create web link](#create-web-link) - [Get web link](#get-web-link) - [Update web link](#update-web-link) - [Remove web link](#remove-web-link) ## Create web link Creates a web link object within a folder. This operation is performed by calling function `CreateWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links/). ``` await client.WebLinks.CreateWebLinkAsync(requestBody: new CreateWebLinkRequestBody(url: "https://www.box.com", parent: new CreateWebLinkRequestBodyParentField(id: parent.Id)) { Name = Utils.GetUUID(), Description = "Weblink description" }); ``` ### Arguments requestBody `CreateWebLinkRequestBody` - Request body of createWebLink method headers `CreateWebLinkHeaders` - Headers of createWebLink method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `WebLink`. Returns the newly created web link object. ## Get web link Retrieve information about a web link. This operation is performed by calling function `GetWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id/). ``` await client.WebLinks.GetWebLinkByIdAsync(webLinkId: weblink.Id); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" headers `GetWebLinkByIdHeaders` - Headers of getWebLinkById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `WebLink`. Returns the web link object. ## Update web link Updates a web link object. This operation is performed by calling function `UpdateWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id/). ``` await client.WebLinks.UpdateWebLinkByIdAsync(webLinkId: weblink.Id, requestBody: new UpdateWebLinkByIdRequestBody() { Name = updatedName, SharedLink = new UpdateWebLinkByIdRequestBodySharedLinkField() { Access = UpdateWebLinkByIdRequestBodySharedLinkAccessField.Open, Password = password } }); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" requestBody `UpdateWebLinkByIdRequestBody` - Request body of updateWebLinkById method headers `UpdateWebLinkByIdHeaders` - Headers of updateWebLinkById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `WebLink`. Returns the updated web link object. ## Remove web link Deletes a web link. This operation is performed by calling function `DeleteWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id/). ``` await client.WebLinks.DeleteWebLinkByIdAsync(webLinkId: webLinkId); ``` ### Arguments webLinkId `string` - The ID of the web link. Example: "12345" headers `DeleteWebLinkByIdHeaders` - Headers of deleteWebLinkById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. An empty response will be returned when the web link was successfully deleted. --- ## Untitled *Type: page* IWebhooksManager List all webhooks Create webhook Get webhook Update webhook Remove webhook List all webhooks Returns all defined webhooks… # IWebhooksManager - [List all webhooks](#list-all-webhooks) - [Create webhook](#create-webhook) - [Get webhook](#get-webhook) - [Update webhook](#update-webhook) - [Remove webhook](#remove-webhook) ## List all webhooks Returns all defined webhooks for the requesting application. This API only returns webhooks that are applied to files or folders that are owned by the authenticated user. This means that an admin can not see webhooks created by a service account unless the admin has access to those folders, and vice versa. This operation is performed by calling function `GetWebhooks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks/). ``` await client.Webhooks.GetWebhooksAsync(); ``` ### Arguments queryParams `GetWebhooksQueryParams` - Query parameters of getWebhooks method headers `GetWebhooksHeaders` - Headers of getWebhooks method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Webhooks`. Returns a list of webhooks. ## Create webhook Creates a webhook. This operation is performed by calling function `CreateWebhook`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-webhooks/). ``` await client.Webhooks.CreateWebhookAsync(requestBody: new CreateWebhookRequestBody(target: new CreateWebhookRequestBodyTargetField() { Id = folder.Id, Type = CreateWebhookRequestBodyTargetTypeField.Folder }, address: "https://example.com/new-webhook", triggers: Array.AsReadOnly(new [] {new StringEnum<CreateWebhookRequestBodyTriggersField>(CreateWebhookRequestBodyTriggersField.FileUploaded)}))); ``` ### Arguments requestBody `CreateWebhookRequestBody` - Request body of createWebhook method headers `CreateWebhookHeaders` - Headers of createWebhook method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Get webhook Retrieves a specific webhook. This operation is performed by calling function `GetWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks-id/). ``` await client.Webhooks.GetWebhookByIdAsync(webhookId: NullableUtils.Unwrap(webhook.Id)); ``` ### Arguments webhookId `string` - The ID of the webhook. Example: "3321123" headers `GetWebhookByIdHeaders` - Headers of getWebhookById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Webhook`. Returns a webhook object. ## Update webhook Updates a webhook. This operation is performed by calling function `UpdateWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-webhooks-id/). ``` await client.Webhooks.UpdateWebhookByIdAsync(webhookId: NullableUtils.Unwrap(webhook.Id), requestBody: new UpdateWebhookByIdRequestBody() { Address = "https://example.com/updated-webhook" }); ``` ### Arguments webhookId `string` - The ID of the webhook. Example: "3321123" requestBody `UpdateWebhookByIdRequestBody` - Request body of updateWebhookById method headers `UpdateWebhookByIdHeaders` - Headers of updateWebhookById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Remove webhook Deletes a webhook. This operation is performed by calling function `DeleteWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-webhooks-id/). ``` await client.Webhooks.DeleteWebhookByIdAsync(webhookId: NullableUtils.Unwrap(webhook.Id)); ``` ### Arguments webhookId `string` - The ID of the webhook. Example: "3321123" headers `DeleteWebhookByIdHeaders` - Headers of deleteWebhookById method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. An empty response will be returned when the webhook was successfully deleted. --- ## Untitled *Type: page* IWorkflowsManager List workflows Starts workflow based on request body List workflows Returns list of workflows that act on a given folder… # IWorkflowsManager - [List workflows](#list-workflows) - [Starts workflow based on request body](#starts-workflow-based-on-request-body) ## List workflows Returns list of workflows that act on a given `folder ID`, and have a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in to use this endpoint. This operation is performed by calling function `GetWorkflows`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-workflows/). ``` await adminClient.Workflows.GetWorkflowsAsync(queryParams: new GetWorkflowsQueryParams(folderId: workflowFolderId)); ``` ### Arguments queryParams `GetWorkflowsQueryParams` - Query parameters of getWorkflows method headers `GetWorkflowsHeaders` - Headers of getWorkflows method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `Workflows`. Returns the workflow. ## Starts workflow based on request body Initiates a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console. This operation is performed by calling function `StartWorkflow`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-workflows-id-start/). ``` await adminClient.Workflows.StartWorkflowAsync(workflowId: NullableUtils.Unwrap(workflowToRun.Id), requestBody: new StartWorkflowRequestBody(flow: new StartWorkflowRequestBodyFlowField() { Type = "flow", Id = NullableUtils.Unwrap(NullableUtils.Unwrap(workflowToRun.Flows)[0].Id) }, files: Array.AsReadOnly(new [] {new StartWorkflowRequestBodyFilesField() { Type = StartWorkflowRequestBodyFilesTypeField.File, Id = workflowFileId }}), folder: new StartWorkflowRequestBodyFolderField() { Type = StartWorkflowRequestBodyFolderTypeField.Folder, Id = workflowFolderId }) { Type = StartWorkflowRequestBodyTypeField.WorkflowParameters }); ``` ### Arguments workflowId `string` - The ID of the workflow. Example: "12345" requestBody `StartWorkflowRequestBody` - Request body of startWorkflow method headers `StartWorkflowHeaders` - Headers of startWorkflow method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `null`. Starts the workflow. --- ## Untitled *Type: page* IZipDownloadsManager Create zip download Download zip archive Get zip download status Download ZIP Create zip download Creates a request to… # IZipDownloadsManager - [Create zip download](#create-zip-download) - [Download zip archive](#download-zip-archive) - [Get zip download status](#get-zip-download-status) - [Download ZIP](#download-zip) ## Create zip download Creates a request to download multiple files and folders as a single `zip` archive file. This API does not return the archive but instead performs all the checks to ensure that the user has access to all the items, and then returns a `download_url` and a `status_url` that can be used to download the archive. The limit for an archive is either the Account's upload limit or 10,000 files, whichever is met first. **Note**: Downloading a large file can be affected by various factors such as distance, network latency, bandwidth, and congestion, as well as packet loss ratio and current server load. For these reasons we recommend that a maximum ZIP archive total size does not exceed 25GB. This operation is performed by calling function `CreateZipDownload`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-zip-downloads/). ``` await client.ZipDownloads.CreateZipDownloadAsync(requestBody: new ZipDownloadRequest(items: Array.AsReadOnly(new [] {new ZipDownloadRequestItemsField(id: file1.Id, type: ZipDownloadRequestItemsTypeField.File),new ZipDownloadRequestItemsField(id: file2.Id, type: ZipDownloadRequestItemsTypeField.File),new ZipDownloadRequestItemsField(id: folder1.Id, type: ZipDownloadRequestItemsTypeField.Folder)})) { DownloadFileName = "zip" }); ``` ### Arguments requestBody `ZipDownloadRequest` - Request body of createZipDownload method headers `CreateZipDownloadHeaders` - Headers of createZipDownload method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ZipDownload`. If the `zip` archive is ready to be downloaded, the API will return a response that will include a `download_url`, a `status_url`, as well as any conflicts that might have occurred when creating the request. ## Download zip archive Returns the contents of a `zip` archive in binary format. This URL does not require any form of authentication and could be used in a user's browser to download the archive to a user's device. By default, this URL is only valid for a few seconds from the creation of the request for this archive. Once a download has started it can not be stopped and resumed, instead a new request for a zip archive would need to be created. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `download_url` field in the response to this endpoint. This operation is performed by calling function `GetZipDownloadContent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-content/). ``` await client.ZipDownloads.GetZipDownloadContentAsync(downloadUrl: NullableUtils.Unwrap(zipDownload.DownloadUrl)); ``` ### Arguments downloadUrl `string` - The URL that can be used to download created `zip` archive. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content` headers `GetZipDownloadContentHeaders` - Headers of getZipDownloadContent method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `System.IO.Stream`. Returns the content of the items requested for this download, formatted as a stream of files and folders in a `zip` archive. ## Get zip download status Returns the download status of a `zip` archive, allowing an application to inspect the progress of the download as well as the number of items that might have been skipped. This endpoint can only be accessed once the download has started. Subsequently this endpoint is valid for 12 hours from the start of the download. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `status_url` field in the response to this endpoint. This operation is performed by calling function `GetZipDownloadStatus`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-status/). ``` await client.ZipDownloads.GetZipDownloadStatusAsync(statusUrl: NullableUtils.Unwrap(zipDownload.StatusUrl)); ``` ### Arguments statusUrl `string` - The URL that can be used to get the status of the `zip` archive being downloaded. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status` headers `GetZipDownloadStatusHeaders` - Headers of getZipDownloadStatus method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `ZipDownloadStatus`. Returns the status of the `zip` archive that is being downloaded. ## Download ZIP Creates a zip and downloads its content This operation is performed by calling function `DownloadZip`. ``` await client.ZipDownloads.DownloadZipAsync(requestBody: new ZipDownloadRequest(items: Array.AsReadOnly(new [] {new ZipDownloadRequestItemsField(id: file1.Id, type: ZipDownloadRequestItemsTypeField.File),new ZipDownloadRequestItemsField(id: file2.Id, type: ZipDownloadRequestItemsTypeField.File),new ZipDownloadRequestItemsField(id: folder1.Id, type: ZipDownloadRequestItemsTypeField.Folder)})) { DownloadFileName = "zip" }); ``` ### Arguments requestBody `ZipDownloadRequest` - Zip download request body headers `DownloadZipHeaders` - Headers of zip download method cancellationToken `System.Threading.CancellationToken?` - Token used for request cancellation. ### Returns This function returns a value of type `System.IO.Stream`. --- ## Untitled *Type: page* Handling null values in Box Dotnet SDK Gen While using Box Dotnet SDK it's important to understand how null values behave. This document… # Handling null values in Box Dotnet SDK Gen While using Box Dotnet SDK it's important to understand how null values behave. This document provides a general overview of null value behaviour in Box Dotnet SDK to help developers manage data consistently and predictably. ## Understanding null behaviour The Box Dotnet SDK follows a consistent pattern when handling null values in update operations. This behaviour applies to most endpoints that modify resources such as users, files, folders and metadata. The updating field behaves differently depending on weather you omit it, set it to null, or provide a value: - Omitting the field: The field won't be included in request and the value will remain unchanged - Setting it to null: Setting a field to null, will cause sending HTTP request with field value set to null, what will result in removing its current value or disassociates it from the resource. - Providing a value: Providing a non-null value assigns or updates the field to that value. ## Example Usage The client.Files.UpdateFileByIdAsync() method demonstrates null handling when modifying the lock field while updating the file: ``` public async Task CreateUpdateFileAsync(BoxClient client) { var fileId = '12345'; var fileWithLockRequestBody = new UpdateFileByIdRequestBody() { Lock = new UpdateFileByIdRequestBodyLockField() { Access = UpdateFileByIdRequestBodyLockAccessField.Lock } }; var fileWithLockQueryParams = new UpdateFileByIdQueryParams() { Fields = new List<string>() { { "lock" } } }; // locking the file var fileWithLock = await client.Files.UpdateFileByIdAsync(fileId, fileWithLockRequestBody, fileWithLockQueryParams); Console.WriteLine(fileWithLock.Lock?.Id); var fileWithoutLockRequestBody = new UpdateFileByIdRequestBody() { Lock = null }; var fileWithoutLockQueryParams = new UpdateFileByIdQueryParams() { Fields = new List<string>() { { "lock" } } }; // unlocking the file using lock value as null var fileWithoutLock = await client.Files.UpdateFileByIdAsync(fileId, fileWithoutLockRequestBody, fileWithoutLockQueryParams); Console.WriteLine(fileWithoutLock.Lock?.Id); } ``` ## Summary To summarize, if you omit the field, the field remains unchanged. If you set it to null, it clears/removes the value. If you provide a value to that field, the field gets updated to that specified value. --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 1.11.0 (2025-0… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## 1.11.0 (2025-08-05) ### Bug Fixes - Fix downscope token to use `retrieveToken` method for token retrieval (box/box-codegen[#731](https://github.com/box/box-dotnet-sdk-gen/issues/731)) ([#492](https://github.com/box/box-dotnet-sdk-gen/issues/492)) ([292360e](https://github.com/box/box-dotnet-sdk-gen/commit/292360efe86797e42dbfb388a5bd2f5b41efa0c1)) - Specify events `next_stream_position` property type as `long` (box/box-openapi[#535](https://github.com/box/box-dotnet-sdk-gen/issues/535)) ([#536](https://github.com/box/box-dotnet-sdk-gen/issues/536)) ([da265bd](https://github.com/box/box-dotnet-sdk-gen/commit/da265bd5c40defc4b2036811aefad59447faca09)) ### New Features and Enhancements - Add `ReadOnlyCollection` implicit operator for Unions (box/box-codegen[#633](https://github.com/box/box-dotnet-sdk-gen/issues/633)) ([#483](https://github.com/box/box-dotnet-sdk-gen/issues/483)) ([a1fc2c5](https://github.com/box/box-dotnet-sdk-gen/commit/a1fc2c584021c151fc9d1815877ffe73c972f711)) - Add AI spreadsheet processor (box/box-openapi[#533](https://github.com/box/box-dotnet-sdk-gen/issues/533)) ([#519](https://github.com/box/box-dotnet-sdk-gen/issues/519)) ([c344023](https://github.com/box/box-dotnet-sdk-gen/commit/c34402355243145a1cab7da78c6c2facde39fb36)) - Add Archive Public API (box/box-openapi[#540](https://github.com/box/box-dotnet-sdk-gen/issues/540)) ([#543](https://github.com/box/box-dotnet-sdk-gen/issues/543)) ([be0bb9d](https://github.com/box/box-dotnet-sdk-gen/commit/be0bb9d3e58f97bc87f749d08d828c990c71789b)) - Add new Hubs APIs and Hubs items API (box/box-openapi[#538](https://github.com/box/box-dotnet-sdk-gen/issues/538)) ([#537](https://github.com/box/box-dotnet-sdk-gen/issues/537)) ([f2584cd](https://github.com/box/box-dotnet-sdk-gen/commit/f2584cd9be40b67eaa3a500411b367543a26f830)) - Add new schema for `Metadata Error` (box/box-openapi[#539](https://github.com/box/box-dotnet-sdk-gen/issues/539)) ([#538](https://github.com/box/box-dotnet-sdk-gen/issues/538)) ([425b4ad](https://github.com/box/box-dotnet-sdk-gen/commit/425b4add7975d49584c8ed18a791caf72559203c)) - add Shield Lists APIs (box/box-openapi[#528](https://github.com/box/box-dotnet-sdk-gen/issues/528)) ([#496](https://github.com/box/box-dotnet-sdk-gen/issues/496)) ([8b81c87](https://github.com/box/box-dotnet-sdk-gen/commit/8b81c879c8b8bb5c020ecb573e527e2a5d9f1701)) - Allow injecting private key decryption mechanism for JWT (box/box-codegen[#754](https://github.com/box/box-dotnet-sdk-gen/issues/754)) ([#528](https://github.com/box/box-dotnet-sdk-gen/issues/528)) ([865c729](https://github.com/box/box-dotnet-sdk-gen/commit/865c729395556a3c4a8bb1f1418c3932d268bdc4)) - Make `OneOf` classes public (box/box-codegen[#773](https://github.com/box/box-dotnet-sdk-gen/issues/773)) ([#551](https://github.com/box/box-dotnet-sdk-gen/issues/551)) ([f7dcc32](https://github.com/box/box-dotnet-sdk-gen/commit/f7dcc3262b289da55ebc6210c5656cc98e3b14b4)) - Support Hubs beta endpoints (box/box-openapi[#531](https://github.com/box/box-dotnet-sdk-gen/issues/531)) ([#511](https://github.com/box/box-dotnet-sdk-gen/issues/511)) ([59c43b8](https://github.com/box/box-dotnet-sdk-gen/commit/59c43b868e46edd26be0be13a5e1772a4d731128)) - Support new tools in AI Studio (box/box-openapi[#534](https://github.com/box/box-dotnet-sdk-gen/issues/534)) ([#520](https://github.com/box/box-dotnet-sdk-gen/issues/520)) ([0b47597](https://github.com/box/box-dotnet-sdk-gen/commit/0b47597f259884a2a5f567608e9e07997e3c6dc9)) - Update legal holds and AI models (box/box-openapi[#526](https://github.com/box/box-dotnet-sdk-gen/issues/526)) ([#494](https://github.com/box/box-dotnet-sdk-gen/issues/494)) ([6310e56](https://github.com/box/box-dotnet-sdk-gen/commit/6310e560df6d9520598295139f55ec8a0a4d69d9)) ## 1.10.0 (2025-05-13) ### New Features and Enhancements - Add `UploadWithPreflightCheck` convenient method (box/box-codegen[#705](https://github.com/box/box-dotnet-sdk-gen/issues/705)) ([#469](https://github.com/box/box-dotnet-sdk-gen/issues/469)) ([8dff7bb](https://github.com/box/box-dotnet-sdk-gen/commit/8dff7bb859cd034d4e43b81c7c11b9a3fdb396e8)) - Add AI agents warnings; allow for more types of metadata value (box/box-openapi[#520](https://github.com/box/box-dotnet-sdk-gen/issues/520)) ([#474](https://github.com/box/box-dotnet-sdk-gen/issues/474)) ([a53cff5](https://github.com/box/box-dotnet-sdk-gen/commit/a53cff54395db91bad179d3c5bbae9800c1b79dd)) - Add security settings properties on sign template schema (box/box-openapi[#518](https://github.com/box/box-dotnet-sdk-gen/issues/518)) ([#462](https://github.com/box/box-dotnet-sdk-gen/issues/462)) ([7fddaea](https://github.com/box/box-dotnet-sdk-gen/commit/7fddaeab425a859dc1aa5dc3420891047d27efdf)) - Add support of IBM models to AI API (box/box-openapi[#522](https://github.com/box/box-dotnet-sdk-gen/issues/522)) ([#475](https://github.com/box/box-dotnet-sdk-gen/issues/475)) ([a187301](https://github.com/box/box-dotnet-sdk-gen/commit/a187301543d6741c77799b66fde0f12d4fca710d)) - Support sensitive data sanitization in errors (box/box-codegen[#695](https://github.com/box/box-dotnet-sdk-gen/issues/695)) ([#453](https://github.com/box/box-dotnet-sdk-gen/issues/453)) ([5ee0c93](https://github.com/box/box-dotnet-sdk-gen/commit/5ee0c932254a0cd1cc7bc814c29fe5f9e2151462)) ## 1.9.0 (2025-03-18) ### Bug Fixes - Add `verification_phone_number` property to create sign request (box/box-openapi[#515](https://github.com/box/box-dotnet-sdk-gen/issues/515)) ([#427](https://github.com/box/box-dotnet-sdk-gen/issues/427)) ([d90faea](https://github.com/box/box-dotnet-sdk-gen/commit/d90faea77650a37ce794a93c51bd9a8eb91f619c)) - Use `targetFramework` when single .Net version is supported (box/box-codegen[#684](https://github.com/box/box-dotnet-sdk-gen/issues/684)) ([#438](https://github.com/box/box-dotnet-sdk-gen/issues/438)) ([4e64174](https://github.com/box/box-dotnet-sdk-gen/commit/4e64174c21c6f1dd2cef75f1f29ebe2ace92d852)) ### New Features and Enhancements - Add find app item for shared link endpoint (box/box-openapi[#514](https://github.com/box/box-dotnet-sdk-gen/issues/514)) ([#426](https://github.com/box/box-dotnet-sdk-gen/issues/426)) ([4dc5dc1](https://github.com/box/box-dotnet-sdk-gen/commit/4dc5dc14e3c204c537180df166d07735ae1c4e40)) - Add Integration Mappings Teams API (box/box-openapi[#517](https://github.com/box/box-dotnet-sdk-gen/issues/517)) ([#429](https://github.com/box/box-dotnet-sdk-gen/issues/429)) ([92063c4](https://github.com/box/box-dotnet-sdk-gen/commit/92063c435d7cb38a7eeca2e71f42e32b995a659a)) - Expose token storage for authentication classes (box/box-codegen[#682](https://github.com/box/box-dotnet-sdk-gen/issues/682)) ([#435](https://github.com/box/box-dotnet-sdk-gen/issues/435)) ([413058e](https://github.com/box/box-dotnet-sdk-gen/commit/413058e78cb69c89be6a819c0e63f9457bd7f2f5)) ## 1.8.0 (2025-02-20) ### Bug Fixes - Do not retry HTTP request when `TaskCanceledException` is thrown (box/box-codegen[#665](https://github.com/box/box-dotnet-sdk-gen/issues/665)) ([#406](https://github.com/box/box-dotnet-sdk-gen/issues/406)) ([1af0a6a](https://github.com/box/box-dotnet-sdk-gen/commit/1af0a6aaf5f1e80f092ce506abe1cc01bf110bb8)) ### New Features and Enhancements - Support AI Studio API (box/box-codegen[#626](https://github.com/box/box-dotnet-sdk-gen/issues/626)) ([#409](https://github.com/box/box-dotnet-sdk-gen/issues/409)) ([9661450](https://github.com/box/box-dotnet-sdk-gen/commit/966145021d4a1dd450cd199cc9ed3e9457f5a141)) ## 1.7.0 (2025-02-06) ### Bug Fixes - Correct types of `paged` and `thumb` properties in File representation (box/box-openapi[#503](https://github.com/box/box-dotnet-sdk-gen/issues/503)) ([#383](https://github.com/box/box-dotnet-sdk-gen/issues/383)) ([d6995ad](https://github.com/box/box-dotnet-sdk-gen/commit/d6995ad8ffa4f2cceb8195ffbfb6606f934a671f)) - Prevent `Authentication` header from being passed during cross-origin redirects (box/box-codegen[#648](https://github.com/box/box-dotnet-sdk-gen/issues/648)) ([#382](https://github.com/box/box-dotnet-sdk-gen/issues/382)) ([a64d373](https://github.com/box/box-dotnet-sdk-gen/commit/a64d373a935cd2a8e6f72184b8dc129a973e9d45)) ### New Features and Enhancements - Add Box Sign shared requests (box/box-openapi[#504](https://github.com/box/box-dotnet-sdk-gen/issues/504)) ([#384](https://github.com/box/box-dotnet-sdk-gen/issues/384)) ([d563886](https://github.com/box/box-dotnet-sdk-gen/commit/d563886f2a2f48a20df13600f9c25ff95198a56f)) - feat: Add hubs support to /ai/ask. Replace type of `Items` property from `IReadOnlyList<AiItemBase>` to `IReadOnlyList<AiItemAsk>` in the `AiAsk` class (box/box-codegen[#656](https://github.com/box/box-dotnet-sdk-gen/issues/656)) ([#397](https://github.com/box/box-dotnet-sdk-gen/issues/397)) ([32b6d03](https://github.com/box/box-dotnet-sdk-gen/commit/32b6d03aba97c18a8901efe98fc60c74e10197ce)) - Update `/ai/extract_structured` response schema (box/box-codegen[#641](https://github.com/box/box-dotnet-sdk-gen/issues/641)) ([#391](https://github.com/box/box-dotnet-sdk-gen/issues/391)) ([5f79a03](https://github.com/box/box-dotnet-sdk-gen/commit/5f79a03453b9339a26eb130113d8f55748f0d912)) ## 1.6.0 (2025-01-21) ### Bug Fixes - Add missing token scope (box/box-openapi[#490](https://github.com/box/box-dotnet-sdk-gen/issues/490)) ([#353](https://github.com/box/box-dotnet-sdk-gen/issues/353)) ([d41e1c8](https://github.com/box/box-dotnet-sdk-gen/commit/d41e1c8c3195a08850f3217fe747e9751a979c76)) - Fix invalid variant config for Integration mapping Slack (box/box-openapi[#492](https://github.com/box/box-dotnet-sdk-gen/issues/492)) ([#356](https://github.com/box/box-dotnet-sdk-gen/issues/356)) ([8320fb7](https://github.com/box/box-dotnet-sdk-gen/commit/8320fb7da8449a8ae9965bd3496523a0f3bfe5af)) - order of fields in the `IntegrationMapping` schema (box/box-openapi[#497](https://github.com/box/box-dotnet-sdk-gen/issues/497)) ([#370](https://github.com/box/box-dotnet-sdk-gen/issues/370)) ([3361ad1](https://github.com/box/box-dotnet-sdk-gen/commit/3361ad1833670f9e99902b2206112592f7272ab8)) - unused parameter from `SignRequest` (box/box-openapi[#489](https://github.com/box/box-dotnet-sdk-gen/issues/489)) ([#343](https://github.com/box/box-dotnet-sdk-gen/issues/343)) ([5d88a51](https://github.com/box/box-dotnet-sdk-gen/commit/5d88a5176489f82057a93bd5dc119e4ae3afdcd7)) ### New Features and Enhancements - Add `aiAgent` info to `AiResponse` (box/box-openapi[#485](https://github.com/box/box-dotnet-sdk-gen/issues/485)) ([#336](https://github.com/box/box-dotnet-sdk-gen/issues/336)) ([cbf91fc](https://github.com/box/box-dotnet-sdk-gen/commit/cbf91fc23012588f0f4175a713d562738818218e)) - Add support for replacing the network client implementation (box/box-codegen[#629](https://github.com/box/box-dotnet-sdk-gen/issues/629)) ([#347](https://github.com/box/box-dotnet-sdk-gen/issues/347)) ([29d904e](https://github.com/box/box-dotnet-sdk-gen/commit/29d904e72fd9c4511183ba35454a82ff9c2d7358)) - Support Box Doc Gen API (box/box-codegen[#644](https://github.com/box/box-dotnet-sdk-gen/issues/644)) ([#378](https://github.com/box/box-dotnet-sdk-gen/issues/378)) ([5cd0fde](https://github.com/box/box-dotnet-sdk-gen/commit/5cd0fdefb6a976fb8904beb08752f3e7dbb7428b)) - Support getting file download URL and file thumbnail URL (box/box-codegen[#642](https://github.com/box/box-dotnet-sdk-gen/issues/642)) ([#374](https://github.com/box/box-dotnet-sdk-gen/issues/374)) ([76b1513](https://github.com/box/box-dotnet-sdk-gen/commit/76b151371f405940eef5ef34fb00809c8f1d8f35)) - Support optional `userId` parameter for updating files, folders and web links (box/box-openapi[#488](https://github.com/box/box-dotnet-sdk-gen/issues/488)) ([#340](https://github.com/box/box-dotnet-sdk-gen/issues/340)) ([fd1c597](https://github.com/box/box-dotnet-sdk-gen/commit/fd1c59739c5361ec4462d2597f504fa3cff5be17)) ## 1.5.0 (2024-12-04) ### Bug Fixes - Support status codes with no content (box/box-codegen[#604](https://github.com/box/box-dotnet-sdk-gen/issues/604)) ([#314](https://github.com/box/box-dotnet-sdk-gen/issues/314)) ([57747d5](https://github.com/box/box-dotnet-sdk-gen/commit/57747d50c48dd4c433dad342a5e2a20ac0b15952)) - update collaboration, metadata and collection resources (box/box-openapi[#483](https://github.com/box/box-dotnet-sdk-gen/issues/483)) ([#316](https://github.com/box/box-dotnet-sdk-gen/issues/316)) ([d331f8a](https://github.com/box/box-dotnet-sdk-gen/commit/d331f8a1f7110e5e00df170cedef85af682d58b4)) ### New Features and Enhancements - Add optional URL parameter to `FetchResponse` (box/box-codegen[#617](https://github.com/box/box-dotnet-sdk-gen/issues/617)) ([#331](https://github.com/box/box-dotnet-sdk-gen/issues/331)) ([61484ec](https://github.com/box/box-dotnet-sdk-gen/commit/61484ec9fbf96c0ae62116ec1ee0cbb50aae7493)) - Allow using default credentials for proxy (box/box-codegen[#623](https://github.com/box/box-dotnet-sdk-gen/issues/623)) ([#334](https://github.com/box/box-dotnet-sdk-gen/issues/334)) ([bc4636e](https://github.com/box/box-dotnet-sdk-gen/commit/bc4636e64859fd7d0b1449ec34b6144d0eb1a768)), closes [#333](https://github.com/box/box-dotnet-sdk-gen/issues/333) - Expose method for making custom HTTP requests (box/box-codegen[#622](https://github.com/box/box-dotnet-sdk-gen/issues/622)) ([#329](https://github.com/box/box-dotnet-sdk-gen/issues/329)) ([e689140](https://github.com/box/box-dotnet-sdk-gen/commit/e689140d6d3be772ff2370e7de5797707df7bdad)) - Support get collection by ID endpoint (box/box-codegen[#595](https://github.com/box/box-dotnet-sdk-gen/issues/595)) ([#304](https://github.com/box/box-dotnet-sdk-gen/issues/304)) ([9ebf59a](https://github.com/box/box-dotnet-sdk-gen/commit/9ebf59ae388aa9aec5d8a0a3551f13e544c7571d)) ## 1.4.0 (2024-10-31) ### Bug Fixes - Change `QueryParams` type in `MetadataQuery` from `Dictionary<string, string>` to `Dictionary<string, object>` (box/box-openapi[#479](https://github.com/box/box-codegen/issues/479)) ([#298](https://github.com/box/box-codegen/issues/298)) ([656b495](https://github.com/box/box-codegen/commit/656b495bea779879bb82b2cda0cca5a30a8ad8ca)) - Fix conversion to `RSAKey` (box/box-codegen[#591](https://github.com/box/box-codegen/issues/591)) ([#297](https://github.com/box/box-codegen/issues/297)) ([068b1f7](https://github.com/box/box-codegen/commit/068b1f7b3ea3c62647e03e0e17176bde049949db)) ### New Features and Enhancements - add AI LLM endpoint AWS `params`. Change the type from `AiLlmEndpointParamsGoogleOrAiLlmEndpointParamsOpenAi` to `AiLlmEndpointParamsAwsOrAiLlmEndpointParamsGoogleOrAiLlmEndpointParamsOpenAi` (box/box-openapi[#478](https://github.com/box/box-codegen/issues/478)) ([#291](https://github.com/box/box-codegen/issues/291)) ([dcb8a20](https://github.com/box/box-codegen/commit/dcb8a201577be08b644266c157db45cd6797c71c)) ### 1.3.1 (2024-10-24) ### Bug Fixes - properly serialize `StringEnum` list when inside query `params` ([#288](https://github.com/box/box-codegen/issues/288)) ([dac8392](https://github.com/box/box-codegen/commit/dac839280b43f4bd954d3966032ff4925150c061)) - update client error schema to support schema errors (box/box-openapi[#467](https://github.com/box/box-codegen/issues/467)) ([#281](https://github.com/box/box-codegen/issues/281)) ([bef2632](https://github.com/box/box-codegen/commit/bef2632af99f0477bd009bcb91248c678b4e1bab)) - update integration mapping response description (box/box-openapi[#463](https://github.com/box/box-codegen/issues/463)) ([#279](https://github.com/box/box-codegen/issues/279)) ([05e07b0](https://github.com/box/box-codegen/commit/05e07b025c234de4c4161e567c0919748d24f804)) ## 1.3.0 (2024-10-17) ### Bug Fixes - bump `system.text.json` to 8.0.5 (box/box-codegen[#578](https://github.com/box/box-codegen/issues/578)) ([#271](https://github.com/box/box-codegen/issues/271)) ([dad2f52](https://github.com/box/box-codegen/commit/dad2f521066e73c3dcdaec196cd6940401e31f3a)) ### New Features and Enhancements - support proxy (box/box-codegen[#577](https://github.com/box/box-codegen/issues/577)) ([#274](https://github.com/box/box-codegen/issues/274)) ([dea1937](https://github.com/box/box-codegen/commit/dea19373a7169365acb968a66c78c5937ef698e1)) ## 1.2.0 (2024-09-26) ### Bug Fixes - correctly send `datetime` when in `queryParams` (box/box-codegen[#560](https://github.com/box/box-codegen/issues/560)) ([#243](https://github.com/box/box-codegen/issues/243)) ([9657526](https://github.com/box/box-codegen/commit/9657526667753d77eacfd674cde60ab4030ae42d)) - Fix variants in metadata query results (box/box-openapi[#456](https://github.com/box/box-codegen/issues/456)) ([#249](https://github.com/box/box-codegen/issues/249)) ([37625ea](https://github.com/box/box-codegen/commit/37625eabe4f87d57a9f58920829c00cddd34bcb1)) ### New Features and Enhancements - add Hubs Beta (box/box-openapi[#453](https://github.com/box/box-codegen/issues/453)) ([#241](https://github.com/box/box-codegen/issues/241)) ([c28f660](https://github.com/box/box-codegen/commit/c28f6605c94e250bbab853ef610c46c1d3c9ef95)) - include raw `json` in types (box/box-codegen[#567](https://github.com/box/box-codegen/issues/567)) ([#258](https://github.com/box/box-codegen/issues/258)) ([a1e7bc5](https://github.com/box/box-codegen/commit/a1e7bc55da0dec8bfd1159a1c158154177581019)) - Support `ai/extract` and `ai/extract_structured` endpoints (box/box-codegen[#564](https://github.com/box/box-codegen/issues/564)) ([#253](https://github.com/box/box-codegen/issues/253)) ([a17d8f8](https://github.com/box/box-codegen/commit/a17d8f8dbce8ac7f42b9e23c8c216e992a64d762)) ## 1.1.0 (2024-08-23) ### Bug Fixes - Add missing `item_upload` scope ([#201](https://github.com/box/box-codegen/issues/201)) ([483b055](https://github.com/box/box-codegen/commit/483b05586f8e45771e101d286fddebc564ff89bd)) - Add missing fields to Sign Template Signer and fix AI schema (box/box-openapi[#451](https://github.com/box/box-codegen/issues/451)) ([#229](https://github.com/box/box-codegen/issues/229)) ([121f733](https://github.com/box/box-codegen/commit/121f733f52e945927125f4941206b1553202914d)) - Fix `IntegrationMapping` schemas (box/box-codegen[#551](https://github.com/box/box-codegen/issues/551)) ([#226](https://github.com/box/box-codegen/issues/226)) ([3eca154](https://github.com/box/box-codegen/commit/3eca15434b65bc0bb2421d36ec50691e7fe40e3b)) - Improve handling of network exceptions, handle big file upload (box/box-openapi[#444](https://github.com/box/box-codegen/issues/444)) ([#222](https://github.com/box/box-codegen/issues/222)) ([75ccd07](https://github.com/box/box-codegen/commit/75ccd078e29015b865462ea1aaf0420d5e63d9cd)) ### New Features and Enhancements - add new parameters to Box AI methods and introduce `AiResponseFull` variant (box/box-openapi[#446](https://github.com/box/box-codegen/issues/446)) ([#224](https://github.com/box/box-codegen/issues/224)) ([6d205c4](https://github.com/box/box-codegen/commit/6d205c4e28a657ad65ae704a7343a8670806f7f1)) - Include URL into `FetchOptions` (box/box-codegen[#549](https://github.com/box/box-codegen/issues/549)) ([#231](https://github.com/box/box-codegen/issues/231)) ([41c45dc](https://github.com/box/box-codegen/commit/41c45dcf6476b6cae7941c0952c375aa76ce42a1)) - parametrise chunked uploads endpoint urls (box/box-openapi[#444](https://github.com/box/box-codegen/issues/444)) ([#208](https://github.com/box/box-codegen/issues/208)) ([feac37c](https://github.com/box/box-codegen/commit/feac37c34f99b5951731b605ef895f7f3b5de6dd)) - Support `nullable` fields (box/box-codegen[#550](https://github.com/box/box-codegen/issues/550)) ([#230](https://github.com/box/box-codegen/issues/230)) ([b9da32b](https://github.com/box/box-codegen/commit/b9da32b27f506618faa0119f725528555be14f60)) ## 1.0.0 (2024-07-24) ### Bug Fixes - Extract `IntegrationMappingPartnerItemSlack` to `IntegrationMappingPartnerItemSlackUnion` (box/box-codegen[#530](https://github.com/box/box-codegen/issues/530)) ([#183](https://github.com/box/box-codegen/issues/183)) ([3b1b634](https://github.com/box/box-codegen/commit/3b1b634904edc73af094aa8aa6e89d32b9e92aee)) - Improve chunked upload reliability (box/box-codegen[#529](https://github.com/box/box-codegen/issues/529)) ([#182](https://github.com/box/box-codegen/issues/182)) ([e2a045f](https://github.com/box/box-codegen/commit/e2a045f5d2afbe15be0284099ee2236f9c19cd73)) - remove `init` from some of the required fields, `nullability` fixes (box/box-codegen[#532](https://github.com/box/box-codegen/issues/532)) ([#190](https://github.com/box/box-codegen/issues/190)) ([c58f8af](https://github.com/box/box-codegen/commit/c58f8afa41fa4346eb3f2ced9e48695980e917e1)) - retry requests with status code of 202 and `retry-after` header (box/box-codegen[#533](https://github.com/box/box-codegen/issues/533)) ([#191](https://github.com/box/box-codegen/issues/191)) ([abaafd7](https://github.com/box/box-codegen/commit/abaafd70b982ae560430ff083b4bee1d533d5275)) - Update chunked upload (box/box-codegen[#523](https://github.com/box/box-codegen/issues/523)) ([#177](https://github.com/box/box-codegen/issues/177)) ([9bcaf51](https://github.com/box/box-codegen/commit/9bcaf51e0bcd3134dea2b37277a24abaa483754a)) ### New Features and Enhancements - Add `is_active` parameter to user collaboration (box/box-openapi[#437](https://github.com/box/box-codegen/issues/437)) ([#181](https://github.com/box/box-codegen/issues/181)) ([ec5f2d1](https://github.com/box/box-codegen/commit/ec5f2d1d2cdba330f26a7db40042b70d3ec5bca2)) - simplify `namespaces` (box/box-codegen[#518](https://github.com/box/box-codegen/issues/518)) ([#175](https://github.com/box/box-codegen/issues/175)) ([7831b09](https://github.com/box/box-codegen/commit/7831b098971616497cbc90a8c277fee9b2c42c39)) - Support AI Agent API (box/box-codegen[#531](https://github.com/box/box-codegen/issues/531)) ([#188](https://github.com/box/box-codegen/issues/188)) ([0c29645](https://github.com/box/box-codegen/commit/0c296458ef966e57c5aba2a8068034d4de820ef9)) - Support default interface properties, bump dependencies (box/box-codegen[#527](https://github.com/box/box-codegen/issues/527)) ([#184](https://github.com/box/box-codegen/issues/184)) ([6b52792](https://github.com/box/box-codegen/commit/6b52792057ab94f6bcc2f86b47e0ed5f25900adf)) ## 0.4.0 (2024-07-03) ### Bug Fixes - Change base urls (box/box-codegen[#491](https://github.com/box/box-codegen/issues/491)) ([#126](https://github.com/box/box-codegen/issues/126)) ([b4c6025](https://github.com/box/box-codegen/commit/b4c6025dc7039e923b19282333f162bb9d3469a9)) - Fix CI for auto update pull requests (box/box-codegen[#506](https://github.com/box/box-codegen/issues/506)) ([#152](https://github.com/box/box-codegen/issues/152)) ([766f03c](https://github.com/box/box-codegen/commit/766f03c743b7a2ab363135ff282e468b6b71d377)) - Fix schemas for updating classification on a file and folder (box/box-openapi[#423](https://github.com/box/box-codegen/issues/423)) ([#117](https://github.com/box/box-codegen/issues/117)) ([40f5a97](https://github.com/box/box-codegen/commit/40f5a97ea44118ff9425e8b0ebb767d9ed08cee7)) - Improve wording for box sign (box/box-openapi[#424](https://github.com/box/box-codegen/issues/424)) ([#122](https://github.com/box/box-codegen/issues/122)) ([64b3bcd](https://github.com/box/box-codegen/commit/64b3bcd2d99039d1c881a565de6e7bc40dfe7aa9)) ### New Features and Enhancements - Add default implementation for interface methods (box/box-codegen[#502](https://github.com/box/box-codegen/issues/502)) ([#148](https://github.com/box/box-codegen/issues/148)) ([0f39071](https://github.com/box/box-codegen/commit/0f39071d2442b9d07f9c51de8a5a757b16cc4fe7)) - Add docs improvements and marker pagination (box/box-openapi[#431](https://github.com/box/box-codegen/issues/431)) ([#153](https://github.com/box/box-codegen/issues/153)) ([780a58b](https://github.com/box/box-codegen/commit/780a58b4d4b18c357381c76dd5e72dd791a20d89)) - Add support for `ExtraData` of generic type `(box/box-codegen[#521](https://github.com/box/box-codegen/issues/521))` ([#170](https://github.com/box/box-codegen/issues/170)) ([2a2208d](https://github.com/box/box-codegen/commit/2a2208d422f5beb1718576acdc10d9eb973ba95c)) - Add support for unions of primitives (box/box-codegen[#501](https://github.com/box/box-codegen/issues/501)) ([#150](https://github.com/box/box-codegen/issues/150)) ([e75ce82](https://github.com/box/box-codegen/commit/e75ce82b09641d4bec439d620facbbf25da97845)) - Make models immutable, hide fields for auths (box/box-codegen[#494](https://github.com/box/box-codegen/issues/494)) ([#127](https://github.com/box/box-codegen/issues/127)) ([8adcc85](https://github.com/box/box-codegen/commit/8adcc858ef0f924f168406b031d379c786fa90d0)) - Add `SuppressNotifications` and `ExternalSystemName` fields for Box Sign (box/box-openapi[#425](https://github.com/box/box-codegen/issues/425)) ([#124](https://github.com/box/box-codegen/issues/124)) ([c841881](https://github.com/box/box-codegen/commit/c841881cea9b0636bb624fe45d77c2817327dd35)) - Support `StringEnum` (box/box-codegen[#514](https://github.com/box/box-codegen/issues/514)) ([#162](https://github.com/box/box-codegen/issues/162)) ([6ac2fe9](https://github.com/box/box-codegen/commit/6ac2fe9811efde6b02cd3ca50834b0bdafea1ab3)) ### 0.3.1 (2024-05-14) ### Bug Fixes - **docs:** fixes for chunked uploads docs (box/box-codegen[#457](https://github.com/box/box-codegen/issues/457)) ([#64](https://github.com/box/box-codegen/issues/64)) ([744fd8b](https://github.com/box/box-codegen/commit/744fd8b9586a7985eb7ff06d7a1379857da9886c)) - fix `datetimeToString` utils function (box/box-codegen[#459](https://github.com/box/box-codegen/issues/459)) ([#57](https://github.com/box/box-codegen/issues/57)) ([96745b6](https://github.com/box/box-codegen/commit/96745b64b75ded429a3ae5709ea826ffddede406)) - Fix Box AI endpoints (box/box-openapi[#418](https://github.com/box/box-codegen/issues/418)) ([#92](https://github.com/box/box-codegen/issues/92)) ([450a46d](https://github.com/box/box-codegen/commit/450a46d5e76df86d1f23a246094cf098dfafb689)) - fix docs code samples (box/box-codegen[#451](https://github.com/box/box-codegen/issues/451)) ([#53](https://github.com/box/box-codegen/issues/53)) ([5f79cfd](https://github.com/box/box-codegen/commit/5f79cfd07c8b922961c3db56d64dc142aec1191c)) - Fix metadata filter resource (box/box-openapi[#419](https://github.com/box/box-codegen/issues/419)) ([#94](https://github.com/box/box-codegen/issues/94)) ([8c119e7](https://github.com/box/box-codegen/commit/8c119e75719ea8557437f7a71d2c22409ae93cad)) - fix queryParams when they contain a json array (box/box-codegen[#470](https://github.com/box/box-codegen/issues/470)) ([#67](https://github.com/box/box-codegen/issues/67)) ([9e860cf](https://github.com/box/box-codegen/commit/9e860cf977e677f34350aa09249b1752f2c5004e)) - remove mixed union case serialization in c# (box/box-codegen[#485](https://github.com/box/box-codegen/issues/485)) ([#96](https://github.com/box/box-codegen/issues/96)) ([4b44940](https://github.com/box/box-codegen/commit/4b4494085e1977ddd563c316f8fe7feca9ccb425)) ### New Features and Enhancements - Assign default value to fields and args of type enum with only one value (box/box-codegen[#465](https://github.com/box/box-codegen/issues/465)) ([#66](https://github.com/box/box-codegen/issues/66)) ([be7a2b2](https://github.com/box/box-codegen/commit/be7a2b261610564bccc1ffdd59116fc37390ae2b)) - Change `asUser` and `asEnterprise` method names (box/box-codegen[#464](https://github.com/box/box-codegen/issues/464)) ([#61](https://github.com/box/box-codegen/issues/61)) ([f654666](https://github.com/box/box-codegen/commit/f65466661c1f4b73e43025d8f2f7c1b843fea252)) - Move schemas to separate modules (box/box-codegen[#483](https://github.com/box/box-codegen/issues/483)) ([#104](https://github.com/box/box-codegen/issues/104)) ([1c58465](https://github.com/box/box-codegen/commit/1c58465bf9405cda1aebce9f36d800022c09635c)) - Support Box AI endpoints (box/box-openapi[#416](https://github.com/box/box-codegen/issues/416)) ([#90](https://github.com/box/box-codegen/issues/90)) ([7664392](https://github.com/box/box-codegen/commit/7664392651e0338098bc1d1b1bc1f79477f158f3)) - support excluding endpoints and schemas in parser (box/box-codegen[#487](https://github.com/box/box-codegen/issues/487)) ([#105](https://github.com/box/box-codegen/issues/105)) ([d6aedf8](https://github.com/box/box-codegen/commit/d6aedf801890d96bf2e9da0b797136f771076ecc)) - support revoking and downscoping token for BoxDeveloperTokenAuth ([#74](https://github.com/box/box-codegen/issues/74)) ([adb7e04](https://github.com/box/box-codegen/commit/adb7e0491dab3cb527fe5992964cf190b51f1900)) - Update `outcomes` parameter of `StartWorkflow` (box/box-openapi[#413](https://github.com/box/box-codegen/issues/413)) ([#50](https://github.com/box/box-codegen/issues/50)) ([02c7c2b](https://github.com/box/box-codegen/commit/02c7c2b74b70d92be372b57c7b7b4473b98d76d0)) - use getDiscriminatorForUnion in C# (box/box-codegen[#462](https://github.com/box/box-codegen/issues/462)) ([#62](https://github.com/box/box-codegen/issues/62)) ([c6846d8](https://github.com/box/box-codegen/commit/c6846d8334fdb06da22f99baf416007230c69252)) ### 0.3.0 (2024-03-13) ### New Features and Enhancements - add method to authentication classes (box/box-codegen[#442](https://github.com/box/box-dotnet-sdk-gen/issues/442)) ([5560f23](https://github.com/box/box-dotnet-sdk-gen/commit/5560f2334d50e568d20a5b83bd7e99510ff97ca5)) - add `retrieveAuthorizationHeader` method to authentication classes (box/box-codegen[#442](https://github.com/box/box-dotnet-sdk-gen/issues/442)) ([480a710](https://github.com/box/box-dotnet-sdk-gen/commit/480a710f8fd713bc9355d85ac8919d4ad988dc92)) - add local to Function, Field and Type to mark as private for Python (box/box-codegen[#440](https://github.com/box/box-dotnet-sdk-gen/issues/440)) ([6c699c7](https://github.com/box/box-dotnet-sdk-gen/commit/6c699c7e17b6232b4900d37aa0e73059450ac1c3)) - Support version in request headers (box/box-codegen[#418](https://github.com/box/box-dotnet-sdk-gen/issues/418)) ([#34](https://github.com/box/box-dotnet-sdk-gen/issues/34)) ([cdc5806](https://github.com/box/box-dotnet-sdk-gen/commit/cdc5806fba30cf07e4f17e02e106b55c0a7c6a1d)) - throw BoxApiError in C# fetch, add additional data to ResponseInfo (box/box-codegen[#439](https://github.com/box/box-dotnet-sdk-gen/issues/439)) ([#23](https://github.com/box/box-dotnet-sdk-gen/issues/23)) ([6dce6d7](https://github.com/box/box-dotnet-sdk-gen/commit/6dce6d7eb28aa7936db1fecdedeff24eadded2c7)) --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - this project is generated using [Box Codegen](https://github.com/box/box-codegen) based on[Box OpenAPI 3.0 Specification](https://github.com/box/box-openapi), so if you want found something you want to change in the generated code, you'll need to modify the codegen project and submit a pull request there. --- ## Untitled *Type: page* Box Dotnet SDK Gen Project Status build nuget version image Platform Coverage We are excited to introduce the stable release of the latest… # Box Dotnet SDK Gen [](http://opensource.box.com/badges) [](https://badge.fury.io/nu/box.sdk.gen) [](https://badge.fury.io/nu/box.sdk.gen) [](https://coveralls.io/github/box/box-dotnet-sdk-gen?branch=main) We are excited to introduce the stable release of the latest generation of Box Dotnet SDK Gen, designed to elevate the developer experience and streamline your integration with the Box Content Cloud. With this SDK, you’ll have access to: 1. Full API Support: The new generation of Box SDKs empowers developers with complete coverage of the Box API ecosystem. You can now access all the latest features and functionalities offered by Box, allowing you to build even more sophisticated and feature-rich applications. 2. Rapid API Updates: Say goodbye to waiting for new Box APIs to be incorporated into the SDK. With our new auto-generation development approach, we can now add new Box APIs to the SDK at a much faster pace (in a matter of days). This means you can leverage the most up-to-date features in your applications without delay. 3. Embedded Documentation: We understand that easy access to information is crucial for developers. With our new approach, we have included comprehensive documentation for all objects and parameters directly in the source code of the SDK. This means you no longer need to look up this information on the developer portal, saving you time and streamlining your development process. 4. Enhanced Convenience Methods: Our commitment to enhancing your development experience continues with the introduction of convenience methods. These methods cover various aspects such as chunk uploads, classification, and much more. 5. Seamless Start: The new SDKs integrate essential functionalities like authentication, automatic retries with exponential backoff, exception handling, request cancellation, and type checking, enabling you to focus solely on your application's business logic. Embrace the new generation of Box SDKs and unlock the full potential of the Box Content Cloud. # Table of contents - [Box Dotnet SDK Gen](#box-dotnet-sdk-gen) - [Table of contents](#table-of-contents) [Installing](#installing) - [BouncyCastle runtime integrity check](#bouncycastle-runtime-integrity-check) [Getting Started](#getting-started) [Documentation](#documentation) [Upgrades](#upgrades) [Integration Tests](#integration-tests) [Running integration tests locally](#running-integration-tests-locally) - [Create Platform Application](#create-platform-application) - [Export configuration](#export-configuration) - [Running tests](#running-tests) [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) [Copyright and License](#copyright-and-license) # Installing You can install SDK using Nuget ``` Install-Package Box.Sdk.Gen ``` Alternatively, you can find this package and it's latest version [on nuget](https://www.nuget.org/packages/Box.Sdk.Gen) and manually add it to the `.csproj` file as a reference: ``` <ItemGroup> <PackageReference Include="Box.Sdk.Gen" Version="X.Y.Z" /> </ItemGroup> ``` ## BouncyCastle runtime integrity check The version of BouncyCastle included in the SDK performs a checksum validation at runtime. As a result, any modifications to the .dll file, such as those introduced by optimizations like [ReadyToRun (R2R)](https://learn.microsoft.com/en-us/dotnet/core/deploying/ready-to-run) compilation, can alter the checksum, causing the validation to fail. This can lead to issues with SDK functionalities that rely on BouncyCastle, such as JWT authentication unusable. You can exclude BouncyCastle from ReadyToRun compilation by adding the following to your `.csproj` file: ``` <ItemGroup> <PublishReadyToRunExclude Include="bc-fips-1.0.2.dll" /> <PublishReadyToRunExclude Include="bcpkix-fips-1.0.2.dll" /> </ItemGroup> ``` # Getting Started To get started with the SDK, get a Developer Token from the Configuration page of your app in the Box Developer Console. You can use this token to make test calls for your own Box account. The SDK provides a `BoxDeveloperTokenAuth` class, which allows you to authenticate using your Developer Token. Use instance of `BoxDeveloperTokenAuth` to initialize `BoxClient` object. Using `BoxClient` object you can access managers, which allow you to perform some operations on your Box account. The example below demonstrates how to authenticate with Developer Token and print names of all items inside a root folder. ``` using Box.Sdk.Gen; var auth = new BoxDeveloperTokenAuth(token: "DEVELOPER_TOKEN_GOES_HERE"); var client = new BoxClient(auth: auth); var items = await client.Folders.GetFolderItemsAsync(folderId: "0"); if (items.Entries != null) { foreach (var item in items.Entries) { if (item.FileFull != null) { Console.WriteLine(item.FileFull.Name); } else if (item.FolderMini != null) { Console.WriteLine(item.FolderMini.Name); } else if (item.WebLink != null) { Console.WriteLine(item.WebLink.Name); } } } ``` The usage docs that show how to make calls to the Box API with the SDK can be found [here](https://github.com/box/box-Dotnet-sdk-gen/tree/main/docs). We recommend, familiarizing yourself with the remaining [authentication methods](https://github.com/box/box-Dotnet-sdk-gen/tree/main/docs/Authentication.md), [uploading files](https://github.com/box/box-Dotnet-sdk-gen/tree/main/docs/Uploads.md) and [downloading files](https://github.com/box/box-Dotnet-sdk-gen/tree/main/docs/Downloads.md). # Documentation Browse the [docs](https://developer.box.com/9bf713975d30c4a497ecc93c108e61e0/README.md) or see [API Reference](https://developer.box.com/reference/) for more information. # Upgrades Upgrading from our legacy SDKs to the new generation SDKs is a straightforward process. See our [migration guide](https://developer.box.com/440547b696987c10bede540d7415cf77/migration-guide.md) and [changelog](https://developer.box.com/504ace9e948bd7b0fe986d9e7f12a88c/CHANGELOG.md) for more information. # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created in the Box Developer Console with `Server Authentication (with JWT)` selected as authentication method. Once created you can edit properties of the application: - In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. - In section `Advanced Features` enable `Make API calls using the as-user header` and `Generate user access tokens`. Now select `Authorization` and submit application to be reviewed by account admin. ### Export configuration Select `Configuration` tab and in the bottom in the section `App Settings` download your app configuration settings as JSON. 1. Encode configuration file to Base64, e.g. using command: `base64 -i path_to_json_file` 2. Set environment variable: `JWT_CONFIG_BASE_64` with base64 encoded jwt configuration file 3. Set environment variable: `BOX_FILE_REQUEST_ID` with ID of file request already created in the user account, `BOX_EXTERNAL_USER_EMAIL` with email of free external user which not belongs to any enterprise. 4. Set environment variable: `WORKFLOW_FOLDER_ID` with the ID of the Relay workflow that deletes the file that triggered the workflow. The workflow should have a manual start to be able to start it from the API. 5. Set environment variable: `APP_ITEM_ASSOCIATION_FILE_ID` to the ID of the file with associated app item and `APP_ITEM_ASSOCIATION_FOLDER_ID` to the ID of the folder with associated app item. 6. Set environment variable: `APP_ITEM_SHARED_LINK` to the shared link associated with app item. 7. Set environment variable: `SLACK_AUTOMATION_USER_ID` to the ID of the user responsible for the Slack automation, `SLACK_ORG_ID` to the ID of the Slack organization and `SLACK_PARTNER_ITEM_ID` to the ID of the Slack partner item. ### Running tests To run integration tests locally: 1. `dotnet test` # Questions, Bugs, and Feature Requests? Need to contact us directly? Browse the issues tickets! Or, if that doesn't work, file a new one and we will get back to you. If you have general questions about the Box API, you can post to the [Box Developer Forum](https://forum.box.com/). # Copyright and License Copyright 2023 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For third party notices visit [THIRD-PARTY-NOTICES](THIRD-PARTY-NOTICES.txt) --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Migration Guide: From Box Windows V2 SDK to Box Dotnet SDK Introduction Installation Highlighting the Key Differences Nullable reference… # Migration Guide: From Box Windows V2 SDK to Box Dotnet SDK - [Introduction](#introduction) - [Installation](#installation) [Highlighting the Key Differences](#highlighting-the-key-differences) - [Nullable reference types support](#nullable-reference-types-support) - [Self-documenting object creation](#self-documenting-object-creation) - [Native cancellation token support](#native-cancellation-token-support) - [One package to rule them all](#one-package-to-rule-them-all) - [Simplified namespaces](#simplified-namespaces) - [Enum wrapper](#enum-wrapper) - [Union types](#union-types) [Diving into Authentication](#diving-into-authentication) - [Developer Token](#developer-token) [JWT Authentication](#jwt-authentication) - [Leveraging the JWT Configuration File](#leveraging-the-jwt-configuration-file) - [Manually Providing JWT Configuration](#manually-providing-jwt-configuration) - [User Authentication Simplified](#user-authentication-simplified) [Client Credentials Grant](#client-credentials-grant) - [Service Account Token Acquisition](#service-account-token-acquisition) - [User Token Acquisition](#user-token-acquisition) [Smooth Switching between Service Account and User](#smooth-switching-between-service-account-and-user) [OAuth 2.0 Authentication](#oauth-20-authentication) - [Fetching the Authorization URL](#fetching-the-authorization-url) - [Seamless Authentication](#seamless-authentication) [Customizable Token Storage](#customizable-token-storage) [Configuration](#configuration) - [As-User header](#as-user-header) - [Custom Base URLs](#custom-base-urls) [Convenience methods](#convenience-methods) - [Chunked upload of big files](#chunked-upload-of-big-files) ## Introduction Welcome to the `Box DotNet SDK`, the pinnacle of Box's SDK evolution tailored for developers eager to integrate with the Box API using C# with .NET. This next-generation toolkit is meticulously crafted with contemporary development practices, ensuring an unparalleled, seamless experience. While the `Box Windows V2 SDK` served its purpose well, the `Box DotNet SDK` elevates the experience to new heights. One of its standout features is its auto-generation directly from the Open API Specification. This guarantees that developers are always equipped with the latest Box API features, eliminating any lag or discrepancies. This guide is your compass, offering insights and directions for a smooth migration from the legacy `Box Windows V2 SDK` to the state-of-the-art `Box DotNet SDK`. As we journey through, we'll spotlight the key differences, enhanced functionalities, and the myriad benefits that await. For those who wish to delve deeper into the intricacies and advantages of the new SDK, the [official README](https://github.com/box/box-dotnet-sdk-gen/blob/main/README.md) is a treasure trove of information. ## Installation Embarking on your journey with the `Box DotNet SDK` is straightforward. Here's how you can set it up: ``` Install-Package Box.Sdk.Gen ``` Alternatively, you can find this package and it's latest version [on nuget](https://www.nuget.org/packages/Box.Sdk.Gen) and manually add it to the `.csproj` file as a reference: ``` <ItemGroup> <PackageReference Include="Box.Sdk.Gen" Version="X.Y.Z" /> </ItemGroup> ``` For those who are hesitant to make the full leap, fear not. The `Box DotNet SDK` can coexist peacefully alongside the legacy `Box Windows V2 SDK` within the same project. This coexistence offers a gentle migration path, allowing developers to transition at their own pace. However, for an optimal experience, a complete transition to the new SDK is recommended in due course. ## Highlighting the Key Differences ### Nullable reference types support The SDK now supports [nullable reference types](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references) whenever possible. This allows to perform null state analyis and detect many problems even before the code is run. To enable support for nullable references, enable it in your project by adding the following line to your .csproj ``` <Nullable>enable</Nullable> ``` When this option is enabled, a null state analysis will be performed and more information about the object will be present. Let's examine the following scenario: ``` var user = await client.Users.GetUserMeAsync(); // a warning is displayed: "Enterprise" may be null here. You should add a check for the null value to prevent NRE Console.WriteLine(user.Enterprise.Id); ``` Thanks to the null state analysis, it is known that `Enterprise` part of the `user` is not always present in the object and can sometimes be set to `null`. In this case, we need to perform an additional check to avoid the [Null Reference Exception](https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception). ``` var user = await client.Users.GetUserMeAsync(); // no warning now Console.WriteLine(user.Enterprise?.Id); ``` Without nullable reference types, it would not be possible to determine which reference types could be set to null, and we would have to do it with each of them. Otherwise we would risk encountering Null Reference Exception. ### Self-documenting object creation In the Legacy SDK `Box Windows V2 SDK` all objects exposed setters and an empty constructor. It was possible to create an object without setting some of the fields required by the API. This would result in the API error (usually Bad Request) saying that the request was missing some requeired fields. Some of the functions validated if the request fields are set properly, but even then, the lack of required fields could not be detected when call to such function was executed. The modern `Box DotNet SDK` is designed to minimize problems with object creation and "force" the creation of objects in the correct state by utilizng constructors capabilities. Let's look at the following example ``` // It is not possible to create user without a name so it's a required argument of a constructor var requestBody = new CreateUserRequestBodyArg(name: "my-test-account"); var response = await client.Users.CreateUserAsync(requestBody); ``` If a field is required by the API, it must be passed to the constructor. In other words, it's not possible to create a `CreateUserRequestBodyArg` without a name supplied as an argument to the constructor. Optional parameters can be passed using [object initializer syntax](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers). ``` // IsPlatformAccessOnly is not required by the API so it's passed in object initializer var requestBody = new CreateUserRequestBodyArg(name: "my-test-account") { IsPlatformAccessOnly = true }; var response = await client.Users.CreateUserAsync(requestBody); ``` This allows for smooth, one-line and immutable object creation and it's easy to see which fields must be filled in and which are optional. Combined with the previous point about nullable reference types, it allows you to take full advantage of C#'s typing arsenal to prevent errors in your code even before the code is executed. ### Native cancellation token support The new SDK also introduces native support for [CancellationToken](https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken) for every call made to the Box API. This means that every API call can be easily cancelled and the task can be shutdown gracefully. Every API method accepts cancellation token usually as the last, optional parameter. You can use `CancellationToken` in response to your system events or as a timeout mechanism by utilizing the `CancelAfter` method. ``` var requestBody = new CreateUserRequestBodyArg(name: "my-test-account"); var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; // cancel request after 10s cancellationTokenSource.CancelAfter(10000); try { var response = await client.Users.CreateUserAsync(requestBody, cancellationToken: cancellationToken); } catch (TaskCanceledException ex) { //handle exception } ``` When task is cancelled, native .NET `TaskCanceledException` is thrown. ### One package to rule them all Legacy `Box Windows V2 SDK` was distributed as a two separate packages namely `Box.V2` and `Box.V2.Core`. Adding the fact that some supported frameworks overlapped in both packages caused additional confusion for the customers, who had to decide which one was best for their projects. Additionally, the maintenance of both packages introduced developer overhead, extending the time of development for some features. In our new generation .NET SDK `Box DotNet SDK`, we have decided to distribute one package that is designed for multiple platforms, namely `Box.Sdk.Gen`. The determination of the best possible package match to the project in which this package is used will be delegated to the .NET platform itself. Each target platform with significiant differences will have a separate code base so that one target does not limit another. Most of the SDK is automatically generated now, so this will not cause a significant development overhead. For now, only .NET (formerly .NET Core) is supported, but .NET Framework support is planned for the future. ### Simplified namespaces Legacy `Box Windows V2 SDK` contained multiple namespaces which greatly reduced the discoverability of new features. The namespaces were also grouped based on their physical location rather than purpose they serve. Developers had to navigate through numerous namespaces to find the classes and methods they needed, which could be overwhelming and confusing, especially for newcomers. To simplify it, our the new generation .NET SDK `Box DotNet SDK`, provides only 4 main namespaces: - Box.Sdk.Gen - mostly contains base classes used by the SDK (e.g. `OneOf`, `StringEnum`). - Box.Sdk.Gen.Managers - contains managers that expose endpoints as functions. It also contains classes used to create requests, such as typed request body or query parameters. - Box.Sdk.Gen.Schemas - contains data models described by the API spec. - Box.Sdk.Gen.Internal - utility functions and classes used by the SDK. Should be used only if needed too. ### Enum wrapper Legacy `Box Windows V2 SDK` used [C# enumeration types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum) when API exposed model with limited number of possible value for `String`. ``` public enum BoxRetentionType { modifiable, non_modifiable } //response fails during deserialization if BoxRetention type returned from the API is not defined on enum (e.g. partially_modifiable) var retentionType = await (client.RetentionPoliciesManager.GetRetentionPolicyAsync('id')).Type; ``` Sometimes this led to a situation where a newly added enum variant was present in the specification, but not in the SDK, and an exception could be thrown when deserializing the response. To overcome these issues the new generation .NET SDK `Box DotNet SDK` wraps enum types in safe, custom `StringEnum` structure. ``` // Type can be null, but it no longer fails, var retentionType = (await client.RetentionPolicies.GetRetentionPolicyByIdAsync(retentionPolicyId: retentionPolicy.Id)).Type; if (retentionType.Value.HasValue) { //it's a nullable enum so we need to access the underlying value RetentionPolicyRetentionTypeField enumVal = retentionType.Value.Value; } else { //if the enum value was null it means that this enum is unknown to the SDK at the moment, but we still can access the original value that came from the api through .StringValue prop string enumVaueAsString = retentionType.StringValue; } ``` This allows safe access to the underlying enumeration type. If the enumeration value is not yet known to the SDK, you can still access the original value from the API, by accessing `.StringValue` field. Thanks to [implicit conversion operators](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators) converting enum types to `StringEnum` is simple and usually there's no need to do it explicitly. ``` var requestBody = new CreateRetentionPolicyRequestBody("myPolicy", CreateRetentionPolicyRequestBodyPolicyTypeField.Finite, CreateRetentionPolicyRequestBodyDispositionActionField.PermanentlyDelete); RetentionPolicy retentionPolicy = await client.RetentionPolicies.CreateRetentionPolicyAsync(requestBody); ``` Usually there's no need to wrap enum type in the `StringEnum`, but if such need arises, you can use existing constructor of the `StringEnum`. ``` RetentionPolicyRetentionTypeField retentionPolicyType = RetentionPolicyRetentionTypeField.Modifiable; StringEnum<RetentionPolicyRetentionTypeField> retentionPolicyTypeWrapped = new StringEnum<RetentionPolicyRetentionTypeField>(retentionPolicyType); ``` ### Union types Box APIs can return and accept objects with different schemas at certain endpoints. This means that in C#, they must be represented by different classes to take full advantage of the type system. Legacy `Box Windows V2 SDK` used approach with common ancestor, by returning base object (in this case `BoxEntity`) that needed to be explicitly casted to the desired type. ``` var enterpriseEvents = await boxClient.EventsManager.EnterpriseEventsAsync(); foreach (BoxEnterpriseEvent entry in enterpriseEvents.Entries) { // we need to check if Source is of type BoxFileEventSource and cast it if (entry.Source is BoxFileEventSource fileEvent) { Console.WriteLine(fileEvent.Parent.Id); } } ``` This solution is error-prone and relies on the knowledge of the internals of the SDK. New generation .NET SDK `Box DotNet SDK` provides a custom structure to represent union types (or sum types) called `OneOf<T1, T2, ...>`. The different variant are represented as different fields on this structure. This allows new SDK users to use it like any other model. In addition, the SDK does not directly expose the `OneOf` structure in the models, but inherits from it, so you do not need to know how it works in detail when working with models. ``` var enterpriseEvents = await client.Events.GetEventsAsync(queryParams: new GetEventsQueryParams() { StreamType = GetEventsQueryParamsStreamTypeField.AdminLogs }); foreach (var entry in enterpriseEvents.Entries) { //if .File is not null it means it was returned from the API if (entry.Source.File != null) { Console.WriteLine(entry.Source.File.Parent.Id); } } ``` ## Diving into Authentication Authentication is a crucial aspect of any SDK. Let's delve into the authentication methods supported by both SDKs and understand the enhancements in the new version: ### Developer Token The Developer Token remains a straightforward method for authentication: **Legacy (`Box Windows V2 SDK`):** ``` using Box.Sdk.V2.Auth; using Box.Sdk.V2.Config; using Box.Sdk.V2; var config = new BoxConfigBuilder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET").Build(); var session = new OAuthSession("YOUR_DEVELOPER_TOKEN", "N/A", 3600, "bearer"); var client = new BoxClient(config, session); ``` **Modern (`Box DotNet SDK`):** The new SDK offers a more streamlined approach: ``` using Box.Sdk.Gen; var auth = new BoxDeveloperTokenAuth(token: "DEVELOPER_TOKEN_GOES_HERE"); var client = new BoxClient(auth: auth); ``` ### JWT Authentication JSON Web Tokens (JWT) offer a secure method of authentication. Here's how the process has evolved: #### Leveraging the JWT Configuration File **Legacy (`Box Windows V2 SDK`):** ``` using Box.Sdk.V2; using Box.Sdk.V2.Config; using Box.Sdk.V2.JWTAuth; using var file = File.Open("/path/to/config.json", FileMode.Open, FileAccess.Read, FileShare.None); var config = BoxConfigBuilder.CreateFromJsonFile(file).Build(); var boxJWT = new BoxJWTAuth(config); var adminToken = await boxJWT.AdminTokenAsync(); BoxClient client = boxJWT.AdminClient(adminToken); ``` **Modern (`Box DotNet SDK`):** The new SDK provides a more organized approach: ``` using Box.Sdk.Gen; using var file = File.Open("/path/to/config.json", FileMode.Open, FileAccess.Read, FileShare.None); var jwtConfig = JwtConfig.FromConfigFile(file); var auth = new BoxJwtAuth(config: jwtConfig); var client = new BoxClient(auth: auth); ``` #### Manually Providing JWT Configuration For those who prefer manual configurations, both SDKs offer flexibility: **Legacy (`Box Windows V2 SDK`):** ``` using Box.Sdk.V2; using Box.Sdk.V2.Config; using Box.Sdk.V2.JWTAuth; var boxConfig = new BoxConfigBuilder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "YOUR_ENTERPRISE_ID", "YOUR_PRIVATE_KEY", "YOUR_PRIVATE_KEY_PASSPHRASE", "YOUR_KEY_ID").Build(); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = await boxJWT.AdminTokenAsync(); BoxClient adminClient = boxJWT.AdminClient(adminToken); ``` **Modern (`Box DotNet SDK`):** The new SDK introduces a more structured approach: ``` using Box.Sdk.Gen; var jwtConfig = new JwtConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", enterpriseId: "YOUR_ENTERPRISE_ID", privateKey: "YOUR_PRIVATE_KEY", privateKeyPassphrase: "YOUR_PRIVATE_KEY_PASSPHRASE", publicKeyId: "YOUR_KEY_ID"); var auth = new BoxJwtAuth(config: jwtConfig); var client = new BoxClient(auth: auth); ``` #### User Authentication Simplified Authenticating as a user has been made even more straightforward: **Legacy (`Box Windows V2 SDK`):** ``` using Box.Sdk.V2; using Box.Sdk.V2.Config; using Box.Sdk.V2.JWTAuth; var userToken = await boxJWT.UserTokenAsync("USER_ID"); var userClient = boxJWT.UserClient(userToken, "YOUR_USER_ID"); ``` **Modern (`Box DotNet SDK`):** The new SDK makes this method more organised: ``` using Box.Sdk.Gen; await auth.AsUserAsync("USER_ID"); var userClient = new BoxClient(auth: auth); ``` ### Client Credentials Grant The Client Credentials Grant method is a popular choice for many developers. Let's see how it's been enhanced: #### Service Account Token Acquisition **Legacy (`Box Windows V2 SDK`):** ``` using Box.Sdk.V2.CCGAuth; using Box.Sdk.V2.Config; var boxConfig = new BoxConfigBuilder(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET") .SetEnterpriseId("YOUR_ENTERPRISE_ID") .Build(); var boxCCG = new BoxCCGAuth(boxConfig); var adminToken = await boxCCG.AdminTokenAsync(); var adminClient = boxCCG.AdminClient(adminToken: adminToken); ``` **Modern (`Box DotNet SDK`):** The new SDK offers a more organized structure: ``` using Box.Sdk.Gen; var ccgConfig = new CcgConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", enterpriseId: "YOUR_ENTERPRISE_ID"); var auth = new BoxCcgAuth(config: ccgConfig); var client = new BoxClient(auth: auth); ``` #### User Token Acquisition **Legacy (`Box Windows V2 SDK`):** ``` using Box.Sdk.V2.CCGAuth; using Box.Sdk.V2.Config; var boxConfig = new BoxConfigBuilder(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET") .Build(); var boxCCG = new BoxCCGAuth(boxConfig); var userToken = await boxCCG.UserTokenAsync("YOUR_USER_ID"); var userClient = boxCCG.UserClient(userToken: userToken, userId: "YOUR_USER_ID"); ``` **Modern (`Box DotNet SDK`):** The new SDK streamlines the process: ``` using Box.Sdk.Gen; var ccgConfig = new CcgConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", userId: "YOUR_USER_ID"); var auth = new BoxCcgAuth(config: ccgConfig); var userClient = new BoxClient(auth: auth); ``` ### Smooth Switching between Service Account and User Transitioning between account types is now more intuitive: **Modern (`Box DotNet SDK`):** ``` using Box.Sdk.Gen; await auth.AsEnterpriseAsync("ENTERPRISE_ID"); ``` ### OAuth 2.0 Authentication OAuth 2.0 remains a robust authentication method. Let's explore the improvements: #### Fetching the Authorization URL **Legacy (`Box Windows V2 SDK`):** ``` using Box.Sdk.V2; using Box.Sdk.V2.Config; var config = new BoxConfigBuilder("CLIENT_ID", "CLIENT_SECRET", new System.Uri("YOUR_REDIRECT_URL")).Build(); var client = new BoxClient(config); // the URL to redirect the user to var authorizeUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code"; ``` **Modern (`Box DotNet SDK`):** The new SDK provides more flexibility: ``` using Box.Sdk.Gen; var config = new OAuthConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET"); var auth = new BoxOAuth(config: config); // the URL to redirect the user to var authorizeUrl = auth.GetAuthorizeUrl(new GetAuthorizeUrlOptions() { RedirectUri = "YOUR_REDIRECT_URL" }); ``` #### Seamless Authentication **Legacy (`Box Windows V2 SDK`):** ``` using Box.Sdk.V2; var session = await client.Auth.AuthenticateAsync("[CODE]"); var client = new BoxClient(config, session); ``` **Modern (`Box DotNet SDK`):** The new SDK simplifies the process: ``` using Box.Sdk.Gen; await auth.GetTokensAuthorizationCodeGrantAsync("code"); ``` ### Customizable Token Storage Token management is crucial for maintaining secure sessions. The new SDK offers enhanced flexibility: **Legacy (`Box Windows V2 SDK`):** ``` // there are no good ways to implement token storage in the legacy sdk // best that can be done is to respond to the authorization events public class CustomTokenStorage { // retrieves token string RetrieveToken(); // stores token void SaveToken(string accessToken); } var client = new BoxClient(config, session); client.Auth.SessionAuthenticated += delegate (object o, SessionAuthenticatedEventArgs e) { string newAccessToken = e.Session.AccessToken; tokenStorage.SaveToken(newAccessToken); }; ``` **Modern (`Box DotNet SDK`):** The new SDK allows developers to define custom classes for token storage: ``` using Box.Sdk.Gen; using Box.Sdk.Gen.Schemas; using Task = System.Threading.Tasks.Task; class CustomTokenStorage : ITokenStorage { // Clear token public Task ClearAsync() { throw new NotImplementedException(); } // Retrieve token public Task<AccessToken?> GetAsync() { throw new NotImplementedException(); } // Store token public Task StoreAsync(AccessToken token) { throw new NotImplementedException(); } } var tokenStorage = new CustomTokenStorage(); var config = new OAuthConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", tokenStorage: tokenStorage); ``` ## Configuration ### As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an `As-User: USER-ID` header. The following examples assume that the client has been instantiated with an access token with appropriate privileges to make As-User calls. In old SDK you could call client constructor with `asUser` parameter to create a new client to impersonate the provided user. **Legacy (`Box Windows V2 SDK`):** ``` using Box.V2.Config; var config = new BoxConfigBuilder("clientId", "clientSecret").Build(); var client = new BoxClient(config, asUser: "userId"); ``` **Modern (`Box DotNet SDK`):** In the new SDK the method was renamed to `WithAsUserHeader(string userId)` and returns a new instance of `BoxClient` class with the As-User header appended to all API calls made by the client. The method accepts only user id as a parameter. ``` using Box.Sdk.Gen; var client = new BoxClient(new BoxCcgAuth(new CcgConfig("clientId", "clientSecret"))); var asUserClient = client.WithAsUserHeader("userId"); ``` Additionally `BoxClient` offers a `WithExtraHeaders(Dictionary<string, string>? extraHeaders = default) ` method, which allows you to specify the custom set of headers, which will be included in every API call made by client. Calling the `client.WithExtraHeaders(extraHeaders)` method creates a new client, leaving the original client unmodified. ``` using Box.Sdk.Gen; var client = new BoxClient(new BoxCcgAuth(new CcgConfig("clientId", "clientSecret"))); var clientWithHeaders = client.WithExtraHeaders(new Dictionary<string, string>() { { "customHeaders", "customHeaderValue" } }); ``` ### Custom Base URLs **Legacy (`Box Windows V2 SDK`):** In old SDK you could specify the custom base URLs, which will be used for API calls made by setting the new values by calling function of `BoxConfigBuilder`. ``` using Box.V2.Config; var config = new BoxConfigBuilder("clientId", "clientSecret") .SetBoxApiHostUri(new Uri("https://new-base-url.com")) .SetBoxUploadApiUri(new Uri("https://my-company-upload-url.com")) .Build(); ``` **Modern (`Box DotNet SDK`):** In the new SDK this functionality has been implemented as part of the `BoxClient` class. By calling the `client.WithCustomBaseUrls()` method, you can specify the custom base URLs that will be used for API calls made by client. Following the immutability pattern, this call creates a new client, leaving the original client unmodified. ``` using Box.Sdk.Gen; var client = new BoxClient(new BoxCcgAuth(new CcgConfig("clientId", "clientSecret"))); var clientWithCustomUrls = client.WithCustomBaseUrls(new BaseUrls("https://new-base-url.com", "https://my-company-upload-url.com", "https://my-company.com/oauth2")); ``` ## Convenience methods ### Chunked upload of big files For large files or in cases where the network connection is less reliable, you may want to upload the file in parts. This allows a single part to fail without aborting the entire upload, and failed parts are being retried automatically. **Legacy (`Box Windows V2 SDK`):** In the old SDK, you could use the `UploadUsingSessionAsync` method of the `FilesManager` class to upload a large file. This method accepted a `Stream` as the input stream, and the file name and parent folder ID were passed as parameters. ``` using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { string parentFolderId = "0"; var bFile = await client.FilesManager.UploadUsingSessionAsync(fileStream, "File v2.pdf", parentFolderId); Console.WriteLine("{0} uploaded to folder: {1} as file: {2}", filePath, parentFolderId, bFile.Id); } ``` **Modern (`Box DotNet SDK`):** In the new SDK, the equivalent method is `ChunkedUploads.UploadBigFileAsync()`. It accepts a `Stream` object as the `file` parameter, and the `fileName` and `fileSize` parameters are now passed as arguments. The `parentFolderId` parameter is also required to specify the folder where the file will be uploaded. ``` int fileSize = 20 * 1024 * 1024; using var fileByteStream = new FileStream("My_Large_File.txt", FileMode.Open, FileAccess.Read); string fileName = "My_Large_File.txt"; const string parentFolderId = "0"; var uploadedFile = await client.ChunkedUploads.UploadBigFileAsync( file: fileByteStream, fileName: fileName, fileSize: fileSize, parentFolderId: parentFolderId ); ``` --- ## Untitled *Type: page* AiManager Ask question Generate text Get AI agent default configuration Extract metadata (freeform) Extract metadata (structured) Ask… # AiManager - [Ask question](#ask-question) - [Generate text](#generate-text) - [Get AI agent default configuration](#get-ai-agent-default-configuration) - [Extract metadata (freeform)](#extract-metadata-freeform) - [Extract metadata (structured)](#extract-metadata-structured) ## Ask question Sends an AI request to supported LLMs and returns an answer specifically focused on the user's question given the provided context. This operation is performed by calling function `createAiAsk`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-ask/). ``` try await client.ai.createAiAsk(requestBody: AiAsk(mode: AiAskModeField.singleItemQa, prompt: "which direction sun rises", items: [AiItemAsk(id: fileToAsk.id, type: AiItemAskTypeField.file, content: "Sun rises in the East")])) ``` ### Arguments requestBody `AiAsk` - Request body of createAiAsk method headers `CreateAiAskHeaders` - Headers of createAiAsk method ### Returns This function returns a value of type `AiResponseFull?`. A successful response including the answer from the LLM.No content is available to answer the question. This is returned when the request item is a hub, but content in the hubs is not indexed. To ensure content in the hub is indexed, make sure Box AI for Hubs in the Admin Console was enabled before hub creation. ## Generate text Sends an AI request to supported Large Language Models (LLMs) and returns generated text based on the provided prompt. This operation is performed by calling function `createAiTextGen`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-text-gen/). ``` try await client.ai.createAiTextGen(requestBody: AiTextGen(prompt: "Parapharse the document.s", items: [AiTextGenItemsField(id: fileToAsk.id, type: AiTextGenItemsTypeField.file, content: "The Earth goes around the sun. Sun rises in the East in the morning.")], dialogueHistory: [AiDialogueHistory(prompt: "What does the earth go around?", answer: "The sun", createdAt: try Utils.Dates.dateTimeFromString(dateTime: "2021-01-01T00:00:00Z")), AiDialogueHistory(prompt: "On Earth, where does the sun rise?", answer: "East", createdAt: try Utils.Dates.dateTimeFromString(dateTime: "2021-01-01T00:00:00Z"))])) ``` ### Arguments requestBody `AiTextGen` - Request body of createAiTextGen method headers `CreateAiTextGenHeaders` - Headers of createAiTextGen method ### Returns This function returns a value of type `AiResponse`. A successful response including the answer from the LLM. ## Get AI agent default configuration Get the AI agent default config. This operation is performed by calling function `getAiAgentDefaultConfig`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agent-default/). ``` try await client.ai.getAiAgentDefaultConfig(queryParams: GetAiAgentDefaultConfigQueryParams(mode: GetAiAgentDefaultConfigQueryParamsModeField.ask, language: "en-US")) ``` ### Arguments queryParams `GetAiAgentDefaultConfigQueryParams` - Query parameters of getAiAgentDefaultConfig method headers `GetAiAgentDefaultConfigHeaders` - Headers of getAiAgentDefaultConfig method ### Returns This function returns a value of type `AiAgentAskOrAiAgentExtractOrAiAgentExtractStructuredOrAiAgentTextGen`. A successful response including the default agent configuration. This response can be one of the following four objects: - AI agent for questions - AI agent for text generation - AI agent for freeform metadata extraction - AI agent for structured metadata extraction. The response depends on the agent configuration requested in this endpoint. ## Extract metadata (freeform) Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of key-value pairs. In this request, both the prompt and the output can be freeform. Metadata template setup before sending the request is not required. This operation is performed by calling function `createAiExtract`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract/). ``` try await client.ai.createAiExtract(requestBody: AiExtract(prompt: "firstName, lastName, location, yearOfBirth, company", items: [AiItemBase(id: file.id)])) ``` ### Arguments requestBody `AiExtract` - Request body of createAiExtract method headers `CreateAiExtractHeaders` - Headers of createAiExtract method ### Returns This function returns a value of type `AiResponse`. A response including the answer from the LLM. ## Extract metadata (structured) Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. For this request, you either need a metadata template or a list of fields you want to extract. Input is **either** a metadata template or a list of fields to ensure the structure. To learn more about creating templates, see [Creating metadata templates in the Admin Console](https://support.box.com/hc/en-us/articles/360044194033-Customizing-Metadata-Templates) or use the [metadata template API](g://metadata/templates/create). This operation is performed by calling function `createAiExtractStructured`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract-structured/). ``` try await client.ai.createAiExtractStructured(requestBody: AiExtractStructured(fields: [AiExtractStructuredFieldsField(key: "firstName", displayName: "First name", description: "Person first name", prompt: "What is the your first name?", type: "string"), AiExtractStructuredFieldsField(key: "lastName", displayName: "Last name", description: "Person last name", prompt: "What is the your last name?", type: "string"), AiExtractStructuredFieldsField(key: "dateOfBirth", displayName: "Birth date", description: "Person date of birth", prompt: "What is the date of your birth?", type: "date"), AiExtractStructuredFieldsField(key: "age", displayName: "Age", description: "Person age", prompt: "How old are you?", type: "float"), AiExtractStructuredFieldsField(key: "hobby", displayName: "Hobby", description: "Person hobby", prompt: "What is your hobby?", type: "multiSelect", options: [AiExtractStructuredFieldsOptionsField(key: "guitar"), AiExtractStructuredFieldsOptionsField(key: "books")])], items: [AiItemBase(id: file.id)])) ``` ### Arguments requestBody `AiExtractStructured` - Request body of createAiExtractStructured method headers `CreateAiExtractStructuredHeaders` - Headers of createAiExtractStructured method ### Returns This function returns a value of type `AiExtractStructuredResponse`. A successful response including the answer from the LLM. --- ## Untitled *Type: page* ArchivesManager List archives Create archive Delete archive List archives Retrieves archives for an enterprise. This operation is performed… # ArchivesManager - [List archives](#list-archives) - [Create archive](#create-archive) - [Delete archive](#delete-archive) ## List archives Retrieves archives for an enterprise. This operation is performed by calling function `getArchivesV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-archives/). ``` try await client.archives.getArchivesV2025R0(queryParams: GetArchivesV2025R0QueryParams(limit: Int64(100))) ``` ### Arguments queryParams `GetArchivesV2025R0QueryParams` - Query parameters of getArchivesV2025R0 method headers `GetArchivesV2025R0Headers` - Headers of getArchivesV2025R0 method ### Returns This function returns a value of type `ArchivesV2025R0`. Returns a list of archives in the enterprise. ## Create archive Creates an archive. This operation is performed by calling function `createArchiveV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-archives/). ``` try await client.archives.createArchiveV2025R0(requestBody: CreateArchiveV2025R0RequestBody(name: archiveName)) ``` ### Arguments requestBody `CreateArchiveV2025R0RequestBody` - Request body of createArchiveV2025R0 method headers `CreateArchiveV2025R0Headers` - Headers of createArchiveV2025R0 method ### Returns This function returns a value of type `ArchiveV2025R0`. Returns a new archive object. ## Delete archive Permanently deletes an archive. This operation is performed by calling function `deleteArchiveByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-archives-id/). ``` try await client.archives.deleteArchiveByIdV2025R0(archiveId: archive.id) ``` ### Arguments archiveId `String` - The ID of the archive. Example: "982312" headers `DeleteArchiveByIdV2025R0Headers` - Headers of deleteArchiveByIdV2025R0 method ### Returns This function returns a value of type ``. Returns an empty response when the archive has been deleted. --- ## Untitled *Type: page* AppItemAssociationsManager List file app item associations List folder app item associations List file app item associations This is a beta… # AppItemAssociationsManager - [List file app item associations](#list-file-app-item-associations) - [List folder app item associations](#list-folder-app-item-associations) ## List file app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the file is associated with. This includes app items associated with ancestors of the file. Assuming the context user has access to the file, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `getFileAppItemAssociations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-app-item-associations/). ``` try await client.appItemAssociations.getFileAppItemAssociations(fileId: fileId) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileAppItemAssociationsQueryParams` - Query parameters of getFileAppItemAssociations method headers `GetFileAppItemAssociationsHeaders` - Headers of getFileAppItemAssociations method ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this file, an empty collection will be returned. This list includes app items on ancestors of this File. ## List folder app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the folder is associated with. This includes app items associated with ancestors of the folder. Assuming the context user has access to the folder, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `getFolderAppItemAssociations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-app-item-associations/). ``` try await client.appItemAssociations.getFolderAppItemAssociations(folderId: folderId) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderAppItemAssociationsQueryParams` - Query parameters of getFolderAppItemAssociations method headers `GetFolderAppItemAssociationsHeaders` - Headers of getFolderAppItemAssociations method ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this folder an empty collection will be returned. This list includes app items on ancestors of this folder. --- ## Untitled *Type: page* AiStudioManager List AI agents Create AI agent Update AI agent Get AI agent by agent ID Delete AI agent List AI agents Lists AI agents based… # AiStudioManager - [List AI agents](#list-ai-agents) - [Create AI agent](#create-ai-agent) - [Update AI agent](#update-ai-agent) - [Get AI agent by agent ID](#get-ai-agent-by-agent-id) - [Delete AI agent](#delete-ai-agent) ## List AI agents Lists AI agents based on the provided parameters. This operation is performed by calling function `getAiAgents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents/). ``` try await client.aiStudio.getAiAgents() ``` ### Arguments queryParams `GetAiAgentsQueryParams` - Query parameters of getAiAgents method headers `GetAiAgentsHeaders` - Headers of getAiAgents method ### Returns This function returns a value of type `AiMultipleAgentResponse`. A successful response including the agents list. ## Create AI agent Creates an AI agent. At least one of the following capabilities must be provided: `ask`, `text_gen`, `extract`. This operation is performed by calling function `createAiAgent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-agents/). ``` try await client.aiStudio.createAiAgent(requestBody: CreateAiAgent(name: agentName, accessState: "enabled", ask: AiStudioAgentAsk(accessState: "enabled", description: "desc1"))) ``` ### Arguments requestBody `CreateAiAgent` - Request body of createAiAgent method headers `CreateAiAgentHeaders` - Headers of createAiAgent method ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Update AI agent Updates an AI agent. This operation is performed by calling function `updateAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-ai-agents-id/). ``` try await client.aiStudio.updateAiAgentById(agentId: createdAgent.id, requestBody: CreateAiAgent(name: agentName, accessState: "enabled", ask: AiStudioAgentAsk(accessState: "disabled", description: "desc2"))) ``` ### Arguments agentId `String` - The ID of the agent to update. Example: "1234" requestBody `CreateAiAgent` - Request body of updateAiAgentById method headers `UpdateAiAgentByIdHeaders` - Headers of updateAiAgentById method ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Get AI agent by agent ID Gets an AI Agent using the `agent_id` parameter. This operation is performed by calling function `getAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents-id/). ``` try await client.aiStudio.getAiAgentById(agentId: createdAgent.id, queryParams: GetAiAgentByIdQueryParams(fields: ["ask"])) ``` ### Arguments agentId `String` - The agent id to get. Example: "1234" queryParams `GetAiAgentByIdQueryParams` - Query parameters of getAiAgentById method headers `GetAiAgentByIdHeaders` - Headers of getAiAgentById method ### Returns This function returns a value of type `AiSingleAgentResponseFull`. A successful response including the agent. ## Delete AI agent Deletes an AI agent using the provided parameters. This operation is performed by calling function `deleteAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-ai-agents-id/). ``` try await client.aiStudio.deleteAiAgentById(agentId: createdAgent.id) ``` ### Arguments agentId `String` - The ID of the agent to delete. Example: "1234" headers `DeleteAiAgentByIdHeaders` - Headers of deleteAiAgentById method ### Returns This function returns a value of type ``. A successful response with no content. --- ## Untitled *Type: page* AuthorizationManager Authorize user Request access token Refresh access token Revoke access token Authorize user Authorize a user by sending… # AuthorizationManager - [Authorize user](#authorize-user) - [Request access token](#request-access-token) - [Refresh access token](#refresh-access-token) - [Revoke access token](#revoke-access-token) ## Authorize user Authorize a user by sending them through the [Box](https://box.com) website and request their permission to act on their behalf. This is the first step when authenticating a user using OAuth 2.0. To request a user's authorization to use the Box APIs on their behalf you will need to send a user to the URL with this format. This operation is performed by calling function `authorizeUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-authorize/). *Currently we don't have an example for calling `authorizeUser` in integration tests* ### Arguments queryParams `AuthorizeUserQueryParams` - Query parameters of authorizeUser method headers `AuthorizeUserHeaders` - Headers of authorizeUser method ### Returns This function returns a value of type ``. Does not return any data, but rather should be used in the browser. ## Request access token Request an Access Token using either a client-side obtained OAuth 2.0 authorization code or a server-side JWT assertion. An Access Token is a string that enables Box to verify that a request belongs to an authorized session. In the normal order of operations you will begin by requesting authentication from the [authorize](#get-authorize) endpoint and Box will send you an authorization code. You will then send this code to this endpoint to exchange it for an Access Token. The returned Access Token can then be used to to make Box API calls. This operation is performed by calling function `requestAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token/). *Currently we don't have an example for calling `requestAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2Token` - Request body of requestAccessToken method headers `RequestAccessTokenHeaders` - Headers of requestAccessToken method ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Refresh access token Refresh an Access Token using its client ID, secret, and refresh token. This operation is performed by calling function `refreshAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token--refresh/). *Currently we don't have an example for calling `refreshAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2TokenRefreshAccessToken` - Request body of refreshAccessToken method headers `RefreshAccessTokenHeaders` - Headers of refreshAccessToken method ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Revoke access token Revoke an active Access Token, effectively logging a user out that has been previously authenticated. This operation is performed by calling function `revokeAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-revoke/). *Currently we don't have an example for calling `revokeAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2Revoke` - Request body of revokeAccessToken method headers `RevokeAccessTokenHeaders` - Headers of revokeAccessToken method ### Returns This function returns a value of type ``. Returns an empty response when the token was successfully revoked. --- ## Untitled *Type: page* AvatarsManager Get user avatar Add or update user avatar Delete user avatar Get user avatar Retrieves an image of a the user's avatar. This… # AvatarsManager - [Get user avatar](#get-user-avatar) - [Add or update user avatar](#add-or-update-user-avatar) - [Delete user avatar](#delete-user-avatar) ## Get user avatar Retrieves an image of a the user's avatar. This operation is performed by calling function `getUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-avatar/). ``` try await client.avatars.getUserAvatar(userId: user.id, downloadDestinationUrl: destinationPath) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" downloadDestinationUrl `URL` - The URL on disk where the file will be saved once it has been downloaded. headers `GetUserAvatarHeaders` - Headers of getUserAvatar method ### Returns This function returns a value of type `URL?`. When an avatar can be found for the user the image data will be returned in the body of the response. ## Add or update user avatar Adds or updates a user avatar. This operation is performed by calling function `createUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-avatar/). ``` try await client.avatars.createUserAvatar(userId: user.id, requestBody: CreateUserAvatarRequestBody(pic: Utils.decodeBase64ByteStream(data: "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg=="), picContentType: "image/png", picFileName: "avatar.png")) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" requestBody `CreateUserAvatarRequestBody` - Request body of createUserAvatar method headers `CreateUserAvatarHeaders` - Headers of createUserAvatar method ### Returns This function returns a value of type `UserAvatar`. `ok`: Returns the `pic_urls` object with URLs to existing user avatars that were updated.`created`: Returns the `pic_urls` object with URLS to user avatars uploaded to Box with the request. ## Delete user avatar Removes an existing user avatar. You cannot reverse this operation. This operation is performed by calling function `deleteUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-avatar/). ``` try await client.avatars.deleteUserAvatar(userId: user.id) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" headers `DeleteUserAvatarHeaders` - Headers of deleteUserAvatar method ### Returns This function returns a value of type ``. `no_content`: Removes the avatar and returns an empty response. --- ## Untitled *Type: page* Authentication Authentication Authentication methods Developer Token Client Credentials Grant Obtaining Service Account token Obtaining User… # Authentication - [Authentication](#authentication) [Authentication methods](#authentication-methods) - [Developer Token](#developer-token) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) - [Switching between Service Account and User](#switching-between-service-account-and-user) [OAuth 2.0 Auth](#oauth-20-auth) - [Login flow (recommended)](#login-flow-recommended) - [Manual flow](#manual-flow) - [Injecting existing token into BoxOAuth](#injecting-existing-token-into-boxoauth) [Retrieve current access token](#retrieve-current-access-token) [Refresh access token](#refresh-access-token) [Revoke token](#revoke-token) [Downscope token](#downscope-token) [Token storage](#token-storage) - [In-memory token storage](#in-memory-token-storage) - [Keychain token storage](#keychain-token-storage) - [Custom storage](#custom-storage) # Authentication methods ## Developer Token The fastest way to get started using the API is with developer token. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. To create a `BoxClient` with a developer token, construct an `BoxDeveloperTokenAuth` object with the `token` set to the developer token and construct the client with that. ``` import BoxSdkGen let auth = BoxDeveloperTokenAuth(token: "DEVELOPER_TOKEN_GOES_HERE") let client = BoxClient(auth: auth) let me = try await client.users.getUserMe() print("My user ID is \(me.id)") ``` ## Client Credentials Grant Before using Client Credentials Grant Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with Client Credentials Grant](https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/) Client Credentials Grant Auth method allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account. You can use `BoxCCGAuth` to initialize a client object the same way as for other authentication types: ``` import BoxSdkGen let config = CCGConfig( clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", userId: "YOUR_USER_ID" ) let auth = BoxCCGAuth(config: config) let client = BoxClient(auth: auth) let user = try await client.users.getUserMe() print("Id of the authenticated user is \(user.id)") ``` Obtained token is valid for specified amount of time, it will be refreshed automatically by default. ### Obtaining Service Account token The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID with client id and secret: ``` import BoxSdkGen let config = CCGConfig( clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", enterpriseId: "YOUR_ENTERPRISE_ID" ) let auth = BoxCCGAuth(config: config) let client = BoxClient(auth: auth) ``` ### Obtaining User token In order to enable obtaining user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/console). In `Configuration` tab, in section `Advanced Features` select `Generate user access tokens`. Do not forget to re-authorize application if it was already authorized. To obtain user account you will have to provide user ID with client id and secret. ``` import BoxSdkGen let config = CCGConfig( clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", userId: "YOUR_USER_ID" ) let auth = BoxCCGAuth(config: config) let client = BoxClient(auth: auth) ``` ### Switching between Service Account and User In order to switch between being authenticated as Service Account and a User you can call: ``` let enterpriseAuth = auth.withEnterpriseSubject(enterpriseId: "YOUR_ENTERPRISE_ID") let enterpriseClient = BoxClient(auth: enterpriseAuth) ``` to authenticate as enterprise or ``` let userAuth = auth.withUserSubject(userId: "YOUR_USER_ID") let userClient = BoxClient(auth: userAuth) ``` to authenticate as User with provided ID. The new token will be automatically fetched with a next API call. ## OAuth 2.0 Auth If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/en/guides/authentication/oauth2/). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. ### Login flow (recommended) The SDK provides a built-in flow for opening a secure web view, into which the user enters their Box login credentials. This requires that the application using the SDK registers itself for a custom URL scheme of the format `boxsdk-<<CLIENT ID>>://boxsdkoauth2redirect`. ``` do { // Initialize configuration with required clientId and clientSecret let config = OAuthConfig(clientId: "<<YOUR CLIENT ID HERE>>", clientSecret: "<<YOUR CLIENT SECRET HERE>>") // Initialize BoxOAuth with configuration let oauth = BoxOAuth(config: config) // Run login flow which opens a secure web view, // where users enter their login credentials to obtain an authorization code, // which is then exchanged for an access token. try await oauth.runLoginFlow(options: .init(), context: self) // Initialize BoxClient with already authorized OAuth let client = BoxClient(auth: oauth) // Use client to make API calls let folder = try await client.folders.getFolderById(folderId: "<<YOUR_FOLDER_ID>>") } catch { print("An error occurred: \(error)") } ``` If your application requires a custom URL scheme that differs from the default format `boxsdk-<<CLIENT ID>>://boxsdkoauth2redirect`, you have the option to pass in a custom `redirectUri` string when running the `runLoginFlow()` method: ``` try await oauth.runLoginFlow(options: AuthorizeUrlParams(redirectUri: "my-custom-scheme://redirect"), context: self) ``` This is the URL to which Box will redirect the user when authentication completes. This requires that the application using the SDK registers itself for the same custom callback URL. When running the `runLoginFlow(options:context:)` method, the *context* parameter is required. It's specify the context to target where in an application's UI the authorization view should be shown. This parameter is of type `ASWebAuthenticationPresentationContextProviding`, so in order to pass it, you have to adopt the mentioned `ASWebAuthenticationPresentationContextProviding` protocol. If you are running your code from the ViewController, you can add the following code to it: ``` extension ViewController: ASWebAuthenticationPresentationContextProviding { func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { return view.window! } } ``` Then in the `context` argument, just pass self as we did in the previous examples. ### Manual flow As an alternative to login flow, where everything is done automatically, you can use the manual one. This flow requires you to actively obtain an authorization code and pass it to the OAuth for the purpose of exchanging it for an Access Token. To initiate this flow, you need to create the `authorizationUrl`, based on provided client data, and redirect to this url the user. ``` let auth = BoxOAuth(config: OAuthConfig(clientId: "<<YOUR CLIENT ID HERE>>", clientSecret: "<<YOUR CLIENT SECRET HERE>>") ) let authorizationUrl = auth.getAuthorizeUrl() ``` After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirectUri` which will contain an authorization code. This code can then be used along with your client ID and client secret to establish an API connection. You need to provide the auth code to the SDK to obtain an access token. Calling `auth.getTokensAuthorizationCodeGrant(authorizationCode: "<<YOUR_AUTHORIZATION_CODE>>")` will exchange the auth code for an access token and save it in the `BoxOAuth` token storage. The SDK will automatically refresh the token when needed. All you need to do is create a client object with the `BoxOAuth` object and start making API calls. ``` try await auth.retrieveToken(); ``` # Refresh access token Access tokens are short-lived and need to be refreshed periodically. The SDK will automatically refresh the token when needed. If you want to manually refresh the token, you can use the following code: ``` try await auth.refreshToken(); ``` # Revoke token Access tokens for a client can be revoked when needed. This call invalidates old token. For BoxCCGAuth you can still reuse the `auth` object to retrieve a new token. If you make any new call after revoking the token, a new token will be automatically retrieved. For BoxOAuth it would be necessary to manually go through the authentication process again. For BoxDeveloperTokenAuth, it is necessary to provide a DeveloperTokenConfig during initialization, containing the client ID and client secret. To revoke current client's tokens in the storage use the following code: ``` try await auth.revokeToken() ``` # Downscope token You can exchange an access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). A downscoped token does not include a refresh token. In that case, to get a new downscoped token, refresh the original refresh token and use that new token to get a downscoped token. More information about downscoping tokens can be found [here](https://developer.box.com/guides/authentication/tokens/downscope/). If you want to learn more about available scopes please go [here](https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/#scopes-for-downscoping). For example to get a new token with only `item_preview` scope, restricted to a single file, suitable for the [Content Preview UI Element](https://developer.box.com/en/guides/embed/ui-elements/preview/) you can the following code: You can also initialize `BoxDeveloperTokenAuth` with the retrieved access token and use it to create a new Client. ``` let resource = "https://api.box.com/2.0/files/123456789" let downscopedToken: AccessToken = try await auth.downscopeToken(scopes: ["item_preview"], resource: resource) let downscopedAuth = BoxDeveloperTokenAuth(token: downscopedToken.accessToken!) let downscopedClient = BoxClient(auth: downscopedAuth) ``` # Token storage ## In-memory token storage By default, the SDK stores the access token in volatile memory. When rerunning your application, the access token won't be reused from the previous run; a new token has to be obtained again. To use in-memory token storage, you don't need to do anything more than create an Auth class using AuthConfig, for example, for BoxOAuth: ``` let auth = BoxOAuth(config: OAuthConfig(clientId: "<<YOUR CLIENT ID HERE>>", clientSecret: "<<YOUR CLIENT SECRET HERE>>") ) ``` ## Keychain token storage If you want to keep an up-to-date access token on Apple's device Keychain, allowing it to be reused after rerunning your application, you can use the `KeychainTokenStorage` class. To enable storing the token in Keychain, you need to pass an object of type `KeychainTokenStorage` to the AuthConfig class. For example, for BoxOAuth: ``` // Initialize configuration with required clientId, clientSecret and tokenStorage let config = OAuthConfig(clientId: "<<YOUR CLIENT ID HERE>>", clientSecret: "<<YOUR CLIENT SECRET HERE>>", tokenStorage: KeychainTokenStorage()) // Initialize OAuth with configuration let oauth = BoxOAuth(config: config) // Initialize BoxClient let client = BoxClient(auth: oauth) // In the case of BoxOAuth authorization, if there is no access token in the keychain, // you must run the `runLoginFlow` process to retrieve the token which will be automatically stored in TokenStorage. if try! await storage.get() == nil { try await oauth.runLoginFlow(options: AuthorizeUrlParams(redirectUri: "my-custom-scheme://redirect"), context: self) } ``` ## Custom storage You can also provide a custom token storage class. All you need to do is create a class that implements `TokenStorage` protocol and pass an instance of your class to the AuthConfig constructor. ``` class MyCustomTokenStorage: TokenStorage { func store(token: AccessToken) async throws { // store token in your custom storage } func get() async throws -> AccessToken? { // retrieve token from your custom storage } func clear() async throws { // clear token from your custom storage } } let auth = BoxOAuth(config: OAuthConfig( clientId: "<<YOUR CLIENT ID HERE>>", clientSecret: "<<YOUR CLIENT SECRET HERE>>", tokenStorage: MyCustomTokenStorage() ) ) ``` --- ## Untitled *Type: page* ClassificationsManager List all classifications Add classification Update classification Add initial classifications List all… # ClassificationsManager - [List all classifications](#list-all-classifications) - [Add classification](#add-classification) - [Update classification](#update-classification) - [Add initial classifications](#add-initial-classifications) ## List all classifications Retrieves the classification metadata template and lists all the classifications available to this enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `getClassificationTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema/). ``` try await client.classifications.getClassificationTemplate() ``` ### Arguments headers `GetClassificationTemplateHeaders` - Headers of getClassificationTemplate method ### Returns This function returns a value of type `ClassificationTemplate`. Returns the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification Adds one or more new classifications to the list of classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `addClassification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--add/). ``` try await client.classifications.addClassification(requestBody: [AddClassificationRequestBody(data: AddClassificationRequestBodyDataField(key: Utils.getUUID(), staticConfig: AddClassificationRequestBodyDataStaticConfigField(classification: AddClassificationRequestBodyDataStaticConfigClassificationField(colorId: Int64(4), classificationDefinition: "Other description"))))]) ``` ### Arguments requestBody `[AddClassificationRequestBody]` - Request body of addClassification method headers `AddClassificationHeaders` - Headers of addClassification method ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Update classification Updates the labels and descriptions of one or more classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `updateClassification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--update/). ``` try await client.classifications.updateClassification(requestBody: [UpdateClassificationRequestBody(enumOptionKey: classification.key, data: UpdateClassificationRequestBodyDataField(key: updatedClassificationName, staticConfig: UpdateClassificationRequestBodyDataStaticConfigField(classification: UpdateClassificationRequestBodyDataStaticConfigClassificationField(colorId: Int64(2), classificationDefinition: updatedClassificationDescription))))]) ``` ### Arguments requestBody `[UpdateClassificationRequestBody]` - Request body of updateClassification method headers `UpdateClassificationHeaders` - Headers of updateClassification method ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add initial classifications When an enterprise does not yet have any classifications, this API call initializes the classification template with an initial set of classifications. If an enterprise already has a classification, the template will already exist and instead an API call should be made to add additional classifications. This operation is performed by calling function `createClassificationTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema--classifications/). *Currently we don't have an example for calling `createClassificationTemplate` in integration tests* ### Arguments requestBody `CreateClassificationTemplateRequestBody` - Request body of createClassificationTemplate method headers `CreateClassificationTemplateHeaders` - Headers of createClassificationTemplate method ### Returns This function returns a value of type `ClassificationTemplate`. Returns a new `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. --- ## Untitled *Type: page* ChunkedUploadsManager This is a manager for chunked uploads (allowed for files at least 20MB). Create upload session Create upload session… # ChunkedUploadsManager This is a manager for chunked uploads (allowed for files at least 20MB). - [Create upload session](#create-upload-session) - [Create upload session for existing file](#create-upload-session-for-existing-file) - [Get upload session by URL](#get-upload-session-by-url) - [Get upload session](#get-upload-session) - [Upload part of file by URL](#upload-part-of-file-by-url) - [Upload part of file](#upload-part-of-file) - [Remove upload session by URL](#remove-upload-session-by-url) - [Remove upload session](#remove-upload-session) - [List parts by URL](#list-parts-by-url) - [List parts](#list-parts) - [Commit upload session by URL](#commit-upload-session-by-url) - [Commit upload session](#commit-upload-session) - [Upload big file](#upload-big-file) ## Create upload session Creates an upload session for a new file. This operation is performed by calling function `createFileUploadSession`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions/). ``` try await client.chunkedUploads.createFileUploadSession(requestBody: CreateFileUploadSessionRequestBody(fileName: fileName, fileSize: Int64(fileSize), folderId: parentFolderId)) ``` ### Arguments requestBody `CreateFileUploadSessionRequestBody` - Request body of createFileUploadSession method headers `CreateFileUploadSessionHeaders` - Headers of createFileUploadSession method ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Create upload session for existing file Creates an upload session for an existing file. This operation is performed by calling function `createFileUploadSessionForExistingFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-upload-sessions/). *Currently we don't have an example for calling `createFileUploadSessionForExistingFile` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CreateFileUploadSessionForExistingFileRequestBody` - Request body of createFileUploadSessionForExistingFile method headers `CreateFileUploadSessionForExistingFileHeaders` - Headers of createFileUploadSessionForExistingFile method ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Get upload session by URL Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `getFileUploadSessionByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` try await client.chunkedUploads.getFileUploadSessionByUrl(url: statusUrl) ``` ### Arguments url `String` - URL of getFileUploadSessionById method headers `GetFileUploadSessionByUrlHeaders` - Headers of getFileUploadSessionById method ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Get upload session Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `getFileUploadSessionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` try await client.chunkedUploads.getFileUploadSessionById(uploadSessionId: uploadSessionId) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" headers `GetFileUploadSessionByIdHeaders` - Headers of getFileUploadSessionById method ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Upload part of file by URL Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `uploadFilePartByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` try await client.chunkedUploads.uploadFilePartByUrl(url: acc.uploadPartUrl, requestBody: Utils.generateByteStreamFromBuffer(buffer: chunkBuffer), headers: UploadFilePartByUrlHeaders(digest: digest, contentRange: contentRange)) ``` ### Arguments url `String` - URL of uploadFilePart method requestBody `InputStream` - Request body of uploadFilePart method headers `UploadFilePartByUrlHeaders` - Headers of uploadFilePart method ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Upload part of file Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `uploadFilePart`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` try await client.chunkedUploads.uploadFilePart(uploadSessionId: acc.uploadSessionId, requestBody: Utils.generateByteStreamFromBuffer(buffer: chunkBuffer), headers: UploadFilePartHeaders(digest: digest, contentRange: contentRange)) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" requestBody `InputStream` - Request body of uploadFilePart method headers `UploadFilePartHeaders` - Headers of uploadFilePart method ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Remove upload session by URL Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `deleteFileUploadSessionByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` try await client.chunkedUploads.deleteFileUploadSessionByUrl(url: abortUrl) ``` ### Arguments url `String` - URL of deleteFileUploadSessionById method headers `DeleteFileUploadSessionByUrlHeaders` - Headers of deleteFileUploadSessionById method ### Returns This function returns a value of type ``. A blank response is returned if the session was successfully aborted. ## Remove upload session Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `deleteFileUploadSessionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` try await client.chunkedUploads.deleteFileUploadSessionById(uploadSessionId: uploadSessionId) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" headers `DeleteFileUploadSessionByIdHeaders` - Headers of deleteFileUploadSessionById method ### Returns This function returns a value of type ``. A blank response is returned if the session was successfully aborted. ## List parts by URL Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `getFileUploadSessionPartsByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` try await client.chunkedUploads.getFileUploadSessionPartsByUrl(url: listPartsUrl) ``` ### Arguments url `String` - URL of getFileUploadSessionParts method queryParams `GetFileUploadSessionPartsByUrlQueryParams` - Query parameters of getFileUploadSessionParts method headers `GetFileUploadSessionPartsByUrlHeaders` - Headers of getFileUploadSessionParts method ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## List parts Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `getFileUploadSessionParts`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` try await client.chunkedUploads.getFileUploadSessionParts(uploadSessionId: uploadSessionId) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" queryParams `GetFileUploadSessionPartsQueryParams` - Query parameters of getFileUploadSessionParts method headers `GetFileUploadSessionPartsHeaders` - Headers of getFileUploadSessionParts method ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## Commit upload session by URL Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `createFileUploadSessionCommitByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` try await client.chunkedUploads.createFileUploadSessionCommitByUrl(url: commitUrl, requestBody: CreateFileUploadSessionCommitByUrlRequestBody(parts: parts), headers: CreateFileUploadSessionCommitByUrlHeaders(digest: digest)) ``` ### Arguments url `String` - URL of createFileUploadSessionCommit method requestBody `CreateFileUploadSessionCommitByUrlRequestBody` - Request body of createFileUploadSessionCommit method headers `CreateFileUploadSessionCommitByUrlHeaders` - Headers of createFileUploadSessionCommit method ### Returns This function returns a value of type `Files?`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Commit upload session Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `createFileUploadSessionCommit`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` try await client.chunkedUploads.createFileUploadSessionCommit(uploadSessionId: uploadSessionId, requestBody: CreateFileUploadSessionCommitRequestBody(parts: parts), headers: CreateFileUploadSessionCommitHeaders(digest: digest)) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" requestBody `CreateFileUploadSessionCommitRequestBody` - Request body of createFileUploadSessionCommit method headers `CreateFileUploadSessionCommitHeaders` - Headers of createFileUploadSessionCommit method ### Returns This function returns a value of type `Files?`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Upload big file Starts the process of chunk uploading a big file. Should return a File object representing uploaded file. This operation is performed by calling function `uploadBigFile`. ``` try await client.chunkedUploads.uploadBigFile(file: fileByteStream, fileName: fileName, fileSize: Int64(fileSize), parentFolderId: parentFolderId) ``` ### Arguments file `InputStream` - The stream of the file to upload. fileName `String` - The name of the file, which will be used for storage in Box. fileSize `Int64` - The total size of the file for the chunked upload in bytes. parentFolderId `String` - The ID of the folder where the file should be uploaded. ### Returns This function returns a value of type `FileFull`. --- ## Untitled *Type: page* Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers… # Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers. - [Client](#client) [Make custom HTTP request](#make-custom-http-request) - [JSON request](#json-request) - [Multi-part request](#multi-part-request) - [Binary response](#binary-response) [Additional headers](#additional-headers) - [As-User header](#as-user-header) - [Suppress notifications](#suppress-notifications) - [Custom headers](#custom-headers) [Custom Base URLs](#custom-base-urls) # Make custom HTTP request You can make custom HTTP requests using the `client.makeRequest()` method. This method allows you to make any HTTP request to the Box API. It will automatically use authentication and network configuration settings from the client. The method accepts a `FetchOptions` object as an argument and returns a `FetchResponse` object. ## JSON request The following example demonstrates how to make a custom POST request to create a new folder in the root folder. ``` let requestBodyPost: String = "\("{\"name\": \"myFolderName\", \"parent\": { \"id\": \"0\"}}")" let response: FetchResponse = try await client.makeRequest( fetchOptions: FetchOptions( url: "https://api.box.com/2.0/folders", method: "POST", data: JsonUtils.jsonToSerializedData(text: requestBodyPost) ) ) let responseContent = String(data: response.data?.data ?? Data(), encoding: .utf8) ?? "" print("Received status code: \(response.status)") print("Response content: \(responseContent)") // We can also deserialize the response content to json dictionary so we can access the values by key if let jsonDict = JsonUtils.sdToJsonDictionary(from: response.data) { print("Created folder name: \(jsonDict["name"] ?? "")" ) } ``` ## Multi-part request The following example demonstrates how to make a custom multipart request that uploads a file to a folder. ``` let multipartAttributes: String = "\("{\"name\": \"newFileName\", \"parent\": { \"id\":\"0\"}}")" guard let fileContentStream = InputStream(url: URL(string: "<URL_TO_YOUR_FILE>")!) else { fatalError("Could not read a file") } let multipartItems = [ MultipartItem(partName: "attributes", data: JsonUtils.jsonToSerializedData(text: multipartAttributes)), MultipartItem(partName: "file", fileStream: fileContentStream) ] let response: FetchResponse = try await client.makeRequest( fetchOptions: FetchOptions( url: "https://upload.box.com/api/2.0/files/content", method: "POST", multipartData: multipartItems, contentType: "multipart/form-data" ) ) print("Received status code: \(response.status)") ``` ## Binary response The following example demonstrates how to make a custom request to download a file. You must specify the `responseFormat` parameter in the `FetchOptions` object as `ResponseFormat.binary` and set the `downloadDestinationUrl` parameter to indicate where the file should be saved. ``` // Path to the file where the downloaded content will be saved let downloadPathString: String = "\(Utils.temporaryDirectoryPath())\(Utils.getUUID())" let fileId = "123456789"; let response: FetchResponse = try await client.makeRequest( fetchOptions: FetchOptions( url: "\("https://api.box.com/2.0/files/")\(fileId)\("/content")", method: "GET", responseFormat: ResponseFormat.binary, downloadDestinationUrl: URL(path: downloadPathString) ) ) print("Received status code: \(response.status)") // If the request is successful, the file content will be saved to the specified path if response.status == 200 { if let url = URL(string: downloadPathString), let data = try? Data(contentsOf: url){ print("File content: \(String(decoding: data, as: UTF8.self))") } } ``` # Additional headers BoxClient provides a convenient method, which allow passing additional headers, which will be included in every API call made by the client. ## As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an As-User: USER-ID header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). The following example assume that the client has been instantiated with an access token belonging to an admin-level user or Service Account with appropriate privileges to make As-User calls. Calling the `client.withAsUserHeader()` method creates a new client to impersonate user with the provided ID. All calls made with the new client will be made in context of the impersonated user, leaving the original client unmodified. ``` let userClient = client.withAsUserHeader(userId: '1234567') ``` ## Suppress notifications If you are making administrative API calls (that is, your application has “Manage an Enterprise” scope, and the user signing in is a co-admin with the correct "Edit settings for your company" permission) then you can suppress both email and webhook notifications. This can be used, for example, for a virus-scanning tool to download copies of everyone’s files in an enterprise, without every collaborator on the file getting an email. All actions will still appear in users' updates feed and audit logs. **Note:** This functionality is only available for approved applications. Calling the `client.withSuppressedNotifications()` method creates a new client. For all calls made with the new client the notifications will be suppressed. ``` let newClient = client.withSuppressedNotifications() ``` ## Custom headers You can also specify the custom set of headers, which will be included in every API call made by client. Calling the `client.withExtraHeaders()` method creates a new client, leaving the original client unmodified. ``` let newClient = client.withExtraHeaders(extraHeaders: ["customHeader": "customValue"]) ``` # Custom Base URLs You can also specify the custom base URLs, which will be used for API calls made by client. Calling the `client.withCustomBaseUrls()` method creates a new client, leaving the original client unmodified. ``` let newClient = client.withCustomBaseUrls(baseUrls: BaseUrls( baseUrl: "https://api.box.com", uploadUrl: "https://upload.box.com/api", oauth2Url: "https://account.box.com/api/oauth2" )) ``` --- ## Untitled *Type: page* CollaborationAllowlistExemptTargetsManager List users exempt from collaboration domain restrictions Create user exemption from collaboration… # CollaborationAllowlistExemptTargetsManager - [List users exempt from collaboration domain restrictions](#list-users-exempt-from-collaboration-domain-restrictions) - [Create user exemption from collaboration domain restrictions](#create-user-exemption-from-collaboration-domain-restrictions) - [Get user exempt from collaboration domain restrictions](#get-user-exempt-from-collaboration-domain-restrictions) - [Remove user from list of users exempt from domain restrictions](#remove-user-from-list-of-users-exempt-from-domain-restrictions) ## List users exempt from collaboration domain restrictions Returns a list of users who have been exempt from the collaboration domain restrictions. This operation is performed by calling function `getCollaborationWhitelistExemptTargets`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets/). ``` try await client.collaborationAllowlistExemptTargets.getCollaborationWhitelistExemptTargets() ``` ### Arguments queryParams `GetCollaborationWhitelistExemptTargetsQueryParams` - Query parameters of getCollaborationWhitelistExemptTargets method headers `GetCollaborationWhitelistExemptTargetsHeaders` - Headers of getCollaborationWhitelistExemptTargets method ### Returns This function returns a value of type `CollaborationAllowlistExemptTargets`. Returns a collection of user exemptions. ## Create user exemption from collaboration domain restrictions Exempts a user from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `createCollaborationWhitelistExemptTarget`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-exempt-targets/). ``` try await client.collaborationAllowlistExemptTargets.createCollaborationWhitelistExemptTarget(requestBody: CreateCollaborationWhitelistExemptTargetRequestBody(user: CreateCollaborationWhitelistExemptTargetRequestBodyUserField(id: user.id))) ``` ### Arguments requestBody `CreateCollaborationWhitelistExemptTargetRequestBody` - Request body of createCollaborationWhitelistExemptTarget method headers `CreateCollaborationWhitelistExemptTargetHeaders` - Headers of createCollaborationWhitelistExemptTarget method ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns a new exemption entry. ## Get user exempt from collaboration domain restrictions Returns a users who has been exempt from the collaboration domain restrictions. This operation is performed by calling function `getCollaborationWhitelistExemptTargetById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets-id/). ``` try await client.collaborationAllowlistExemptTargets.getCollaborationWhitelistExemptTargetById(collaborationWhitelistExemptTargetId: newExemptTarget.id!) ``` ### Arguments collaborationWhitelistExemptTargetId `String` - The ID of the exemption to the list. Example: "984923" headers `GetCollaborationWhitelistExemptTargetByIdHeaders` - Headers of getCollaborationWhitelistExemptTargetById method ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns the user's exempted from the list of collaboration domains. ## Remove user from list of users exempt from domain restrictions Removes a user's exemption from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `deleteCollaborationWhitelistExemptTargetById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-exempt-targets-id/). ``` try await client.collaborationAllowlistExemptTargets.deleteCollaborationWhitelistExemptTargetById(collaborationWhitelistExemptTargetId: exemptTarget.id!) ``` ### Arguments collaborationWhitelistExemptTargetId `String` - The ID of the exemption to the list. Example: "984923" headers `DeleteCollaborationWhitelistExemptTargetByIdHeaders` - Headers of deleteCollaborationWhitelistExemptTargetById method ### Returns This function returns a value of type ``. A blank response is returned if the exemption was successfully deleted. --- ## Untitled *Type: page* CollaborationAllowlistEntriesManager List allowed collaboration domains Add domain to list of allowed collaboration domains Get allowed… # CollaborationAllowlistEntriesManager - [List allowed collaboration domains](#list-allowed-collaboration-domains) - [Add domain to list of allowed collaboration domains](#add-domain-to-list-of-allowed-collaboration-domains) - [Get allowed collaboration domain](#get-allowed-collaboration-domain) - [Remove domain from list of allowed collaboration domains](#remove-domain-from-list-of-allowed-collaboration-domains) ## List allowed collaboration domains Returns the list domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `getCollaborationWhitelistEntries`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries/). ``` try await client.collaborationAllowlistEntries.getCollaborationWhitelistEntries() ``` ### Arguments queryParams `GetCollaborationWhitelistEntriesQueryParams` - Query parameters of getCollaborationWhitelistEntries method headers `GetCollaborationWhitelistEntriesHeaders` - Headers of getCollaborationWhitelistEntries method ### Returns This function returns a value of type `CollaborationAllowlistEntries`. Returns a collection of domains that are allowed for collaboration. ## Add domain to list of allowed collaboration domains Creates a new entry in the list of allowed domains to allow collaboration for. This operation is performed by calling function `createCollaborationWhitelistEntry`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-entries/). ``` try await client.collaborationAllowlistEntries.createCollaborationWhitelistEntry(requestBody: CreateCollaborationWhitelistEntryRequestBody(direction: CreateCollaborationWhitelistEntryRequestBodyDirectionField.inbound, domain: domain)) ``` ### Arguments requestBody `CreateCollaborationWhitelistEntryRequestBody` - Request body of createCollaborationWhitelistEntry method headers `CreateCollaborationWhitelistEntryHeaders` - Headers of createCollaborationWhitelistEntry method ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns a new entry on the list of allowed domains. ## Get allowed collaboration domain Returns a domain that has been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `getCollaborationWhitelistEntryById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries-id/). ``` try await client.collaborationAllowlistEntries.getCollaborationWhitelistEntryById(collaborationWhitelistEntryId: newEntry.id!) ``` ### Arguments collaborationWhitelistEntryId `String` - The ID of the entry in the list. Example: "213123" headers `GetCollaborationWhitelistEntryByIdHeaders` - Headers of getCollaborationWhitelistEntryById method ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns an entry on the list of allowed domains. ## Remove domain from list of allowed collaboration domains Removes a domain from the list of domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `deleteCollaborationWhitelistEntryById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-entries-id/). ``` try await client.collaborationAllowlistEntries.deleteCollaborationWhitelistEntryById(collaborationWhitelistEntryId: entry.id!) ``` ### Arguments collaborationWhitelistEntryId `String` - The ID of the entry in the list. Example: "213123" headers `DeleteCollaborationWhitelistEntryByIdHeaders` - Headers of deleteCollaborationWhitelistEntryById method ### Returns This function returns a value of type ``. A blank response is returned if the entry was successfully deleted. --- ## Untitled *Type: page* CollectionsManager List all collections List collection items Get collection by ID List all collections Retrieves all collections for a… # CollectionsManager - [List all collections](#list-all-collections) - [List collection items](#list-collection-items) - [Get collection by ID](#get-collection-by-id) ## List all collections Retrieves all collections for a given user. Currently, only the `favorites` collection is supported. This operation is performed by calling function `getCollections`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections/). ``` try await client.collections.getCollections() ``` ### Arguments queryParams `GetCollectionsQueryParams` - Query parameters of getCollections method headers `GetCollectionsHeaders` - Headers of getCollections method ### Returns This function returns a value of type `Collections`. Returns all collections for the given user. ## List collection items Retrieves the files and/or folders contained within this collection. This operation is performed by calling function `getCollectionItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id-items/). ``` try await client.collections.getCollectionItems(collectionId: favouriteCollection.id!) ``` ### Arguments collectionId `String` - The ID of the collection. Example: "926489" queryParams `GetCollectionItemsQueryParams` - Query parameters of getCollectionItems method headers `GetCollectionItemsHeaders` - Headers of getCollectionItems method ### Returns This function returns a value of type `ItemsOffsetPaginated`. Returns an array of items in the collection. ## Get collection by ID Retrieves a collection by its ID. This operation is performed by calling function `getCollectionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id/). ``` try await client.collections.getCollectionById(collectionId: collections.entries![0].id!) ``` ### Arguments collectionId `String` - The ID of the collection. Example: "926489" headers `GetCollectionByIdHeaders` - Headers of getCollectionById method ### Returns This function returns a value of type `Collection`. Returns an array of items in the collection. --- ## Untitled *Type: page* CommentsManager List file comments Get comment Update comment Remove comment Create comment List file comments Retrieves a list of comments… # CommentsManager - [List file comments](#list-file-comments) - [Get comment](#get-comment) - [Update comment](#update-comment) - [Remove comment](#remove-comment) - [Create comment](#create-comment) ## List file comments Retrieves a list of comments for a file. This operation is performed by calling function `getFileComments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-comments/). ``` try await client.comments.getFileComments(fileId: fileId) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileCommentsQueryParams` - Query parameters of getFileComments method headers `GetFileCommentsHeaders` - Headers of getFileComments method ### Returns This function returns a value of type `Comments`. Returns a collection of comment objects. If there are no comments on this file an empty collection will be returned. ## Get comment Retrieves the message and metadata for a specific comment, as well as information on the user who created the comment. This operation is performed by calling function `getCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-comments-id/). ``` try await client.comments.getCommentById(commentId: newComment.id!) ``` ### Arguments commentId `String` - The ID of the comment. Example: "12345" queryParams `GetCommentByIdQueryParams` - Query parameters of getCommentById method headers `GetCommentByIdHeaders` - Headers of getCommentById method ### Returns This function returns a value of type `CommentFull`. Returns a full comment object. ## Update comment Update the message of a comment. This operation is performed by calling function `updateCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-comments-id/). ``` try await client.comments.updateCommentById(commentId: newReplyComment.id!, requestBody: UpdateCommentByIdRequestBody(message: newMessage)) ``` ### Arguments commentId `String` - The ID of the comment. Example: "12345" requestBody `UpdateCommentByIdRequestBody` - Request body of updateCommentById method queryParams `UpdateCommentByIdQueryParams` - Query parameters of updateCommentById method headers `UpdateCommentByIdHeaders` - Headers of updateCommentById method ### Returns This function returns a value of type `CommentFull`. Returns the updated comment object. ## Remove comment Permanently deletes a comment. This operation is performed by calling function `deleteCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-comments-id/). ``` try await client.comments.deleteCommentById(commentId: newComment.id!) ``` ### Arguments commentId `String` - The ID of the comment. Example: "12345" headers `DeleteCommentByIdHeaders` - Headers of deleteCommentById method ### Returns This function returns a value of type ``. Returns an empty response when the comment has been deleted. ## Create comment Adds a comment by the user to a specific file, or as a reply to an other comment. This operation is performed by calling function `createComment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-comments/). ``` try await client.comments.createComment(requestBody: CreateCommentRequestBody(message: message, item: CreateCommentRequestBodyItemField(id: fileId, type: CreateCommentRequestBodyItemTypeField.file))) ``` ### Arguments requestBody `CreateCommentRequestBody` - Request body of createComment method queryParams `CreateCommentQueryParams` - Query parameters of createComment method headers `CreateCommentHeaders` - Headers of createComment method ### Returns This function returns a value of type `CommentFull`. Returns the newly created comment object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* DevicePinnersManager Get device pin Remove device pin List enterprise device pins Get device pin Retrieves information about an individual… # DevicePinnersManager - [Get device pin](#get-device-pin) - [Remove device pin](#remove-device-pin) - [List enterprise device pins](#list-enterprise-device-pins) ## Get device pin Retrieves information about an individual device pin. This operation is performed by calling function `getDevicePinnerById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-device-pinners-id/). ``` try await client.devicePinners.getDevicePinnerById(devicePinnerId: devicePinnerId) ``` ### Arguments devicePinnerId `String` - The ID of the device pin. Example: "2324234" headers `GetDevicePinnerByIdHeaders` - Headers of getDevicePinnerById method ### Returns This function returns a value of type `DevicePinner`. Returns information about a single device pin. ## Remove device pin Deletes an individual device pin. This operation is performed by calling function `deleteDevicePinnerById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-device-pinners-id/). ``` try await client.devicePinners.deleteDevicePinnerById(devicePinnerId: devicePinnerId) ``` ### Arguments devicePinnerId `String` - The ID of the device pin. Example: "2324234" headers `DeleteDevicePinnerByIdHeaders` - Headers of deleteDevicePinnerById method ### Returns This function returns a value of type ``. Returns an empty response when the pin has been deleted. ## List enterprise device pins Retrieves all the device pins within an enterprise. The user must have admin privileges, and the application needs the "manage enterprise" scope to make this call. This operation is performed by calling function `getEnterpriseDevicePinners`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-enterprises-id-device-pinners/). ``` try await client.devicePinners.getEnterpriseDevicePinners(enterpriseId: enterpriseId) ``` ### Arguments enterpriseId `String` - The ID of the enterprise. Example: "3442311" queryParams `GetEnterpriseDevicePinnersQueryParams` - Query parameters of getEnterpriseDevicePinners method headers `GetEnterpriseDevicePinnersHeaders` - Headers of getEnterpriseDevicePinners method ### Returns This function returns a value of type `DevicePinners`. Returns a list of device pins for a given enterprise. --- ## Untitled *Type: page* DocgenManager Get Box Doc Gen job by ID List all Box Doc Gen jobs Get Box Doc Gen jobs by batch ID Generate document using Box Doc Gen… # DocgenManager - [Get Box Doc Gen job by ID](#get-box-doc-gen-job-by-id) - [List all Box Doc Gen jobs](#list-all-box-doc-gen-jobs) - [Get Box Doc Gen jobs by batch ID](#get-box-doc-gen-jobs-by-batch-id) - [Generate document using Box Doc Gen template](#generate-document-using-box-doc-gen-template) ## Get Box Doc Gen job by ID Get details of the Box Doc Gen job. This operation is performed by calling function `getDocgenJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs-id/). ``` try await client.docgen.getDocgenJobByIdV2025R0(jobId: docgenJobItemFromList.id) ``` ### Arguments jobId `String` - Box Doc Gen job ID. Example: 123 headers `GetDocgenJobByIdV2025R0Headers` - Headers of getDocgenJobByIdV2025R0 method ### Returns This function returns a value of type `DocGenJobV2025R0`. Details of the Box Doc Gen job. ## List all Box Doc Gen jobs Lists all Box Doc Gen jobs for a user. This operation is performed by calling function `getDocgenJobsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs/). ``` try await client.docgen.getDocgenJobsV2025R0(queryParams: GetDocgenJobsV2025R0QueryParams(limit: Int64(500))) ``` ### Arguments queryParams `GetDocgenJobsV2025R0QueryParams` - Query parameters of getDocgenJobsV2025R0 method headers `GetDocgenJobsV2025R0Headers` - Headers of getDocgenJobsV2025R0 method ### Returns This function returns a value of type `DocGenJobsFullV2025R0`. A list of Box Doc Gen jobs. ## Get Box Doc Gen jobs by batch ID Lists Box Doc Gen jobs in a batch. This operation is performed by calling function `getDocgenBatchJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-batch-jobs-id/). ``` try await client.docgen.getDocgenBatchJobByIdV2025R0(batchId: docgenBatch.id) ``` ### Arguments batchId `String` - Box Doc Gen batch ID. Example: 123 queryParams `GetDocgenBatchJobByIdV2025R0QueryParams` - Query parameters of getDocgenBatchJobByIdV2025R0 method headers `GetDocgenBatchJobByIdV2025R0Headers` - Headers of getDocgenBatchJobByIdV2025R0 method ### Returns This function returns a value of type `DocGenJobsV2025R0`. Returns a list of Box Doc Gen jobs in a Box Doc Gen batch. ## Generate document using Box Doc Gen template Generates a document using a Box Doc Gen template. This operation is performed by calling function `createDocgenBatchV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-batches/). ``` try await client.docgen.createDocgenBatchV2025R0(requestBody: DocGenBatchCreateRequestV2025R0(file: FileReferenceV2025R0(id: uploadedFile.id), inputSource: "api", destinationFolder: DocGenBatchCreateRequestV2025R0DestinationFolderField(id: folder.id), outputType: "pdf", documentGenerationData: [DocGenDocumentGenerationDataV2025R0(generatedFileName: "test", userInput: ["abc": "xyz"])])) ``` ### Arguments requestBody `DocGenBatchCreateRequestV2025R0` - Request body of createDocgenBatchV2025R0 method headers `CreateDocgenBatchV2025R0Headers` - Headers of createDocgenBatchV2025R0 method ### Returns This function returns a value of type `DocGenBatchBaseV2025R0`. The created Batch ID. --- ## Untitled *Type: page* Downloads Downloads module is used to download files from Box. Download a File Download a File To download a file to your device(local disk… # Downloads Downloads module is used to download files from Box. - [Download a File](#download-a-file) ## Download a File To download a file to your device(local disk), call `client.downloads.downloadFile(fileId:downloadDestinationURL:queryParams:headers)` method with the ID of the file to download and a URL to the location (including name of the file) where the file should be downloaded to. ``` let downloadsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let destinationURL = downloadsDirectoryURL.appendingPathComponent("file.txt") let url = try await client.downloads.downloadFile(fileId: file.id, downloadDestinationURL: destinationURL) if let fileContent = try? String(contentsOf: url, encoding: .utf8) { print("The content of the file: \(fileContent)") } ``` --- ## Untitled *Type: page* EmailAliasesManager List user's email aliases Create email alias Remove email alias List user's email aliases Retrieves all email aliases… # EmailAliasesManager - [List user's email aliases](#list-users-email-aliases) - [Create email alias](#create-email-alias) - [Remove email alias](#remove-email-alias) ## List user's email aliases Retrieves all email aliases for a user. The collection does not include the primary login for the user. This operation is performed by calling function `getUserEmailAliases`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-email-aliases/). ``` try await client.emailAliases.getUserEmailAliases(userId: newUser.id) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" headers `GetUserEmailAliasesHeaders` - Headers of getUserEmailAliases method ### Returns This function returns a value of type `EmailAliases`. Returns a collection of email aliases. ## Create email alias Adds a new email alias to a user account.. This operation is performed by calling function `createUserEmailAlias`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-email-aliases/). ``` try await client.emailAliases.createUserEmailAlias(userId: newUser.id, requestBody: CreateUserEmailAliasRequestBody(email: newAliasEmail)) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" requestBody `CreateUserEmailAliasRequestBody` - Request body of createUserEmailAlias method headers `CreateUserEmailAliasHeaders` - Headers of createUserEmailAlias method ### Returns This function returns a value of type `EmailAlias`. Returns the newly created email alias object. ## Remove email alias Removes an email alias from a user. This operation is performed by calling function `deleteUserEmailAliasById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-email-aliases-id/). ``` try await client.emailAliases.deleteUserEmailAliasById(userId: newUser.id, emailAliasId: newAlias.id!) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" emailAliasId `String` - The ID of the email alias. Example: "23432" headers `DeleteUserEmailAliasByIdHeaders` - Headers of deleteUserEmailAliasById method ### Returns This function returns a value of type ``. Removes the alias and returns an empty response. --- ## Untitled *Type: page* DocgenTemplateManager Create Box Doc Gen template List Box Doc Gen templates Delete Box Doc Gen template Get Box Doc Gen template by ID List… # DocgenTemplateManager - [Create Box Doc Gen template](#create-box-doc-gen-template) - [List Box Doc Gen templates](#list-box-doc-gen-templates) - [Delete Box Doc Gen template](#delete-box-doc-gen-template) - [Get Box Doc Gen template by ID](#get-box-doc-gen-template-by-id) - [List all Box Doc Gen template tags in template](#list-all-box-doc-gen-template-tags-in-template) - [Get list of all Box Doc Gen jobs for template](#get-list-of-all-box-doc-gen-jobs-for-template) ## Create Box Doc Gen template Marks a file as a Box Doc Gen template. This operation is performed by calling function `createDocgenTemplateV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-templates/). ``` try await client.docgenTemplate.createDocgenTemplateV2025R0(requestBody: DocGenTemplateCreateRequestV2025R0(file: FileReferenceV2025R0(id: file.id))) ``` ### Arguments requestBody `DocGenTemplateCreateRequestV2025R0` - Request body of createDocgenTemplateV2025R0 method headers `CreateDocgenTemplateV2025R0Headers` - Headers of createDocgenTemplateV2025R0 method ### Returns This function returns a value of type `DocGenTemplateBaseV2025R0`. The file which has now been marked as a Box Doc Gen template. ## List Box Doc Gen templates Lists Box Doc Gen templates on which the user is a collaborator. This operation is performed by calling function `getDocgenTemplatesV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates/). ``` try await client.docgenTemplate.getDocgenTemplatesV2025R0() ``` ### Arguments queryParams `GetDocgenTemplatesV2025R0QueryParams` - Query parameters of getDocgenTemplatesV2025R0 method headers `GetDocgenTemplatesV2025R0Headers` - Headers of getDocgenTemplatesV2025R0 method ### Returns This function returns a value of type `DocGenTemplatesV2025R0`. Returns a collection of templates. ## Delete Box Doc Gen template Unmarks file as Box Doc Gen template. This operation is performed by calling function `deleteDocgenTemplateByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-docgen-templates-id/). ``` try await client.docgenTemplate.deleteDocgenTemplateByIdV2025R0(templateId: createdDocgenTemplate.file!.id) ``` ### Arguments templateId `String` - ID of the file which will no longer be marked as a Box Doc Gen template. Example: "123" headers `DeleteDocgenTemplateByIdV2025R0Headers` - Headers of deleteDocgenTemplateByIdV2025R0 method ### Returns This function returns a value of type ``. Returns an empty response when a file is no longer marked as a Box Doc Gen template. ## Get Box Doc Gen template by ID Lists details of a specific Box Doc Gen template. This operation is performed by calling function `getDocgenTemplateByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id/). ``` try await client.docgenTemplate.getDocgenTemplateByIdV2025R0(templateId: createdDocgenTemplate.file!.id) ``` ### Arguments templateId `String` - The ID of a Box Doc Gen template. Example: 123 headers `GetDocgenTemplateByIdV2025R0Headers` - Headers of getDocgenTemplateByIdV2025R0 method ### Returns This function returns a value of type `DocGenTemplateV2025R0`. Returns a template. ## List all Box Doc Gen template tags in template Lists all tags in a Box Doc Gen template. This operation is performed by calling function `getDocgenTemplateTagsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id-tags/). ``` try await client.docgenTemplate.getDocgenTemplateTagsV2025R0(templateId: fetchedDocgenTemplate.file!.id) ``` ### Arguments templateId `String` - ID of template. Example: 123 queryParams `GetDocgenTemplateTagsV2025R0QueryParams` - Query parameters of getDocgenTemplateTagsV2025R0 method headers `GetDocgenTemplateTagsV2025R0Headers` - Headers of getDocgenTemplateTagsV2025R0 method ### Returns This function returns a value of type `DocGenTagsV2025R0`. A list of document generation template tags.Processing tags for the file. ## Get list of all Box Doc Gen jobs for template Lists the users jobs which use this template. This operation is performed by calling function `getDocgenTemplateJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-template-jobs-id/). ``` try await client.docgenTemplate.getDocgenTemplateJobByIdV2025R0(templateId: fetchedDocgenTemplate.file!.id) ``` ### Arguments templateId `String` - Id of template to fetch jobs for. Example: 123 queryParams `GetDocgenTemplateJobByIdV2025R0QueryParams` - Query parameters of getDocgenTemplateJobByIdV2025R0 method headers `GetDocgenTemplateJobByIdV2025R0Headers` - Headers of getDocgenTemplateJobByIdV2025R0 method ### Returns This function returns a value of type `DocGenJobsV2025R0`. A single Box Doc Gen template. --- ## Untitled *Type: page* EventsManager Get events long poll endpoint List user and enterprise events Get events long poll endpoint Returns a list of real-time… # EventsManager - [Get events long poll endpoint](#get-events-long-poll-endpoint) - [List user and enterprise events](#list-user-and-enterprise-events) ## Get events long poll endpoint Returns a list of real-time servers that can be used for long-polling updates to the [event stream](#get-events). Long polling is the concept where a HTTP request is kept open until the server sends a response, then repeating the process over and over to receive updated responses. Long polling the event stream can only be used for user events, not for enterprise events. To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next, make a long poll request to any of the provided URLs. When an event occurs in monitored account a response with the value `new_change` will be sent. The response contains no other details as it only serves as a prompt to take further action such as sending a request to the [events endpoint](#get-events) with the last known `stream_position`. After the server sends this response it closes the connection. You must now repeat the long poll process to begin listening for events again. If no events occur for a while and the connection times out you will receive a response with the value `reconnect`. When you receive this response you’ll make another call to this endpoint to restart the process. If you receive no events in `retry_timeout` seconds then you will need to make another request to the real-time server (one of the URLs in the response for this endpoint). This might be necessary due to network errors. Finally, if you receive a `max_retries` error when making a request to the real-time server, you should start over by making a call to this endpoint first. This operation is performed by calling function `getEventsWithLongPolling`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-events/). ``` try await client.events.getEventsWithLongPolling() ``` ### Arguments headers `GetEventsWithLongPollingHeaders` - Headers of getEventsWithLongPolling method ### Returns This function returns a value of type `RealtimeServers`. Returns a paginated array of servers that can be used instead of the regular endpoints for long-polling events. ## List user and enterprise events Returns up to a year of past events for a given user or for the entire enterprise. By default this returns events for the authenticated user. To retrieve events for the entire enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events, or `admin_logs` for querying across historical events. The user making the API call will need to have admin privileges, and the application will need to have the scope `manage enterprise properties` checked. This operation is performed by calling function `getEvents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-events/). ``` try await client.events.getEvents() ``` ### Arguments queryParams `GetEventsQueryParams` - Query parameters of getEvents method headers `GetEventsHeaders` - Headers of getEvents method ### Returns This function returns a value of type `Events`. Returns a list of event objects. Events objects are returned in pages, with each page (chunk) including a list of event objects. The response includes a `chunk_size` parameter indicating how many events were returned in this chunk, as well as the next `stream_position` that can be queried. --- ## Untitled *Type: page* FileMetadataManager List metadata instances on file Get metadata instance on file Create metadata instance on file Update metadata instance… # FileMetadataManager - [List metadata instances on file](#list-metadata-instances-on-file) - [Get metadata instance on file](#get-metadata-instance-on-file) - [Create metadata instance on file](#create-metadata-instance-on-file) - [Update metadata instance on file](#update-metadata-instance-on-file) - [Remove metadata instance from file](#remove-metadata-instance-from-file) ## List metadata instances on file Retrieves all metadata for a given file. This operation is performed by calling function `getFileMetadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata/). ``` try await client.fileMetadata.getFileMetadata(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileMetadataHeaders` - Headers of getFileMetadata method ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Get metadata instance on file Retrieves the instance of a metadata template that has been applied to a file. This operation is performed by calling function `getFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-id-id/). ``` try await client.fileMetadata.getFileMetadataById(fileId: file.id, scope: GetFileMetadataByIdScope.global, templateKey: "properties") ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `GetFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `GetFileMetadataByIdHeaders` - Headers of getFileMetadataById method ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on file Applies an instance of a metadata template to a file. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. This operation is performed by calling function `createFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-id-id/). ``` try await client.fileMetadata.createFileMetadataById(fileId: file.id, scope: CreateFileMetadataByIdScope.global, templateKey: "properties", requestBody: ["abc": "xyz"]) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `CreateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `CreateFileMetadataByIdRequestBody` - Request body of createFileMetadataById method headers `CreateFileMetadataByIdHeaders` - Headers of createFileMetadataById method ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update metadata instance on file Updates a piece of metadata on a file. The metadata instance can only be updated if the template has already been applied to the file before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `updateFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-id-id/). *Currently we don't have an example for calling `updateFileMetadataById` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `UpdateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `[UpdateFileMetadataByIdRequestBody]` - Request body of updateFileMetadataById method headers `UpdateFileMetadataByIdHeaders` - Headers of updateFileMetadataById method ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from file Deletes a piece of file metadata. This operation is performed by calling function `deleteFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-id-id/). ``` try await client.fileMetadata.deleteFileMetadataById(fileId: file.id, scope: DeleteFileMetadataByIdScope.global, templateKey: "properties") ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `DeleteFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `DeleteFileMetadataByIdHeaders` - Headers of deleteFileMetadataById method ### Returns This function returns a value of type ``. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* FileClassificationsManager Get classification on file Add classification to file Update classification on file Remove classification from… # FileClassificationsManager - [Get classification on file](#get-classification-on-file) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Remove classification from file](#remove-classification-from-file) ## Get classification on file Retrieves the classification metadata instance that has been applied to a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `getClassificationOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` try await client.fileClassifications.getClassificationOnFile(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetClassificationOnFileHeaders` - Headers of getClassificationOnFile method ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to file Adds a classification to a file by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `addClassificationToFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` try await client.fileClassifications.addClassificationToFile(fileId: file.id, requestBody: AddClassificationToFileRequestBody(boxSecurityClassificationKey: classification.key)) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `AddClassificationToFileRequestBody` - Request body of addClassificationToFile method headers `AddClassificationToFileHeaders` - Headers of addClassificationToFile method ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the file. ## Update classification on file Updates a classification on a file. The classification can only be updated if a classification has already been applied to the file before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `updateClassificationOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` try await client.fileClassifications.updateClassificationOnFile(fileId: file.id, requestBody: [UpdateClassificationOnFileRequestBody(value: secondClassification.key)]) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `[UpdateClassificationOnFileRequestBody]` - Request body of updateClassificationOnFile method headers `UpdateClassificationOnFileHeaders` - Headers of updateClassificationOnFile method ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from file Removes any classifications from a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `deleteClassificationFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` try await client.fileClassifications.deleteClassificationFromFile(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteClassificationFromFileHeaders` - Headers of deleteClassificationFromFile method ### Returns This function returns a value of type ``. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* FileVersionLegalHoldsManager Get file version legal hold List file version legal holds Get file version legal hold Retrieves information… # FileVersionLegalHoldsManager - [Get file version legal hold](#get-file-version-legal-hold) - [List file version legal holds](#list-file-version-legal-holds) ## Get file version legal hold Retrieves information about the legal hold policies assigned to a file version. This operation is performed by calling function `getFileVersionLegalHoldById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds-id/). ``` try await client.fileVersionLegalHolds.getFileVersionLegalHoldById(fileVersionLegalHoldId: fileVersionLegalHoldId) ``` ### Arguments fileVersionLegalHoldId `String` - The ID of the file version legal hold. Example: "2348213" headers `GetFileVersionLegalHoldByIdHeaders` - Headers of getFileVersionLegalHoldById method ### Returns This function returns a value of type `FileVersionLegalHold`. Returns the legal hold policy assignments for the file version. ## List file version legal holds Get a list of file versions on legal hold for a legal hold assignment. Due to ongoing re-architecture efforts this API might not return all file versions for this policy ID. Instead, this API will only return file versions held in the legacy architecture. Two new endpoints will available to request any file versions held in the new architecture. For file versions held in the new architecture, the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API can be used to return all past file versions available for this policy assignment, and the `GET /legal_hold_policy_assignments/:id/files_on_hold` API can be used to return any current (latest) versions of a file under legal hold. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. Once the re-architecture is completed this API will be deprecated. This operation is performed by calling function `getFileVersionLegalHolds`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds/). ``` try await client.fileVersionLegalHolds.getFileVersionLegalHolds(queryParams: GetFileVersionLegalHoldsQueryParams(policyId: policyId)) ``` ### Arguments queryParams `GetFileVersionLegalHoldsQueryParams` - Query parameters of getFileVersionLegalHolds method headers `GetFileVersionLegalHoldsHeaders` - Headers of getFileVersionLegalHolds method ### Returns This function returns a value of type `FileVersionLegalHolds`. Returns the list of file version legal holds for a specific legal hold policy. --- ## Untitled *Type: page* FileRequestsManager Get file request Update file request Delete file request Copy file request Get file request Retrieves the information… # FileRequestsManager - [Get file request](#get-file-request) - [Update file request](#update-file-request) - [Delete file request](#delete-file-request) - [Copy file request](#copy-file-request) ## Get file request Retrieves the information about a file request. This operation is performed by calling function `getFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-requests-id/). ``` try await client.fileRequests.getFileRequestById(fileRequestId: fileRequestId) ``` ### Arguments fileRequestId `String` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" headers `GetFileRequestByIdHeaders` - Headers of getFileRequestById method ### Returns This function returns a value of type `FileRequest`. Returns a file request object. ## Update file request Updates a file request. This can be used to activate or deactivate a file request. This operation is performed by calling function `updateFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-file-requests-id/). ``` try await client.fileRequests.updateFileRequestById(fileRequestId: copiedFileRequest.id, requestBody: FileRequestUpdateRequest(title: "updated title", description: "updated description")) ``` ### Arguments fileRequestId `String` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" requestBody `FileRequestUpdateRequest` - Request body of updateFileRequestById method headers `UpdateFileRequestByIdHeaders` - Headers of updateFileRequestById method ### Returns This function returns a value of type `FileRequest`. Returns the updated file request object. ## Delete file request Deletes a file request permanently. This operation is performed by calling function `deleteFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-file-requests-id/). ``` try await client.fileRequests.deleteFileRequestById(fileRequestId: updatedFileRequest.id) ``` ### Arguments fileRequestId `String` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" headers `DeleteFileRequestByIdHeaders` - Headers of deleteFileRequestById method ### Returns This function returns a value of type ``. Returns an empty response when the file request has been successfully deleted. ## Copy file request Copies an existing file request that is already present on one folder, and applies it to another folder. This operation is performed by calling function `createFileRequestCopy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-file-requests-id-copy/). ``` try await client.fileRequests.createFileRequestCopy(fileRequestId: fileRequestId, requestBody: FileRequestCopyRequest(folder: FileRequestCopyRequestFolderField(id: fileRequest.folder.id, type: FileRequestCopyRequestFolderTypeField.folder))) ``` ### Arguments fileRequestId `String` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" requestBody `FileRequestCopyRequest` - Request body of createFileRequestCopy method headers `CreateFileRequestCopyHeaders` - Headers of createFileRequestCopy method ### Returns This function returns a value of type `FileRequest`. Returns updated file request object. --- ## Untitled *Type: page* FileVersionsManager List all file versions Get file version Remove file version Restore file version Promote file version List all file… # FileVersionsManager - [List all file versions](#list-all-file-versions) - [Get file version](#get-file-version) - [Remove file version](#remove-file-version) - [Restore file version](#restore-file-version) - [Promote file version](#promote-file-version) ## List all file versions Retrieve a list of the past versions for a file. Versions are only tracked by Box users with premium accounts. To fetch the ID of the current version of a file, use the `GET /file/:id` API. This operation is performed by calling function `getFileVersions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions/). ``` try await client.fileVersions.getFileVersions(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileVersionsQueryParams` - Query parameters of getFileVersions method headers `GetFileVersionsHeaders` - Headers of getFileVersions method ### Returns This function returns a value of type `FileVersions`. Returns an array of past versions for this file. ## Get file version Retrieve a specific version of a file. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `getFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions-id/). ``` try await client.fileVersions.getFileVersionById(fileId: file.id, fileVersionId: fileVersions.entries![0].id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `String` - The ID of the file version. Example: "1234" queryParams `GetFileVersionByIdQueryParams` - Query parameters of getFileVersionById method headers `GetFileVersionByIdHeaders` - Headers of getFileVersionById method ### Returns This function returns a value of type `FileVersionFull`. Returns a specific version of a file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Remove file version Move a file version to the trash. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `deleteFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-versions-id/). ``` try await client.fileVersions.deleteFileVersionById(fileId: file.id, fileVersionId: fileVersion.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `String` - The ID of the file version. Example: "1234" headers `DeleteFileVersionByIdHeaders` - Headers of deleteFileVersionById method ### Returns This function returns a value of type ``. Returns an empty response when the file has been successfully deleted. ## Restore file version Restores a specific version of a file after it was deleted. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `updateFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-versions-id/). *Currently we don't have an example for calling `updateFileVersionById` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `String` - The ID of the file version. Example: "1234" requestBody `UpdateFileVersionByIdRequestBody` - Request body of updateFileVersionById method headers `UpdateFileVersionByIdHeaders` - Headers of updateFileVersionById method ### Returns This function returns a value of type `FileVersionFull`. Returns a restored file version object. ## Promote file version Promote a specific version of a file. If previous versions exist, this method can be used to promote one of the older versions to the top of the version history. This creates a new copy of the old version and puts it at the top of the versions history. The file will have the exact same contents as the older version, with the the same hash digest, `etag`, and name as the original. Other properties such as comments do not get updated to their former values. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `promoteFileVersion`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-versions-current/). ``` try await client.fileVersions.promoteFileVersion(fileId: file.id, requestBody: PromoteFileVersionRequestBody(id: fileVersions.entries![0].id, type: PromoteFileVersionRequestBodyTypeField.fileVersion)) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `PromoteFileVersionRequestBody` - Request body of promoteFileVersion method queryParams `PromoteFileVersionQueryParams` - Query parameters of promoteFileVersion method headers `PromoteFileVersionHeaders` - Headers of promoteFileVersion method ### Returns This function returns a value of type `FileVersionFull`. Returns a newly created file version object. --- ## Untitled *Type: page* FileVersionRetentionsManager List file version retentions Get retention on file List file version retentions Retrieves all file version… # FileVersionRetentionsManager - [List file version retentions](#list-file-version-retentions) - [Get retention on file](#get-retention-on-file) ## List file version retentions Retrieves all file version retentions for the given enterprise. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `getFileVersionRetentions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions/). ``` try await client.fileVersionRetentions.getFileVersionRetentions() ``` ### Arguments queryParams `GetFileVersionRetentionsQueryParams` - Query parameters of getFileVersionRetentions method headers `GetFileVersionRetentionsHeaders` - Headers of getFileVersionRetentions method ### Returns This function returns a value of type `FileVersionRetentions`. Returns a list of all file version retentions for the enterprise. ## Get retention on file Returns information about a file version retention. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `getFileVersionRetentionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions-id/). ``` try await client.fileVersionRetentions.getFileVersionRetentionById(fileVersionRetentionId: fileVersionRetention.id!) ``` ### Arguments fileVersionRetentionId `String` - The ID of the file version retention. Example: "3424234" headers `GetFileVersionRetentionByIdHeaders` - Headers of getFileVersionRetentionById method ### Returns This function returns a value of type `FileVersionRetention`. Returns a file version retention object. --- ## Untitled *Type: page* FileWatermarksManager Get watermark on file Apply watermark to file Remove watermark from file Get watermark on file Retrieve the watermark… # FileWatermarksManager - [Get watermark on file](#get-watermark-on-file) - [Apply watermark to file](#apply-watermark-to-file) - [Remove watermark from file](#remove-watermark-from-file) ## Get watermark on file Retrieve the watermark for a file. This operation is performed by calling function `getFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-watermark/). ``` try await client.fileWatermarks.getFileWatermark(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileWatermarkHeaders` - Headers of getFileWatermark method ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this file. ## Apply watermark to file Applies or update a watermark on a file. This operation is performed by calling function `updateFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-watermark/). ``` try await client.fileWatermarks.updateFileWatermark(fileId: file.id, requestBody: UpdateFileWatermarkRequestBody(watermark: UpdateFileWatermarkRequestBodyWatermarkField(imprint: UpdateFileWatermarkRequestBodyWatermarkImprintField.default_))) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateFileWatermarkRequestBody` - Request body of updateFileWatermark method headers `UpdateFileWatermarkHeaders` - Headers of updateFileWatermark method ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this file.Returns a new watermark if no watermark existed on this file yet. ## Remove watermark from file Removes the watermark from a file. This operation is performed by calling function `deleteFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-watermark/). ``` try await client.fileWatermarks.deleteFileWatermark(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteFileWatermarkHeaders` - Headers of deleteFileWatermark method ### Returns This function returns a value of type ``. Removes the watermark and returns an empty response. --- ## Untitled *Type: page* FilesManager Get file information Update file Delete file Copy file Get file thumbnail URL Get file thumbnail Get file information Retrieves… # FilesManager - [Get file information](#get-file-information) - [Update file](#update-file) - [Delete file](#delete-file) - [Copy file](#copy-file) - [Get file thumbnail URL](#get-file-thumbnail-url) - [Get file thumbnail](#get-file-thumbnail) ## Get file information Retrieves the details about a file. This operation is performed by calling function `getFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id/). ``` try await client.files.getFileById(fileId: uploadedFile.id, queryParams: GetFileByIdQueryParams(fields: ["is_externally_owned", "has_collaborations"])) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileByIdQueryParams` - Query parameters of getFileById method headers `GetFileByIdHeaders` - Headers of getFileById method ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update file Updates a file. This can be used to rename or move a file, create a shared link, or lock a file. This operation is performed by calling function `updateFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id/). ``` try await client.files.updateFileById(fileId: fileToUpdate.id, requestBody: UpdateFileByIdRequestBody(name: updatedName, description: "Updated description")) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateFileByIdRequestBody` - Request body of updateFileById method queryParams `UpdateFileByIdQueryParams` - Query parameters of updateFileById method headers `UpdateFileByIdHeaders` - Headers of updateFileById method ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Delete file Deletes a file, either permanently or by moving it to the trash. The the enterprise settings determine whether the item will be permanently deleted from Box or moved to the trash. This operation is performed by calling function `deleteFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id/). ``` try await client.files.deleteFileById(fileId: thumbnailFile.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteFileByIdHeaders` - Headers of deleteFileById method ### Returns This function returns a value of type ``. Returns an empty response when the file has been successfully deleted. ## Copy file Creates a copy of a file. This operation is performed by calling function `copyFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-copy/). ``` try await client.files.copyFile(fileId: fileOrigin.id, requestBody: CopyFileRequestBody(parent: CopyFileRequestBodyParentField(id: "0"), name: copiedFileName)) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CopyFileRequestBody` - Request body of copyFile method queryParams `CopyFileQueryParams` - Query parameters of copyFile method headers `CopyFileHeaders` - Headers of copyFile method ### Returns This function returns a value of type `FileFull`. Returns a new file object representing the copied file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Get file thumbnail URL Get the download URL without downloading the content. This operation is performed by calling function `getFileThumbnailUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` try await client.files.getFileThumbnailUrl(fileId: thumbnailFile.id, extension_: GetFileThumbnailUrlExtension.png) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension_ `GetFileThumbnailUrlExtension` - The file format for the thumbnail. Example: "png" queryParams `GetFileThumbnailUrlQueryParams` - Query parameters of getFileThumbnailById method headers `GetFileThumbnailUrlHeaders` - Headers of getFileThumbnailById method ### Returns This function returns a value of type `String`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. ## Get file thumbnail Retrieves a thumbnail, or smaller image representation, of a file. Sizes of `32x32`,`64x64`, `128x128`, and `256x256` can be returned in the `.png` format and sizes of `32x32`, `160x160`, and `320x320` can be returned in the `.jpg` format. Thumbnails can be generated for the image and video file formats listed [found on our community site](https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327). This operation is performed by calling function `getFileThumbnailById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` try await client.files.getFileThumbnailById(fileId: thumbnailFile.id, extension_: GetFileThumbnailByIdExtension.png, downloadDestinationUrl: destinationPath) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension_ `GetFileThumbnailByIdExtension` - The file format for the thumbnail. Example: "png" downloadDestinationUrl `URL` - The URL on disk where the file will be saved once it has been downloaded. queryParams `GetFileThumbnailByIdQueryParams` - Query parameters of getFileThumbnailById method headers `GetFileThumbnailByIdHeaders` - Headers of getFileThumbnailById method ### Returns This function returns a value of type `URL?`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. --- ## Untitled *Type: page* FolderClassificationsManager Get classification on folder Add classification to folder Update classification on folder Remove classification… # FolderClassificationsManager - [Get classification on folder](#get-classification-on-folder) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Get classification on folder Retrieves the classification metadata instance that has been applied to a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `getClassificationOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` try await client.folderClassifications.getClassificationOnFolder(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetClassificationOnFolderHeaders` - Headers of getClassificationOnFolder method ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to folder Adds a classification to a folder by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `addClassificationToFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` try await client.folderClassifications.addClassificationToFolder(folderId: folder.id, requestBody: AddClassificationToFolderRequestBody(boxSecurityClassificationKey: classification.key)) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `AddClassificationToFolderRequestBody` - Request body of addClassificationToFolder method headers `AddClassificationToFolderHeaders` - Headers of addClassificationToFolder method ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the folder. ## Update classification on folder Updates a classification on a folder. The classification can only be updated if a classification has already been applied to the folder before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `updateClassificationOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` try await client.folderClassifications.updateClassificationOnFolder(folderId: folder.id, requestBody: [UpdateClassificationOnFolderRequestBody(value: secondClassification.key)]) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `[UpdateClassificationOnFolderRequestBody]` - Request body of updateClassificationOnFolder method headers `UpdateClassificationOnFolderHeaders` - Headers of updateClassificationOnFolder method ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from folder Removes any classifications from a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `deleteClassificationFromFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` try await client.folderClassifications.deleteClassificationFromFolder(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteClassificationFromFolderHeaders` - Headers of deleteClassificationFromFolder method ### Returns This function returns a value of type ``. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* FolderLocksManager List folder locks Create folder lock Delete folder lock List folder locks Retrieves folder lock details for a given… # FolderLocksManager - [List folder locks](#list-folder-locks) - [Create folder lock](#create-folder-lock) - [Delete folder lock](#delete-folder-lock) ## List folder locks Retrieves folder lock details for a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `getFolderLocks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folder-locks/). ``` try await client.folderLocks.getFolderLocks(queryParams: GetFolderLocksQueryParams(folderId: folder.id)) ``` ### Arguments queryParams `GetFolderLocksQueryParams` - Query parameters of getFolderLocks method headers `GetFolderLocksHeaders` - Headers of getFolderLocks method ### Returns This function returns a value of type `FolderLocks`. Returns details for all folder locks applied to the folder, including the lock type and user that applied the lock. ## Create folder lock Creates a folder lock on a folder, preventing it from being moved and/or deleted. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `createFolderLock`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folder-locks/). ``` try await client.folderLocks.createFolderLock(requestBody: CreateFolderLockRequestBody(folder: CreateFolderLockRequestBodyFolderField(id: folder.id, type: "folder"), lockedOperations: CreateFolderLockRequestBodyLockedOperationsField(move: true, delete: true))) ``` ### Arguments requestBody `CreateFolderLockRequestBody` - Request body of createFolderLock method headers `CreateFolderLockHeaders` - Headers of createFolderLock method ### Returns This function returns a value of type `FolderLock`. Returns the instance of the folder lock that was applied to the folder, including the user that applied the lock and the operations set. ## Delete folder lock Deletes a folder lock on a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `deleteFolderLockById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folder-locks-id/). ``` try await client.folderLocks.deleteFolderLockById(folderLockId: folderLock.id!) ``` ### Arguments folderLockId `String` - The ID of the folder lock. Example: "12345" headers `DeleteFolderLockByIdHeaders` - Headers of deleteFolderLockById method ### Returns This function returns a value of type ``. Returns an empty response when the folder lock is successfully deleted. --- ## Untitled *Type: page* FolderMetadataManager List metadata instances on folder Get metadata instance on folder Create metadata instance on folder Update metadata… # FolderMetadataManager - [List metadata instances on folder](#list-metadata-instances-on-folder) - [Get metadata instance on folder](#get-metadata-instance-on-folder) - [Create metadata instance on folder](#create-metadata-instance-on-folder) - [Update metadata instance on folder](#update-metadata-instance-on-folder) - [Remove metadata instance from folder](#remove-metadata-instance-from-folder) ## List metadata instances on folder Retrieves all metadata for a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getFolderMetadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata/). ``` try await client.folderMetadata.getFolderMetadata(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetFolderMetadataHeaders` - Headers of getFolderMetadata method ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a folder. This API does not support pagination and will therefore always return all of the metadata associated to the folder. ## Get metadata instance on folder Retrieves the instance of a metadata template that has been applied to a folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-id-id/). ``` try await client.folderMetadata.getFolderMetadataById(folderId: folder.id, scope: GetFolderMetadataByIdScope.global, templateKey: "properties") ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `GetFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `GetFolderMetadataByIdHeaders` - Headers of getFolderMetadataById method ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on folder Applies an instance of a metadata template to a folder. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. To display the metadata template in the Box web app the enterprise needs to be configured to enable **Cascading Folder Level Metadata** for the user in the admin console. This operation is performed by calling function `createFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-id-id/). ``` try await client.folderMetadata.createFolderMetadataById(folderId: folder.id, scope: CreateFolderMetadataByIdScope.global, templateKey: "properties", requestBody: ["abc": "xyz"]) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `CreateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `CreateFolderMetadataByIdRequestBody` - Request body of createFolderMetadataById method headers `CreateFolderMetadataByIdHeaders` - Headers of createFolderMetadataById method ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the folder, including the data that was applied to the template. ## Update metadata instance on folder Updates a piece of metadata on a folder. The metadata instance can only be updated if the template has already been applied to the folder before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `updateFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-id-id/). *Currently we don't have an example for calling `updateFolderMetadataById` in integration tests* ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `UpdateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `[UpdateFolderMetadataByIdRequestBody]` - Request body of updateFolderMetadataById method headers `UpdateFolderMetadataByIdHeaders` - Headers of updateFolderMetadataById method ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from folder Deletes a piece of folder metadata. This operation is performed by calling function `deleteFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-id-id/). ``` try await client.folderMetadata.deleteFolderMetadataById(folderId: folder.id, scope: DeleteFolderMetadataByIdScope.global, templateKey: "properties") ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `DeleteFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `DeleteFolderMetadataByIdHeaders` - Headers of deleteFolderMetadataById method ### Returns This function returns a value of type ``. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* FolderWatermarksManager Get watermark for folder Apply watermark to folder Remove watermark from folder Get watermark for folder Retrieve… # FolderWatermarksManager - [Get watermark for folder](#get-watermark-for-folder) - [Apply watermark to folder](#apply-watermark-to-folder) - [Remove watermark from folder](#remove-watermark-from-folder) ## Get watermark for folder Retrieve the watermark for a folder. This operation is performed by calling function `getFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-watermark/). ``` try await client.folderWatermarks.getFolderWatermark(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetFolderWatermarkHeaders` - Headers of getFolderWatermark method ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this folder. ## Apply watermark to folder Applies or update a watermark on a folder. This operation is performed by calling function `updateFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-watermark/). ``` try await client.folderWatermarks.updateFolderWatermark(folderId: folder.id, requestBody: UpdateFolderWatermarkRequestBody(watermark: UpdateFolderWatermarkRequestBodyWatermarkField(imprint: UpdateFolderWatermarkRequestBodyWatermarkImprintField.default_))) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateFolderWatermarkRequestBody` - Request body of updateFolderWatermark method headers `UpdateFolderWatermarkHeaders` - Headers of updateFolderWatermark method ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this folder.Returns a new watermark if no watermark existed on this folder yet. ## Remove watermark from folder Removes the watermark from a folder. This operation is performed by calling function `deleteFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-watermark/). ``` try await client.folderWatermarks.deleteFolderWatermark(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteFolderWatermarkHeaders` - Headers of deleteFolderWatermark method ### Returns This function returns a value of type ``. An empty response will be returned when the watermark was successfully deleted. --- ## Untitled *Type: page* FoldersManager Get folder information Update folder Delete folder List items in folder Create folder Copy folder Get folder information… # FoldersManager - [Get folder information](#get-folder-information) - [Update folder](#update-folder) - [Delete folder](#delete-folder) - [List items in folder](#list-items-in-folder) - [Create folder](#create-folder) - [Copy folder](#copy-folder) ## Get folder information Retrieves details for a folder, including the first 100 entries in the folder. Passing `sort`, `direction`, `offset`, and `limit` parameters in query allows you to manage the list of returned [folder items](r://folder--full#param-item-collection). To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items) endpoint. This operation is performed by calling function `getFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id/). ``` try await client.folders.getFolderById(folderId: "0") ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderByIdQueryParams` - Query parameters of getFolderById method headers `GetFolderByIdHeaders` - Headers of getFolderById method ### Returns This function returns a value of type `FolderFull`. Returns a folder, including the first 100 entries in the folder. If you used query parameters like `sort`, `direction`, `offset`, or `limit` the *folder items list* will be affected accordingly. To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items)) endpoint. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update folder Updates a folder. This can be also be used to move the folder, create shared links, update collaborations, and more. This operation is performed by calling function `updateFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id/). ``` try await client.folders.updateFolderById(folderId: folderToUpdate.id, requestBody: UpdateFolderByIdRequestBody(name: updatedName, description: "Updated description")) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateFolderByIdRequestBody` - Request body of updateFolderById method queryParams `UpdateFolderByIdQueryParams` - Query parameters of updateFolderById method headers `UpdateFolderByIdHeaders` - Headers of updateFolderById method ### Returns This function returns a value of type `FolderFull`. Returns a folder object for the updated folder Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. If the user is moving folders with a large number of items in all of their descendants, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. ## Delete folder Deletes a folder, either permanently or by moving it to the trash. This operation is performed by calling function `deleteFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id/). ``` try await client.folders.deleteFolderById(folderId: newFolder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `DeleteFolderByIdQueryParams` - Query parameters of deleteFolderById method headers `DeleteFolderByIdHeaders` - Headers of deleteFolderById method ### Returns This function returns a value of type ``. Returns an empty response when the folder is successfully deleted or moved to the trash. ## List items in folder Retrieves a page of items in a folder. These items can be files, folders, and web links. To request more information about the folder itself, like its size, use the [Get a folder](#get-folders-id) endpoint instead. This operation is performed by calling function `getFolderItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-items/). ``` try await client.folders.getFolderItems(folderId: folderOrigin.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderItemsQueryParams` - Query parameters of getFolderItems method headers `GetFolderItemsHeaders` - Headers of getFolderItems method ### Returns This function returns a value of type `Items`. Returns a collection of files, folders, and web links contained in a folder. ## Create folder Creates a new empty folder within the specified parent folder. This operation is performed by calling function `createFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders/). ``` try await client.folders.createFolder(requestBody: CreateFolderRequestBody(name: newFolderName, parent: CreateFolderRequestBodyParentField(id: "0"))) ``` ### Arguments requestBody `CreateFolderRequestBody` - Request body of createFolder method queryParams `CreateFolderQueryParams` - Query parameters of createFolder method headers `CreateFolderHeaders` - Headers of createFolder method ### Returns This function returns a value of type `FolderFull`. Returns a folder object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Copy folder Creates a copy of a folder within a destination folder. The original folder will not be changed. This operation is performed by calling function `copyFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-copy/). ``` try await client.folders.copyFolder(folderId: folderOrigin.id, requestBody: CopyFolderRequestBody(parent: CopyFolderRequestBodyParentField(id: "0"), name: copiedFolderName)) ``` ### Arguments folderId `String` - The unique identifier of the folder to copy. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder with the ID `0` can not be copied. Example: "0" requestBody `CopyFolderRequestBody` - Request body of copyFolder method queryParams `CopyFolderQueryParams` - Query parameters of copyFolder method headers `CopyFolderHeaders` - Headers of copyFolder method ### Returns This function returns a value of type `FolderFull`. Returns a new folder object representing the copied folder. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* HubCollaborationsManager Get hub collaborations Create hub collaboration Get hub collaboration by collaboration ID Update hub collaboration… # HubCollaborationsManager - [Get hub collaborations](#get-hub-collaborations) - [Create hub collaboration](#create-hub-collaboration) - [Get hub collaboration by collaboration ID](#get-hub-collaboration-by-collaboration-id) - [Update hub collaboration](#update-hub-collaboration) - [Remove hub collaboration](#remove-hub-collaboration) ## Get hub collaborations Retrieves all collaborations for a hub. This operation is performed by calling function `getHubCollaborationsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations/). ``` try await client.hubCollaborations.getHubCollaborationsV2025R0(queryParams: GetHubCollaborationsV2025R0QueryParams(hubId: hub.id)) ``` ### Arguments queryParams `GetHubCollaborationsV2025R0QueryParams` - Query parameters of getHubCollaborationsV2025R0 method headers `GetHubCollaborationsV2025R0Headers` - Headers of getHubCollaborationsV2025R0 method ### Returns This function returns a value of type `HubCollaborationsV2025R0`. Retrieves the collaborations associated with the specified hub. ## Create hub collaboration Adds a collaboration for a single user or a single group to a hub. Collaborations can be created using email address, user IDs, or group IDs. This operation is performed by calling function `createHubCollaborationV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hub-collaborations/). ``` try await client.hubCollaborations.createHubCollaborationV2025R0(requestBody: HubCollaborationCreateRequestV2025R0(hub: HubCollaborationCreateRequestV2025R0HubField(id: hub.id), accessibleBy: HubCollaborationCreateRequestV2025R0AccessibleByField(type: "user", id: user.id), role: "viewer")) ``` ### Arguments requestBody `HubCollaborationCreateRequestV2025R0` - Request body of createHubCollaborationV2025R0 method headers `CreateHubCollaborationV2025R0Headers` - Headers of createHubCollaborationV2025R0 method ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a new hub collaboration object. ## Get hub collaboration by collaboration ID Retrieves details for a hub collaboration by collaboration ID. This operation is performed by calling function `getHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations-id/). ``` try await client.hubCollaborations.getHubCollaborationByIdV2025R0(hubCollaborationId: createdCollaboration.id) ``` ### Arguments hubCollaborationId `String` - The ID of the hub collaboration. Example: "1234" headers `GetHubCollaborationByIdV2025R0Headers` - Headers of getHubCollaborationByIdV2025R0 method ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a hub collaboration object. ## Update hub collaboration Updates a hub collaboration. Can be used to change the hub role. This operation is performed by calling function `updateHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hub-collaborations-id/). ``` try await client.hubCollaborations.updateHubCollaborationByIdV2025R0(hubCollaborationId: createdCollaboration.id, requestBody: HubCollaborationUpdateRequestV2025R0(role: "editor")) ``` ### Arguments hubCollaborationId `String` - The ID of the hub collaboration. Example: "1234" requestBody `HubCollaborationUpdateRequestV2025R0` - Request body of updateHubCollaborationByIdV2025R0 method headers `UpdateHubCollaborationByIdV2025R0Headers` - Headers of updateHubCollaborationByIdV2025R0 method ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns an updated hub collaboration object. ## Remove hub collaboration Deletes a single hub collaboration. This operation is performed by calling function `deleteHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hub-collaborations-id/). ``` try await client.hubCollaborations.deleteHubCollaborationByIdV2025R0(hubCollaborationId: createdCollaboration.id) ``` ### Arguments hubCollaborationId `String` - The ID of the hub collaboration. Example: "1234" headers `DeleteHubCollaborationByIdV2025R0Headers` - Headers of deleteHubCollaborationByIdV2025R0 method ### Returns This function returns a value of type ``. A blank response is returned if the hub collaboration was successfully deleted. --- ## Untitled *Type: page* GroupsManager List groups for enterprise Create group Get group Update group Remove group List groups for enterprise Retrieves all of the… # GroupsManager - [List groups for enterprise](#list-groups-for-enterprise) - [Create group](#create-group) - [Get group](#get-group) - [Update group](#update-group) - [Remove group](#remove-group) ## List groups for enterprise Retrieves all of the groups for a given enterprise. The user must have admin permissions to inspect enterprise's groups. This operation is performed by calling function `getGroups`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups/). ``` try await client.groups.getGroups() ``` ### Arguments queryParams `GetGroupsQueryParams` - Query parameters of getGroups method headers `GetGroupsHeaders` - Headers of getGroups method ### Returns This function returns a value of type `Groups`. Returns a collection of group objects. If there are no groups, an empty collection will be returned. ## Create group Creates a new group of users in an enterprise. Only users with admin permissions can create new groups. This operation is performed by calling function `createGroup`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups/). ``` try await client.groups.createGroup(requestBody: CreateGroupRequestBody(name: groupName, description: groupDescription)) ``` ### Arguments requestBody `CreateGroupRequestBody` - Request body of createGroup method queryParams `CreateGroupQueryParams` - Query parameters of createGroup method headers `CreateGroupHeaders` - Headers of createGroup method ### Returns This function returns a value of type `GroupFull`. Returns the new group object. ## Get group Retrieves information about a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id/). ``` try await client.groups.getGroupById(groupId: group.id, queryParams: GetGroupByIdQueryParams(fields: ["id", "name", "description", "group_type"])) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" queryParams `GetGroupByIdQueryParams` - Query parameters of getGroupById method headers `GetGroupByIdHeaders` - Headers of getGroupById method ### Returns This function returns a value of type `GroupFull`. Returns the group object. ## Update group Updates a specific group. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `updateGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-groups-id/). ``` try await client.groups.updateGroupById(groupId: group.id, requestBody: UpdateGroupByIdRequestBody(name: updatedGroupName)) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" requestBody `UpdateGroupByIdRequestBody` - Request body of updateGroupById method queryParams `UpdateGroupByIdQueryParams` - Query parameters of updateGroupById method headers `UpdateGroupByIdHeaders` - Headers of updateGroupById method ### Returns This function returns a value of type `GroupFull`. Returns the updated group object. ## Remove group Permanently deletes a group. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `deleteGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-groups-id/). ``` try await client.groups.deleteGroupById(groupId: group.id) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" headers `DeleteGroupByIdHeaders` - Headers of deleteGroupById method ### Returns This function returns a value of type ``. A blank response is returned if the group was successfully deleted. --- ## Untitled *Type: page* HubItemsManager Get hub items Manage hub items Get hub items Retrieves all items associated with a Hub. This operation is performed by… # HubItemsManager - [Get hub items](#get-hub-items) - [Manage hub items](#manage-hub-items) ## Get hub items Retrieves all items associated with a Hub. This operation is performed by calling function `getHubItemsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-items/). ``` try await client.hubItems.getHubItemsV2025R0(queryParams: GetHubItemsV2025R0QueryParams(hubId: createdHub.id)) ``` ### Arguments queryParams `GetHubItemsV2025R0QueryParams` - Query parameters of getHubItemsV2025R0 method headers `GetHubItemsV2025R0Headers` - Headers of getHubItemsV2025R0 method ### Returns This function returns a value of type `HubItemsV2025R0`. Retrieves the items associated with the specified Hub. ## Manage hub items Adds and/or removes Hub items from a Hub. This operation is performed by calling function `manageHubItemsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-manage-items/). *Currently we don't have an example for calling `manageHubItemsV2025R0` in integration tests* ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubItemsManageRequestV2025R0` - Request body of manageHubItemsV2025R0 method headers `ManageHubItemsV2025R0Headers` - Headers of manageHubItemsV2025R0 method ### Returns This function returns a value of type `HubItemsManageResponseV2025R0`. --- ## Untitled *Type: page* IntegrationMappingsManager List Slack integration mappings Create Slack integration mapping Update Slack integration mapping Delete Slack… # IntegrationMappingsManager - [List Slack integration mappings](#list-slack-integration-mappings) - [Create Slack integration mapping](#create-slack-integration-mapping) - [Update Slack integration mapping](#update-slack-integration-mapping) - [Delete Slack integration mapping](#delete-slack-integration-mapping) - [List Teams integration mappings](#list-teams-integration-mappings) - [Create Teams integration mapping](#create-teams-integration-mapping) - [Update Teams integration mapping](#update-teams-integration-mapping) - [Delete Teams integration mapping](#delete-teams-integration-mapping) ## List Slack integration mappings Lists [Slack integration mappings](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `getSlackIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-slack/). ``` try await userClient.integrationMappings.getSlackIntegrationMapping() ``` ### Arguments queryParams `GetSlackIntegrationMappingQueryParams` - Query parameters of getSlackIntegrationMapping method headers `GetSlackIntegrationMappingHeaders` - Headers of getSlackIntegrationMapping method ### Returns This function returns a value of type `IntegrationMappings`. Returns a collection of integration mappings. ## Create Slack integration mapping Creates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) by mapping a Slack channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `createSlackIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-slack/). ``` try await userClient.integrationMappings.createSlackIntegrationMapping(requestBody: IntegrationMappingSlackCreateRequest(partnerItem: IntegrationMappingPartnerItemSlack(id: slackPartnerItemId, slackOrgId: slackOrgId), boxItem: IntegrationMappingBoxItemSlack(id: folder.id))) ``` ### Arguments requestBody `IntegrationMappingSlackCreateRequest` - Request body of createSlackIntegrationMapping method headers `CreateSlackIntegrationMappingHeaders` - Headers of createSlackIntegrationMapping method ### Returns This function returns a value of type `IntegrationMapping`. Returns the created integration mapping. ## Update Slack integration mapping Updates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `updateSlackIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-slack-id/). ``` try await userClient.integrationMappings.updateSlackIntegrationMappingById(integrationMappingId: slackIntegrationMapping.id, requestBody: UpdateSlackIntegrationMappingByIdRequestBody(boxItem: IntegrationMappingBoxItemSlack(id: folder.id))) ``` ### Arguments integrationMappingId `String` - An ID of an integration mapping. Example: "11235432" requestBody `UpdateSlackIntegrationMappingByIdRequestBody` - Request body of updateSlackIntegrationMappingById method headers `UpdateSlackIntegrationMappingByIdHeaders` - Headers of updateSlackIntegrationMappingById method ### Returns This function returns a value of type `IntegrationMapping`. Returns the updated integration mapping object. ## Delete Slack integration mapping Deletes a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `deleteSlackIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-slack-id/). ``` try await userClient.integrationMappings.deleteSlackIntegrationMappingById(integrationMappingId: slackIntegrationMapping.id) ``` ### Arguments integrationMappingId `String` - An ID of an integration mapping. Example: "11235432" headers `DeleteSlackIntegrationMappingByIdHeaders` - Headers of deleteSlackIntegrationMappingById method ### Returns This function returns a value of type ``. Empty body in response. ## List Teams integration mappings Lists [Teams integration mappings](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `getTeamsIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-teams/). ``` try await userClient.integrationMappings.getTeamsIntegrationMapping() ``` ### Arguments queryParams `GetTeamsIntegrationMappingQueryParams` - Query parameters of getTeamsIntegrationMapping method headers `GetTeamsIntegrationMappingHeaders` - Headers of getTeamsIntegrationMapping method ### Returns This function returns a value of type `IntegrationMappingsTeams`. Returns a collection of integration mappings. ## Create Teams integration mapping Creates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) by mapping a Teams channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `createTeamsIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-teams/). ``` try await userClient.integrationMappings.createTeamsIntegrationMapping(requestBody: IntegrationMappingTeamsCreateRequest(partnerItem: IntegrationMappingPartnerItemTeamsCreateRequest(type: IntegrationMappingPartnerItemTeamsCreateRequestTypeField.channel, id: partnerItemId, tenantId: tenantId, teamId: teamId), boxItem: FolderReference(id: folder.id))) ``` ### Arguments requestBody `IntegrationMappingTeamsCreateRequest` - Request body of createTeamsIntegrationMapping method headers `CreateTeamsIntegrationMappingHeaders` - Headers of createTeamsIntegrationMapping method ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the created integration mapping. ## Update Teams integration mapping Updates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `updateTeamsIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-teams-id/). ``` try await userClient.integrationMappings.updateTeamsIntegrationMappingById(integrationMappingId: integrationMappingId, requestBody: UpdateTeamsIntegrationMappingByIdRequestBody(boxItem: FolderReference(id: "1234567"))) ``` ### Arguments integrationMappingId `String` - An ID of an integration mapping. Example: "11235432" requestBody `UpdateTeamsIntegrationMappingByIdRequestBody` - Request body of updateTeamsIntegrationMappingById method headers `UpdateTeamsIntegrationMappingByIdHeaders` - Headers of updateTeamsIntegrationMappingById method ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the updated integration mapping object. ## Delete Teams integration mapping Deletes a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `deleteTeamsIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-teams-id/). ``` try await userClient.integrationMappings.deleteTeamsIntegrationMappingById(integrationMappingId: integrationMappingId) ``` ### Arguments integrationMappingId `String` - An ID of an integration mapping. Example: "11235432" headers `DeleteTeamsIntegrationMappingByIdHeaders` - Headers of deleteTeamsIntegrationMappingById method ### Returns This function returns a value of type ``. Empty body in response. --- ## Untitled *Type: page* HubsManager List all hubs Create hub List all hubs for requesting enterprise Get hub information by ID Update hub information by ID Delete… # HubsManager - [List all hubs](#list-all-hubs) - [Create hub](#create-hub) - [List all hubs for requesting enterprise](#list-all-hubs-for-requesting-enterprise) - [Get hub information by ID](#get-hub-information-by-id) - [Update hub information by ID](#update-hub-information-by-id) - [Delete hub](#delete-hub) - [Copy hub](#copy-hub) ## List all hubs Retrieves all hubs for requesting user. This operation is performed by calling function `getHubsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs/). ``` try await client.hubs.getHubsV2025R0(queryParams: GetHubsV2025R0QueryParams(scope: "all", sort: "name", direction: GetHubsV2025R0QueryParamsDirectionField.asc)) ``` ### Arguments queryParams `GetHubsV2025R0QueryParams` - Query parameters of getHubsV2025R0 method headers `GetHubsV2025R0Headers` - Headers of getHubsV2025R0 method ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Create hub Creates a new Hub. This operation is performed by calling function `createHubV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs/). ``` try await client.hubs.createHubV2025R0(requestBody: HubCreateRequestV2025R0(title: hubTitle, description: hubDescription)) ``` ### Arguments requestBody `HubCreateRequestV2025R0` - Request body of createHubV2025R0 method headers `CreateHubV2025R0Headers` - Headers of createHubV2025R0 method ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. ## List all hubs for requesting enterprise Retrieves all hubs for a given enterprise. Admins or Hub Co-admins of an enterprise with GCM scope can make this call. This operation is performed by calling function `getEnterpriseHubsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-enterprise-hubs/). ``` try await client.hubs.getEnterpriseHubsV2025R0(queryParams: GetEnterpriseHubsV2025R0QueryParams(sort: "name", direction: GetEnterpriseHubsV2025R0QueryParamsDirectionField.asc)) ``` ### Arguments queryParams `GetEnterpriseHubsV2025R0QueryParams` - Query parameters of getEnterpriseHubsV2025R0 method headers `GetEnterpriseHubsV2025R0Headers` - Headers of getEnterpriseHubsV2025R0 method ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Get hub information by ID Retrieves details for a hub by its ID. This operation is performed by calling function `getHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs-id/). ``` try await client.hubs.getHubByIdV2025R0(hubId: hubId) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" headers `GetHubByIdV2025R0Headers` - Headers of getHubByIdV2025R0 method ### Returns This function returns a value of type `HubV2025R0`. Returns a hub object. ## Update hub information by ID Updates a Hub. Can be used to change title, description, or Hub settings. This operation is performed by calling function `updateHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hubs-id/). ``` try await client.hubs.updateHubByIdV2025R0(hubId: hubId, requestBody: HubUpdateRequestV2025R0(title: newHubTitle, description: newHubDescription)) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubUpdateRequestV2025R0` - Request body of updateHubByIdV2025R0 method headers `UpdateHubByIdV2025R0Headers` - Headers of updateHubByIdV2025R0 method ### Returns This function returns a value of type `HubV2025R0`. Returns a Hub object. ## Delete hub Deletes a single hub. This operation is performed by calling function `deleteHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hubs-id/). ``` try await client.hubs.deleteHubByIdV2025R0(hubId: hubId) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" headers `DeleteHubByIdV2025R0Headers` - Headers of deleteHubByIdV2025R0 method ### Returns This function returns a value of type ``. A blank response is returned if the hub was successfully deleted. ## Copy hub Creates a copy of a Hub. The original Hub will not be modified. This operation is performed by calling function `copyHubV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-copy/). ``` try await client.hubs.copyHubV2025R0(hubId: createdHub.id, requestBody: HubCopyRequestV2025R0(title: copiedHubTitle, description: copiedHubDescription)) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubCopyRequestV2025R0` - Request body of copyHubV2025R0 method headers `CopyHubV2025R0Headers` - Headers of copyHubV2025R0 method ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. --- ## Untitled *Type: page* InvitesManager Create user invite Get user invite status Create user invite Invites an existing external user to join an enterprise. The… # InvitesManager - [Create user invite](#create-user-invite) - [Get user invite status](#get-user-invite-status) ## Create user invite Invites an existing external user to join an enterprise. The existing user can not be part of another enterprise and must already have a Box account. Once invited, the user will receive an email and are prompted to accept the invitation within the Box web application. This method requires the "Manage An Enterprise" scope enabled for the application, which can be enabled within the developer console. This operation is performed by calling function `createInvite`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-invites/). ``` try await client.invites.createInvite(requestBody: CreateInviteRequestBody(enterprise: CreateInviteRequestBodyEnterpriseField(id: currentUser.enterprise!.id!), actionableBy: CreateInviteRequestBodyActionableByField(login: email))) ``` ### Arguments requestBody `CreateInviteRequestBody` - Request body of createInvite method queryParams `CreateInviteQueryParams` - Query parameters of createInvite method headers `CreateInviteHeaders` - Headers of createInvite method ### Returns This function returns a value of type `Invite`. Returns a new invite object. ## Get user invite status Returns the status of a user invite. This operation is performed by calling function `getInviteById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-invites-id/). ``` try await client.invites.getInviteById(inviteId: invitation.id) ``` ### Arguments inviteId `String` - The ID of an invite. Example: "213723" queryParams `GetInviteByIdQueryParams` - Query parameters of getInviteById method headers `GetInviteByIdHeaders` - Headers of getInviteById method ### Returns This function returns a value of type `Invite`. Returns an invite object. --- ## Untitled *Type: page* LegalHoldPolicyAssignmentsManager List legal hold policy assignments Assign legal hold policy Get legal hold policy assignment Unassign… # LegalHoldPolicyAssignmentsManager - [List legal hold policy assignments](#list-legal-hold-policy-assignments) - [Assign legal hold policy](#assign-legal-hold-policy) - [Get legal hold policy assignment](#get-legal-hold-policy-assignment) - [Unassign legal hold policy](#unassign-legal-hold-policy) - [List files with current file versions for legal hold policy assignment](#list-files-with-current-file-versions-for-legal-hold-policy-assignment) ## List legal hold policy assignments Retrieves a list of items a legal hold policy has been assigned to. This operation is performed by calling function `getLegalHoldPolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments/). ``` try await client.legalHoldPolicyAssignments.getLegalHoldPolicyAssignments(queryParams: GetLegalHoldPolicyAssignmentsQueryParams(policyId: legalHoldPolicyId)) ``` ### Arguments queryParams `GetLegalHoldPolicyAssignmentsQueryParams` - Query parameters of getLegalHoldPolicyAssignments method headers `GetLegalHoldPolicyAssignmentsHeaders` - Headers of getLegalHoldPolicyAssignments method ### Returns This function returns a value of type `LegalHoldPolicyAssignments`. Returns a list of legal hold policy assignments. ## Assign legal hold policy Assign a legal hold to a file, file version, folder, or user. This operation is performed by calling function `createLegalHoldPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policy-assignments/). ``` try await client.legalHoldPolicyAssignments.createLegalHoldPolicyAssignment(requestBody: CreateLegalHoldPolicyAssignmentRequestBody(policyId: legalHoldPolicyId, assignTo: CreateLegalHoldPolicyAssignmentRequestBodyAssignToField(type: CreateLegalHoldPolicyAssignmentRequestBodyAssignToTypeField.file, id: fileId))) ``` ### Arguments requestBody `CreateLegalHoldPolicyAssignmentRequestBody` - Request body of createLegalHoldPolicyAssignment method headers `CreateLegalHoldPolicyAssignmentHeaders` - Headers of createLegalHoldPolicyAssignment method ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a new legal hold policy assignment. ## Get legal hold policy assignment Retrieve a legal hold policy assignment. This operation is performed by calling function `getLegalHoldPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id/). ``` try await client.legalHoldPolicyAssignments.getLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId: legalHoldPolicyAssignmentId) ``` ### Arguments legalHoldPolicyAssignmentId `String` - The ID of the legal hold policy assignment. Example: "753465" headers `GetLegalHoldPolicyAssignmentByIdHeaders` - Headers of getLegalHoldPolicyAssignmentById method ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a legal hold policy object. ## Unassign legal hold policy Remove a legal hold from an item. This is an asynchronous process. The policy will not be fully removed yet when the response returns. This operation is performed by calling function `deleteLegalHoldPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policy-assignments-id/). ``` try await client.legalHoldPolicyAssignments.deleteLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId: legalHoldPolicyAssignmentId) ``` ### Arguments legalHoldPolicyAssignmentId `String` - The ID of the legal hold policy assignment. Example: "753465" headers `DeleteLegalHoldPolicyAssignmentByIdHeaders` - Headers of deleteLegalHoldPolicyAssignmentById method ### Returns This function returns a value of type ``. A blank response is returned if the assignment was successfully deleted. ## List files with current file versions for legal hold policy assignment Get a list of files with current file versions for a legal hold assignment. In some cases you may want to get previous file versions instead. In these cases, use the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API instead to return any previous versions of a file for this legal hold policy assignment. Due to ongoing re-architecture efforts this API might not return all file versions held for this policy ID. Instead, this API will only return the latest file version held in the newly developed architecture. The `GET /file_version_legal_holds` API can be used to fetch current and past versions of files held within the legacy architecture. This endpoint does not support returning any content that is on hold due to a Custodian collaborating on a Hub. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. This operation is performed by calling function `getLegalHoldPolicyAssignmentFileOnHold`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id-files-on-hold/). ``` try await client.legalHoldPolicyAssignments.getLegalHoldPolicyAssignmentFileOnHold(legalHoldPolicyAssignmentId: legalHoldPolicyAssignmentId) ``` ### Arguments legalHoldPolicyAssignmentId `String` - The ID of the legal hold policy assignment. Example: "753465" queryParams `GetLegalHoldPolicyAssignmentFileOnHoldQueryParams` - Query parameters of getLegalHoldPolicyAssignmentFileOnHold method headers `GetLegalHoldPolicyAssignmentFileOnHoldHeaders` - Headers of getLegalHoldPolicyAssignmentFileOnHold method ### Returns This function returns a value of type `FilesOnHold`. Returns the list of current file versions held under legal hold for a specific legal hold policy assignment. --- ## Untitled *Type: page* LegalHoldPoliciesManager List all legal hold policies Create legal hold policy Get legal hold policy Update legal hold policy Remove legal… # LegalHoldPoliciesManager - [List all legal hold policies](#list-all-legal-hold-policies) - [Create legal hold policy](#create-legal-hold-policy) - [Get legal hold policy](#get-legal-hold-policy) - [Update legal hold policy](#update-legal-hold-policy) - [Remove legal hold policy](#remove-legal-hold-policy) ## List all legal hold policies Retrieves a list of legal hold policies that belong to an enterprise. This operation is performed by calling function `getLegalHoldPolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies/). ``` try await client.legalHoldPolicies.getLegalHoldPolicies() ``` ### Arguments queryParams `GetLegalHoldPoliciesQueryParams` - Query parameters of getLegalHoldPolicies method headers `GetLegalHoldPoliciesHeaders` - Headers of getLegalHoldPolicies method ### Returns This function returns a value of type `LegalHoldPolicies`. Returns a list of legal hold policies. ## Create legal hold policy Create a new legal hold policy. This operation is performed by calling function `createLegalHoldPolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policies/). ``` try await client.legalHoldPolicies.createLegalHoldPolicy(requestBody: CreateLegalHoldPolicyRequestBody(policyName: legalHoldPolicyName, description: legalHoldDescription, isOngoing: false, filterStartedAt: filterStartedAt, filterEndedAt: filterEndedAt)) ``` ### Arguments requestBody `CreateLegalHoldPolicyRequestBody` - Request body of createLegalHoldPolicy method headers `CreateLegalHoldPolicyHeaders` - Headers of createLegalHoldPolicy method ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Get legal hold policy Retrieve a legal hold policy. This operation is performed by calling function `getLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies-id/). ``` try await client.legalHoldPolicies.getLegalHoldPolicyById(legalHoldPolicyId: legalHoldPolicyId) ``` ### Arguments legalHoldPolicyId `String` - The ID of the legal hold policy. Example: "324432" headers `GetLegalHoldPolicyByIdHeaders` - Headers of getLegalHoldPolicyById method ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a legal hold policy object. ## Update legal hold policy Update legal hold policy. This operation is performed by calling function `updateLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-legal-hold-policies-id/). ``` try await client.legalHoldPolicies.updateLegalHoldPolicyById(legalHoldPolicyId: legalHoldPolicyId, requestBody: UpdateLegalHoldPolicyByIdRequestBody(policyName: updatedLegalHoldPolicyName)) ``` ### Arguments legalHoldPolicyId `String` - The ID of the legal hold policy. Example: "324432" requestBody `UpdateLegalHoldPolicyByIdRequestBody` - Request body of updateLegalHoldPolicyById method headers `UpdateLegalHoldPolicyByIdHeaders` - Headers of updateLegalHoldPolicyById method ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Remove legal hold policy Delete an existing legal hold policy. This is an asynchronous process. The policy will not be fully deleted yet when the response returns. This operation is performed by calling function `deleteLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policies-id/). ``` try await client.legalHoldPolicies.deleteLegalHoldPolicyById(legalHoldPolicyId: legalHoldPolicy.id) ``` ### Arguments legalHoldPolicyId `String` - The ID of the legal hold policy. Example: "324432" headers `DeleteLegalHoldPolicyByIdHeaders` - Headers of deleteLegalHoldPolicyById method ### Returns This function returns a value of type ``. A blank response is returned if the policy was successfully deleted. --- ## Untitled *Type: page* ListCollaborationsManager List file collaborations List folder collaborations List pending collaborations List group collaborations List… # ListCollaborationsManager - [List file collaborations](#list-file-collaborations) - [List folder collaborations](#list-folder-collaborations) - [List pending collaborations](#list-pending-collaborations) - [List group collaborations](#list-group-collaborations) ## List file collaborations Retrieves a list of pending and active collaborations for a file. This returns all the users that have access to the file or have been invited to the file. This operation is performed by calling function `getFileCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-collaborations/). ``` try await client.listCollaborations.getFileCollaborations(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileCollaborationsQueryParams` - Query parameters of getFileCollaborations method headers `GetFileCollaborationsHeaders` - Headers of getFileCollaborations method ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this file an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List folder collaborations Retrieves a list of pending and active collaborations for a folder. This returns all the users that have access to the folder or have been invited to the folder. This operation is performed by calling function `getFolderCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-collaborations/). ``` try await client.listCollaborations.getFolderCollaborations(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. Example: "12345" queryParams `GetFolderCollaborationsQueryParams` - Query parameters of getFolderCollaborations method headers `GetFolderCollaborationsHeaders` - Headers of getFolderCollaborations method ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this folder an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List pending collaborations Retrieves all pending collaboration invites for this user. This operation is performed by calling function `getCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations/). ``` try await client.listCollaborations.getCollaborations(queryParams: GetCollaborationsQueryParams(status: GetCollaborationsQueryParamsStatusField.pending)) ``` ### Arguments queryParams `GetCollaborationsQueryParams` - Query parameters of getCollaborations method headers `GetCollaborationsHeaders` - Headers of getCollaborations method ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of pending collaboration objects. If the user has no pending collaborations, the collection will be empty. ## List group collaborations Retrieves all the collaborations for a group. The user must have admin permissions to inspect enterprise's groups. Each collaboration object has details on which files or folders the group has access to and with what role. This operation is performed by calling function `getGroupCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-collaborations/). ``` try await client.listCollaborations.getGroupCollaborations(groupId: group.id) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" queryParams `GetGroupCollaborationsQueryParams` - Query parameters of getGroupCollaborations method headers `GetGroupCollaborationsHeaders` - Headers of getGroupCollaborations method ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of collaboration objects. If there are no collaborations, an empty collection will be returned. --- ## Untitled *Type: page* MembershipsManager List user's groups List members of group Add user to group Get group membership Update group membership Remove user from… # MembershipsManager - [List user's groups](#list-users-groups) - [List members of group](#list-members-of-group) - [Add user to group](#add-user-to-group) - [Get group membership](#get-group-membership) - [Update group membership](#update-group-membership) - [Remove user from group](#remove-user-from-group) ## List user's groups Retrieves all the groups for a user. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getUserMemberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-memberships/). ``` try await client.memberships.getUserMemberships(userId: user.id) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" queryParams `GetUserMembershipsQueryParams` - Query parameters of getUserMemberships method headers `GetUserMembershipsHeaders` - Headers of getUserMemberships method ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## List members of group Retrieves all the members for a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupMemberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-memberships/). ``` try await client.memberships.getGroupMemberships(groupId: group.id) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" queryParams `GetGroupMembershipsQueryParams` - Query parameters of getGroupMemberships method headers `GetGroupMembershipsHeaders` - Headers of getGroupMemberships method ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## Add user to group Creates a group membership. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `createGroupMembership`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-group-memberships/). ``` try await client.memberships.createGroupMembership(requestBody: CreateGroupMembershipRequestBody(user: CreateGroupMembershipRequestBodyUserField(id: user.id), group: CreateGroupMembershipRequestBodyGroupField(id: group.id))) ``` ### Arguments requestBody `CreateGroupMembershipRequestBody` - Request body of createGroupMembership method queryParams `CreateGroupMembershipQueryParams` - Query parameters of createGroupMembership method headers `CreateGroupMembershipHeaders` - Headers of createGroupMembership method ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Get group membership Retrieves a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-group-memberships-id/). ``` try await client.memberships.getGroupMembershipById(groupMembershipId: groupMembership.id!) ``` ### Arguments groupMembershipId `String` - The ID of the group membership. Example: "434534" queryParams `GetGroupMembershipByIdQueryParams` - Query parameters of getGroupMembershipById method headers `GetGroupMembershipByIdHeaders` - Headers of getGroupMembershipById method ### Returns This function returns a value of type `GroupMembership`. Returns the group membership object. ## Update group membership Updates a user's group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `updateGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-group-memberships-id/). ``` try await client.memberships.updateGroupMembershipById(groupMembershipId: groupMembership.id!, requestBody: UpdateGroupMembershipByIdRequestBody(role: UpdateGroupMembershipByIdRequestBodyRoleField.admin)) ``` ### Arguments groupMembershipId `String` - The ID of the group membership. Example: "434534" requestBody `UpdateGroupMembershipByIdRequestBody` - Request body of updateGroupMembershipById method queryParams `UpdateGroupMembershipByIdQueryParams` - Query parameters of updateGroupMembershipById method headers `UpdateGroupMembershipByIdHeaders` - Headers of updateGroupMembershipById method ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Remove user from group Deletes a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `deleteGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-group-memberships-id/). ``` try await client.memberships.deleteGroupMembershipById(groupMembershipId: groupMembership.id!) ``` ### Arguments groupMembershipId `String` - The ID of the group membership. Example: "434534" headers `DeleteGroupMembershipByIdHeaders` - Headers of deleteGroupMembershipById method ### Returns This function returns a value of type ``. A blank response is returned if the membership was successfully deleted. --- ## Untitled *Type: page* MetadataCascadePoliciesManager List metadata cascade policies Create metadata cascade policy Get metadata cascade policy Remove metadata… # MetadataCascadePoliciesManager - [List metadata cascade policies](#list-metadata-cascade-policies) - [Create metadata cascade policy](#create-metadata-cascade-policy) - [Get metadata cascade policy](#get-metadata-cascade-policy) - [Remove metadata cascade policy](#remove-metadata-cascade-policy) - [Force-apply metadata cascade policy to folder](#force-apply-metadata-cascade-policy-to-folder) ## List metadata cascade policies Retrieves a list of all the metadata cascade policies that are applied to a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getMetadataCascadePolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies/). ``` try await client.metadataCascadePolicies.getMetadataCascadePolicies(queryParams: GetMetadataCascadePoliciesQueryParams(folderId: folder.id)) ``` ### Arguments queryParams `GetMetadataCascadePoliciesQueryParams` - Query parameters of getMetadataCascadePolicies method headers `GetMetadataCascadePoliciesHeaders` - Headers of getMetadataCascadePolicies method ### Returns This function returns a value of type `MetadataCascadePolicies`. Returns a list of metadata cascade policies. ## Create metadata cascade policy Creates a new metadata cascade policy that applies a given metadata template to a given folder and automatically cascades it down to any files within that folder. In order for the policy to be applied a metadata instance must first be applied to the folder the policy is to be applied to. This operation is performed by calling function `createMetadataCascadePolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies/). ``` try await client.metadataCascadePolicies.createMetadataCascadePolicy(requestBody: CreateMetadataCascadePolicyRequestBody(folderId: folder.id, scope: CreateMetadataCascadePolicyRequestBodyScopeField.enterprise, templateKey: templateKey)) ``` ### Arguments requestBody `CreateMetadataCascadePolicyRequestBody` - Request body of createMetadataCascadePolicy method headers `CreateMetadataCascadePolicyHeaders` - Headers of createMetadataCascadePolicy method ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a new of metadata cascade policy. ## Get metadata cascade policy Retrieve a specific metadata cascade policy assigned to a folder. This operation is performed by calling function `getMetadataCascadePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies-id/). ``` try await client.metadataCascadePolicies.getMetadataCascadePolicyById(metadataCascadePolicyId: cascadePolicyId) ``` ### Arguments metadataCascadePolicyId `String` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" headers `GetMetadataCascadePolicyByIdHeaders` - Headers of getMetadataCascadePolicyById method ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a metadata cascade policy. ## Remove metadata cascade policy Deletes a metadata cascade policy. This operation is performed by calling function `deleteMetadataCascadePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-cascade-policies-id/). ``` try await client.metadataCascadePolicies.deleteMetadataCascadePolicyById(metadataCascadePolicyId: cascadePolicyId) ``` ### Arguments metadataCascadePolicyId `String` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" headers `DeleteMetadataCascadePolicyByIdHeaders` - Headers of deleteMetadataCascadePolicyById method ### Returns This function returns a value of type ``. Returns an empty response when the policy is successfully deleted. ## Force-apply metadata cascade policy to folder Force the metadata on a folder with a metadata cascade policy to be applied to all of its children. This can be used after creating a new cascade policy to enforce the metadata to be cascaded down to all existing files within that folder. This operation is performed by calling function `applyMetadataCascadePolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies-id-apply/). ``` try await client.metadataCascadePolicies.applyMetadataCascadePolicy(metadataCascadePolicyId: cascadePolicyId, requestBody: ApplyMetadataCascadePolicyRequestBody(conflictResolution: ApplyMetadataCascadePolicyRequestBodyConflictResolutionField.overwrite)) ``` ### Arguments metadataCascadePolicyId `String` - The ID of the cascade policy to force-apply. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" requestBody `ApplyMetadataCascadePolicyRequestBody` - Request body of applyMetadataCascadePolicy method headers `ApplyMetadataCascadePolicyHeaders` - Headers of applyMetadataCascadePolicy method ### Returns This function returns a value of type ``. Returns an empty response when the API call was successful. The metadata cascade operation will be performed asynchronously. The API call will return directly, before the cascade operation is complete. There is currently no API to check for the status of this operation. --- ## Untitled *Type: page* MetadataTemplatesManager Find metadata template by instance ID Get metadata template by name Update metadata template Remove metadata… # MetadataTemplatesManager - [Find metadata template by instance ID](#find-metadata-template-by-instance-id) - [Get metadata template by name](#get-metadata-template-by-name) - [Update metadata template](#update-metadata-template) - [Remove metadata template](#remove-metadata-template) - [Get metadata template by ID](#get-metadata-template-by-id) - [List all global metadata templates](#list-all-global-metadata-templates) - [List all metadata templates for enterprise](#list-all-metadata-templates-for-enterprise) - [Create metadata template](#create-metadata-template) ## Find metadata template by instance ID Finds a metadata template by searching for the ID of an instance of the template. This operation is performed by calling function `getMetadataTemplatesByInstanceId`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates/). ``` try await client.metadataTemplates.getMetadataTemplatesByInstanceId(queryParams: GetMetadataTemplatesByInstanceIdQueryParams(metadataInstanceId: createdMetadataInstance.id!)) ``` ### Arguments queryParams `GetMetadataTemplatesByInstanceIdQueryParams` - Query parameters of getMetadataTemplatesByInstanceId method headers `GetMetadataTemplatesByInstanceIdHeaders` - Headers of getMetadataTemplatesByInstanceId method ### Returns This function returns a value of type `MetadataTemplates`. Returns a list containing the 1 metadata template that matches the instance ID. ## Get metadata template by name Retrieves a metadata template by its `scope` and `templateKey` values. To find the `scope` and `templateKey` for a template, list all templates for an enterprise or globally, or list all templates applied to a file or folder. This operation is performed by calling function `getMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id-id-schema/). ``` try await client.metadataTemplates.getMetadataTemplate(scope: GetMetadataTemplateScope.enterprise, templateKey: template.templateKey!) ``` ### Arguments scope `GetMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `GetMetadataTemplateHeaders` - Headers of getMetadataTemplate method ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template matching the `scope` and `template` name. ## Update metadata template Updates a metadata template. The metadata template can only be updated if the template already exists. The update is applied atomically. If any errors occur during the application of the operations, the metadata template will not be changed. This operation is performed by calling function `updateMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-id-id-schema/). ``` try await client.metadataTemplates.updateMetadataTemplate(scope: UpdateMetadataTemplateScope.enterprise, templateKey: templateKey, requestBody: [UpdateMetadataTemplateRequestBody(op: UpdateMetadataTemplateRequestBodyOpField.addField, fieldKey: "newfieldname", data: ["type": "string", "displayName": "newFieldName"])]) ``` ### Arguments scope `UpdateMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `[UpdateMetadataTemplateRequestBody]` - Request body of updateMetadataTemplate method headers `UpdateMetadataTemplateHeaders` - Headers of updateMetadataTemplate method ### Returns This function returns a value of type `MetadataTemplate`. Returns the updated metadata template, with the custom template data included. ## Remove metadata template Delete a metadata template and its instances. This deletion is permanent and can not be reversed. This operation is performed by calling function `deleteMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-templates-id-id-schema/). ``` try await client.metadataTemplates.deleteMetadataTemplate(scope: DeleteMetadataTemplateScope.enterprise, templateKey: template.templateKey!) ``` ### Arguments scope `DeleteMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `DeleteMetadataTemplateHeaders` - Headers of deleteMetadataTemplate method ### Returns This function returns a value of type ``. Returns an empty response when the metadata template is successfully deleted. ## Get metadata template by ID Retrieves a metadata template by its ID. This operation is performed by calling function `getMetadataTemplateById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id/). ``` try await client.metadataTemplates.getMetadataTemplateById(templateId: template.id) ``` ### Arguments templateId `String` - The ID of the template. Example: "f7a9891f" headers `GetMetadataTemplateByIdHeaders` - Headers of getMetadataTemplateById method ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template that matches the ID. ## List all global metadata templates Used to retrieve all generic, global metadata templates available to all enterprises using Box. This operation is performed by calling function `getGlobalMetadataTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-global/). ``` try await client.metadataTemplates.getGlobalMetadataTemplates() ``` ### Arguments queryParams `GetGlobalMetadataTemplatesQueryParams` - Query parameters of getGlobalMetadataTemplates method headers `GetGlobalMetadataTemplatesHeaders` - Headers of getGlobalMetadataTemplates method ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates available to all enterprises and their corresponding schema. ## List all metadata templates for enterprise Used to retrieve all metadata templates created to be used specifically within the user's enterprise. This operation is performed by calling function `getEnterpriseMetadataTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise/). ``` try await client.metadataTemplates.getEnterpriseMetadataTemplates() ``` ### Arguments queryParams `GetEnterpriseMetadataTemplatesQueryParams` - Query parameters of getEnterpriseMetadataTemplates method headers `GetEnterpriseMetadataTemplatesHeaders` - Headers of getEnterpriseMetadataTemplates method ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates within an enterprise and their corresponding schema. ## Create metadata template Creates a new metadata template that can be applied to files and folders. This operation is performed by calling function `createMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema/). ``` try await client.metadataTemplates.createMetadataTemplate(requestBody: CreateMetadataTemplateRequestBody(scope: "enterprise", displayName: templateKey, templateKey: templateKey, fields: [CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.string, key: "testName", displayName: "testName"), CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.float, key: "age", displayName: "age"), CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.date, key: "birthDate", displayName: "birthDate"), CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.enum_, key: "countryCode", displayName: "countryCode", options: [CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "US"), CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "CA")]), CreateMetadataTemplateRequestBodyFieldsField(type: CreateMetadataTemplateRequestBodyFieldsTypeField.multiSelect, key: "sports", displayName: "sports", options: [CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "basketball"), CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "football"), CreateMetadataTemplateRequestBodyFieldsOptionsField(key: "tennis")])])) ``` ### Arguments requestBody `CreateMetadataTemplateRequestBody` - Request body of createMetadataTemplate method headers `CreateMetadataTemplateHeaders` - Headers of createMetadataTemplate method ### Returns This function returns a value of type `MetadataTemplate`. The schema representing the metadata template created. --- ## Untitled *Type: page* RecentItemsManager List recently accessed items List recently accessed items Returns information about the recent items accessed by a user… # RecentItemsManager - [List recently accessed items](#list-recently-accessed-items) ## List recently accessed items Returns information about the recent items accessed by a user, either in the last 90 days or up to the last 1000 items accessed. This operation is performed by calling function `getRecentItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-recent-items/). ``` try await client.recentItems.getRecentItems() ``` ### Arguments queryParams `GetRecentItemsQueryParams` - Query parameters of getRecentItems method headers `GetRecentItemsHeaders` - Headers of getRecentItems method ### Returns This function returns a value of type `RecentItems`. Returns a list recent items access by a user. --- ## Untitled *Type: page* RetentionPoliciesManager List retention policies Create retention policy Get retention policy Update retention policy Delete retention… # RetentionPoliciesManager - [List retention policies](#list-retention-policies) - [Create retention policy](#create-retention-policy) - [Get retention policy](#get-retention-policy) - [Update retention policy](#update-retention-policy) - [Delete retention policy](#delete-retention-policy) ## List retention policies Retrieves all of the retention policies for an enterprise. This operation is performed by calling function `getRetentionPolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies/). ``` try await client.retentionPolicies.getRetentionPolicies() ``` ### Arguments queryParams `GetRetentionPoliciesQueryParams` - Query parameters of getRetentionPolicies method headers `GetRetentionPoliciesHeaders` - Headers of getRetentionPolicies method ### Returns This function returns a value of type `RetentionPolicies`. Returns a list retention policies in the enterprise. ## Create retention policy Creates a retention policy. This operation is performed by calling function `createRetentionPolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policies/). ``` try await client.retentionPolicies.createRetentionPolicy(requestBody: CreateRetentionPolicyRequestBody(policyName: retentionPolicyName, policyType: CreateRetentionPolicyRequestBodyPolicyTypeField.finite, areOwnersNotified: true, canOwnerExtendRetention: true, description: retentionDescription, dispositionAction: CreateRetentionPolicyRequestBodyDispositionActionField.removeRetention, retentionLength: "1", retentionType: CreateRetentionPolicyRequestBodyRetentionTypeField.modifiable)) ``` ### Arguments requestBody `CreateRetentionPolicyRequestBody` - Request body of createRetentionPolicy method headers `CreateRetentionPolicyHeaders` - Headers of createRetentionPolicy method ### Returns This function returns a value of type `RetentionPolicy`. Returns a new retention policy object. ## Get retention policy Retrieves a retention policy. This operation is performed by calling function `getRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id/). ``` try await client.retentionPolicies.getRetentionPolicyById(retentionPolicyId: retentionPolicy.id) ``` ### Arguments retentionPolicyId `String` - The ID of the retention policy. Example: "982312" queryParams `GetRetentionPolicyByIdQueryParams` - Query parameters of getRetentionPolicyById method headers `GetRetentionPolicyByIdHeaders` - Headers of getRetentionPolicyById method ### Returns This function returns a value of type `RetentionPolicy`. Returns the retention policy object. ## Update retention policy Updates a retention policy. This operation is performed by calling function `updateRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-retention-policies-id/). ``` try await client.retentionPolicies.updateRetentionPolicyById(retentionPolicyId: retentionPolicy.id, requestBody: UpdateRetentionPolicyByIdRequestBody(policyName: updatedRetentionPolicyName)) ``` ### Arguments retentionPolicyId `String` - The ID of the retention policy. Example: "982312" requestBody `UpdateRetentionPolicyByIdRequestBody` - Request body of updateRetentionPolicyById method headers `UpdateRetentionPolicyByIdHeaders` - Headers of updateRetentionPolicyById method ### Returns This function returns a value of type `RetentionPolicy`. Returns the updated retention policy object. ## Delete retention policy Permanently deletes a retention policy. This operation is performed by calling function `deleteRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policies-id/). ``` try await client.retentionPolicies.deleteRetentionPolicyById(retentionPolicyId: retentionPolicy.id) ``` ### Arguments retentionPolicyId `String` - The ID of the retention policy. Example: "982312" headers `DeleteRetentionPolicyByIdHeaders` - Headers of deleteRetentionPolicyById method ### Returns This function returns a value of type ``. Returns an empty response when the policy has been deleted. --- ## Untitled *Type: page* RetentionPolicyAssignmentsManager List retention policy assignments Assign retention policy Get retention policy assignment Remove retention… # RetentionPolicyAssignmentsManager - [List retention policy assignments](#list-retention-policy-assignments) - [Assign retention policy](#assign-retention-policy) - [Get retention policy assignment](#get-retention-policy-assignment) - [Remove retention policy assignment](#remove-retention-policy-assignment) - [Get files under retention](#get-files-under-retention) ## List retention policy assignments Returns a list of all retention policy assignments associated with a specified retention policy. This operation is performed by calling function `getRetentionPolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id-assignments/). ``` try await client.retentionPolicyAssignments.getRetentionPolicyAssignments(retentionPolicyId: retentionPolicy.id) ``` ### Arguments retentionPolicyId `String` - The ID of the retention policy. Example: "982312" queryParams `GetRetentionPolicyAssignmentsQueryParams` - Query parameters of getRetentionPolicyAssignments method headers `GetRetentionPolicyAssignmentsHeaders` - Headers of getRetentionPolicyAssignments method ### Returns This function returns a value of type `RetentionPolicyAssignments`. Returns a list of the retention policy assignments associated with the specified retention policy. ## Assign retention policy Assigns a retention policy to an item. This operation is performed by calling function `createRetentionPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policy-assignments/). ``` try await client.retentionPolicyAssignments.createRetentionPolicyAssignment(requestBody: CreateRetentionPolicyAssignmentRequestBody(policyId: retentionPolicy.id, assignTo: CreateRetentionPolicyAssignmentRequestBodyAssignToField(type: CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField.folder, id: folder.id))) ``` ### Arguments requestBody `CreateRetentionPolicyAssignmentRequestBody` - Request body of createRetentionPolicyAssignment method headers `CreateRetentionPolicyAssignmentHeaders` - Headers of createRetentionPolicyAssignment method ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns a new retention policy assignment object. ## Get retention policy assignment Retrieves a retention policy assignment. This operation is performed by calling function `getRetentionPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id/). ``` try await client.retentionPolicyAssignments.getRetentionPolicyAssignmentById(retentionPolicyAssignmentId: retentionPolicyAssignment.id) ``` ### Arguments retentionPolicyAssignmentId `String` - The ID of the retention policy assignment. Example: "1233123" queryParams `GetRetentionPolicyAssignmentByIdQueryParams` - Query parameters of getRetentionPolicyAssignmentById method headers `GetRetentionPolicyAssignmentByIdHeaders` - Headers of getRetentionPolicyAssignmentById method ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns the retention policy assignment object. ## Remove retention policy assignment Removes a retention policy assignment applied to content. This operation is performed by calling function `deleteRetentionPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policy-assignments-id/). ``` try await client.retentionPolicyAssignments.deleteRetentionPolicyAssignmentById(retentionPolicyAssignmentId: retentionPolicyAssignment.id) ``` ### Arguments retentionPolicyAssignmentId `String` - The ID of the retention policy assignment. Example: "1233123" headers `DeleteRetentionPolicyAssignmentByIdHeaders` - Headers of deleteRetentionPolicyAssignmentById method ### Returns This function returns a value of type ``. Returns an empty response when the policy assignment is successfully deleted. ## Get files under retention Returns a list of files under retention for a retention policy assignment. This operation is performed by calling function `getFilesUnderRetentionPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention/). ``` try await client.retentionPolicyAssignments.getFilesUnderRetentionPolicyAssignment(retentionPolicyAssignmentId: retentionPolicyAssignment.id) ``` ### Arguments retentionPolicyAssignmentId `String` - The ID of the retention policy assignment. Example: "1233123" queryParams `GetFilesUnderRetentionPolicyAssignmentQueryParams` - Query parameters of getFilesUnderRetentionPolicyAssignment method headers `GetFilesUnderRetentionPolicyAssignmentHeaders` - Headers of getFilesUnderRetentionPolicyAssignment method ### Returns This function returns a value of type `FilesUnderRetention`. Returns a list of files under retention that are associated with the specified retention policy assignment. --- ## Untitled *Type: page* Documentation High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available… # Documentation ## High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available by topic: - [Ai](https://developer.box.com/9dc7c8f4acf9e1b3a61220e8d37c6b1c/Ai.md) - [Ai studio](https://developer.box.com/227b81b2fe46c92e313ad164ec5d20a8/AiStudio.md) - [App item associations](https://developer.box.com/04d05fc1f7b6348be9ec6598399f2fb9/AppItemAssociations.md) - [Archives](https://developer.box.com/ac1c7ce53ed9efd399e6bab4543a6fac/Archives.md) - [Authorization](https://developer.box.com/1e2d6b38f474114c770c3726cbae720c/Authorization.md) - [Avatars](https://developer.box.com/6c67c5aed1b3fd03651dd8388f7ec5c1/Avatars.md) - [Chunked uploads](https://developer.box.com/74295a615fd35cf795da5f1a09b90f1d/ChunkedUploads.md) - [Classifications](https://developer.box.com/2671efd2e8d76211b6655a52250d2d36/Classifications.md) - [Collaboration allowlist entries](https://developer.box.com/de2f805c3217e1fefad04d2971390909/CollaborationAllowlistEntries.md) - [Collaboration allowlist exempt targets](https://developer.box.com/e5d4c14e8586a311cac61d795be88b30/CollaborationAllowlistExemptTargets.md) - [Collections](https://developer.box.com/f17f7569cbfd9c98f0a1e31a92af466a/Collections.md) - [Comments](https://developer.box.com/fba7172d9a3d616981ed23155dd80e15/Comments.md) - [Device pinners](https://developer.box.com/3e20308e2bd56cc3e00aa572f3169558/DevicePinners.md) - [Docgen](https://developer.box.com/e32247350e2685895d3db4f7a0fbc044/Docgen.md) - [Docgen template](https://developer.box.com/6ff2bdbd3914ca62b003bbc8bb293d58/DocgenTemplate.md) - [Downloads](https://developer.box.com/a58df25d77160e5c8d375e0a10e673d2/Downloads.md) - [Email aliases](https://developer.box.com/7b9c9b272cc0710edd90f47c7a9997b9/EmailAliases.md) - [Events](https://developer.box.com/c8500a2472482fa596e33d83f3268cde/Events.md) - [File classifications](https://developer.box.com/0a3175a4c9fd6002fd7bdecfe4cd8ab9/FileClassifications.md) - [File metadata](https://developer.box.com/6bcc4d28a4c5d3026aac4148ffd88bd4/FileMetadata.md) - [File requests](https://developer.box.com/8be9a969c48e7b20564d19b137cd741c/FileRequests.md) - [File version legal holds](https://developer.box.com/c0e1e9db5819f8c336b58b167ed78b52/FileVersionLegalHolds.md) - [File version retentions](https://developer.box.com/bed1b4d1aed3c4d6a156909a9ff53e62/FileVersionRetentions.md) - [File versions](https://developer.box.com/169bff239656467e490a640102ef7195/FileVersions.md) - [File watermarks](https://developer.box.com/d640bba4ba90067afeeeb91f9e76f554/FileWatermarks.md) - [Files](https://developer.box.com/3a8a7052b0b247e7101ea874ec3e0fee/Files.md) - [Folder classifications](https://developer.box.com/7a1b8d8694a979ec35173378cd982566/FolderClassifications.md) - [Folder locks](https://developer.box.com/069dbc54498d9c7fc175cdc1f5e99450/FolderLocks.md) - [Folder metadata](https://developer.box.com/1685743365ab810fa59b68205859afbb/FolderMetadata.md) - [Folder watermarks](https://developer.box.com/8a00f626a5646d60d2824c5a62d64d88/FolderWatermarks.md) - [Folders](https://developer.box.com/6af009ae17bee91fc9af22e2a34fe186/Folders.md) - [Groups](https://developer.box.com/ed02325488bf39dedd6ed7c72d3de994/Groups.md) - [Hub collaborations](https://developer.box.com/3d26bc1f9973776cf177199aaa59c467/HubCollaborations.md) - [Hub items](https://developer.box.com/ef488412d232325f94d0d2ba38fce24a/HubItems.md) - [Hubs](https://developer.box.com/e46fcccad7150030ed5335ff40bb0db5/Hubs.md) - [Integration mappings](https://developer.box.com/aa5dd619f70e4c5df9f04f99c1d5a07f/IntegrationMappings.md) - [Invites](https://developer.box.com/5f6091aa675bd1609535d0a454cdb9ab/Invites.md) - [Legal hold policies](https://developer.box.com/756d3c4ef486e62c32270a30d00347f3/LegalHoldPolicies.md) - [Legal hold policy assignments](https://developer.box.com/706d9a05ae66ab79cd331acc8fa65a41/LegalHoldPolicyAssignments.md) - [List collaborations](https://developer.box.com/37595e2cc7f6a4ef9bee6875bd3ba09d/ListCollaborations.md) - [Memberships](https://developer.box.com/10c6cbbadfb2a7553ec80f5dc4dd5112/Memberships.md) - [Metadata cascade policies](https://developer.box.com/a959124da0fec5ab80f1981549b5d7e8/MetadataCascadePolicies.md) - [Metadata templates](https://developer.box.com/b483047323b44b9268f8190adf76973e/MetadataTemplates.md) - [Recent items](https://developer.box.com/090a8a7bbd34120c05a2c668a3a8223e/RecentItems.md) - [Retention policies](https://developer.box.com/69f48cc4d528fc2353bb27564e6e1442/RetentionPolicies.md) - [Retention policy assignments](https://developer.box.com/36f77dfbfa720f58817ea61b2be8f446/RetentionPolicyAssignments.md) - [Search](https://developer.box.com/9291341229610f7689bb08aaafd23481/Search.md) - [Session termination](https://developer.box.com/f3f8feb1c444f7338b47016f00078f8e/SessionTermination.md) - [Shared links app items](https://developer.box.com/ec53f626c3e0ac3c867245d156f36ac7/SharedLinksAppItems.md) - [Shared links files](https://developer.box.com/ffb17430c963c811ce944e00d40f3966/SharedLinksFiles.md) - [Shared links folders](https://developer.box.com/0c0d7b6b22d1daa10d5b53412c6ec662/SharedLinksFolders.md) - [Shared links web links](https://developer.box.com/f1b922ccab5c43cbbb23774c81929a8e/SharedLinksWebLinks.md) - [Shield information barrier reports](https://developer.box.com/89089c0bd63e32a77dc4cf07e8207ffb/ShieldInformationBarrierReports.md) - [Shield information barrier segment members](https://developer.box.com/4f974cd274f15085bb0e821c4e6045b7/ShieldInformationBarrierSegmentMembers.md) - [Shield information barrier segment restrictions](https://developer.box.com/0aaeabb6fa6bc3e81cd3d605622131db/ShieldInformationBarrierSegmentRestrictions.md) - [Shield information barrier segments](https://developer.box.com/e98dfcd459d5d55c755dd7f6497ce238/ShieldInformationBarrierSegments.md) - [Shield information barriers](https://developer.box.com/a20977d47e2f235dc7c003b00afcb256/ShieldInformationBarriers.md) - [Shield lists](https://developer.box.com/0a23f842dd1ee70c0e0087764e931618/ShieldLists.md) - [Sign requests](https://developer.box.com/15f7637dd800aa9f45922a34db4c8292/SignRequests.md) - [Sign templates](https://developer.box.com/256bce276ab7a5f18c87c45bd15c35fe/SignTemplates.md) - [Skills](https://developer.box.com/a6bc430e183348c7495ad928c77f2680/Skills.md) - [Storage policies](https://developer.box.com/c254ac5008f6a1c060cce5d76faf67dd/StoragePolicies.md) - [Storage policy assignments](https://developer.box.com/3e1c2bafd123a298bee4f0eef28377cc/StoragePolicyAssignments.md) - [Task assignments](https://developer.box.com/f08cb5275bdebdbea309b616da608914/TaskAssignments.md) - [Tasks](https://developer.box.com/d27989287e1e1e32eea39a7ad183b189/Tasks.md) - [Terms of service user statuses](https://developer.box.com/913dd8ed7cd7ab2716860a153fd043ad/TermsOfServiceUserStatuses.md) - [Terms of services](https://developer.box.com/faa36281b3b1a18ebdf28b32d58b9261/TermsOfServices.md) - [Transfer](https://developer.box.com/1c9ddfbba246afed021d7e220cb36ce2/Transfer.md) - [Trashed files](https://developer.box.com/00eeda48126195ddbd138ffa158b2a33/TrashedFiles.md) - [Trashed folders](https://developer.box.com/2c52b31a2527c35d607f6613a302d17a/TrashedFolders.md) - [Trashed items](https://developer.box.com/9f7c64d0af63556089078be05fbb6c41/TrashedItems.md) - [Trashed web links](https://developer.box.com/3226282df756748ad546d1c165cbf05f/TrashedWebLinks.md) - [Uploads](https://developer.box.com/e7966845f3cc06ba93d89fd3b6fc9173/Uploads.md) - [User collaborations](https://developer.box.com/0fd9cd55adf5e72e28cd53a7e89b0502/UserCollaborations.md) - [Users](https://developer.box.com/cdaeb56fa642c08fc0c6e056ed316cc7/Users.md) - [Web links](https://developer.box.com/222b06cdf7fcfc38bdf3cf7430dc52f1/WebLinks.md) - [Webhooks](https://developer.box.com/700aacebc873f0ba29bf185a0e3babbb/Webhooks.md) - [Workflows](https://developer.box.com/ec2b9b76c9ad7a05f78a8a4662785ac5/Workflows.md) - [Zip downloads](https://developer.box.com/0a2c8bf926c220dbc74be2a1a10f608d/ZipDownloads.md) --- ## Untitled *Type: page* SearchManager Query files/folders by metadata Search for content Query files/folders by metadata Create a search using SQL-like syntax to… # SearchManager - [Query files/folders by metadata](#query-files-folders-by-metadata) - [Search for content](#search-for-content) ## Query files/folders by metadata Create a search using SQL-like syntax to return items that match specific metadata. By default, this endpoint returns only the most basic info about the items for which the query matches. To get additional fields for each item, including any of the metadata, use the `fields` attribute in the query. This operation is performed by calling function `searchByMetadataQuery`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-queries-execute-read/). ``` try await client.search.searchByMetadataQuery(requestBody: MetadataQuery(ancestorFolderId: "0", from: searchFrom, query: "name = :name AND age < :age AND birthDate >= :birthDate AND countryCode = :countryCode AND sports = :sports", queryParams: ["name": "John", "age": 50, "birthDate": "2001-01-01T02:20:10.120Z", "countryCode": "US", "sports": ["basketball", "tennis"]])) ``` ### Arguments requestBody `MetadataQuery` - Request body of searchByMetadataQuery method headers `SearchByMetadataQueryHeaders` - Headers of searchByMetadataQuery method ### Returns This function returns a value of type `MetadataQueryResults`. Returns a list of files and folders that match this metadata query. ## Search for content Searches for files, folders, web links, and shared files across the users content or across the entire enterprise. This operation is performed by calling function `searchForContent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-search/). *Currently we don't have an example for calling `searchForContent` in integration tests* ### Arguments queryParams `SearchForContentQueryParams` - Query parameters of searchForContent method headers `SearchForContentHeaders` - Headers of searchForContent method ### Returns This function returns a value of type `SearchResultsOrSearchResultsWithSharedLinks`. Returns a collection of search results. If there are no matching search results, the `entries` array will be empty. --- ## Untitled *Type: page* SharedLinksAppItemsManager Find app item for shared link Find app item for shared link Returns the app item represented by a shared link… # SharedLinksAppItemsManager - [Find app item for shared link](#find-app-item-for-shared-link) ## Find app item for shared link Returns the app item represented by a shared link. The link can originate from the current enterprise or another. This operation is performed by calling function `findAppItemForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--app-items/). ``` try await client.sharedLinksAppItems.findAppItemForSharedLink(headers: FindAppItemForSharedLinkHeaders(boxapi: "\("shared_link=")\(appItemSharedLink)")) ``` ### Arguments headers `FindAppItemForSharedLinkHeaders` - Headers of findAppItemForSharedLink method ### Returns This function returns a value of type `AppItem`. Returns a full app item resource if the shared link is valid and the user has access to it. --- ## Untitled *Type: page* SessionTerminationManager Create jobs to terminate users session Create jobs to terminate user group session Create jobs to terminate users… # SessionTerminationManager - [Create jobs to terminate users session](#create-jobs-to-terminate-users-session) - [Create jobs to terminate user group session](#create-jobs-to-terminate-user-group-session) ## Create jobs to terminate users session Validates the roles and permissions of the user, and creates asynchronous jobs to terminate the user's sessions. Returns the status for the POST request. This operation is performed by calling function `terminateUsersSessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-terminate-sessions/). ``` try await client.sessionTermination.terminateUsersSessions(requestBody: TerminateUsersSessionsRequestBody(userIds: [Utils.getEnvironmentVariable(name: "USER_ID")], userLogins: [user.login!])) ``` ### Arguments requestBody `TerminateUsersSessionsRequestBody` - Request body of terminateUsersSessions method headers `TerminateUsersSessionsHeaders` - Headers of terminateUsersSessions method ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. ## Create jobs to terminate user group session Validates the roles and permissions of the group, and creates asynchronous jobs to terminate the group's sessions. Returns the status for the POST request. This operation is performed by calling function `terminateGroupsSessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups-terminate-sessions/). ``` try await client.sessionTermination.terminateGroupsSessions(requestBody: TerminateGroupsSessionsRequestBody(groupIds: [group.id])) ``` ### Arguments requestBody `TerminateGroupsSessionsRequestBody` - Request body of terminateGroupsSessions method headers `TerminateGroupsSessionsHeaders` - Headers of terminateGroupsSessions method ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. --- ## Untitled *Type: page* SharedLinksFilesManager Find file for shared link Get shared link for file Add shared link to file Update shared link on file Remove shared… # SharedLinksFilesManager - [Find file for shared link](#find-file-for-shared-link) - [Get shared link for file](#get-shared-link-for-file) - [Add shared link to file](#add-shared-link-to-file) - [Update shared link on file](#update-shared-link-on-file) - [Remove shared link from file](#remove-shared-link-from-file) ## Find file for shared link Returns the file represented by a shared link. A shared file can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared file when only given a shared link. The `shared_link_permission_options` array field can be returned by requesting it in the `fields` query parameter. This operation is performed by calling function `findFileForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items/). ``` try await userClient.sharedLinksFiles.findFileForSharedLink(queryParams: FindFileForSharedLinkQueryParams(), headers: FindFileForSharedLinkHeaders(boxapi: "\("shared_link=")\(fileFromApi.sharedLink!.url)\("&shared_link_password=Secret123@")")) ``` ### Arguments queryParams `FindFileForSharedLinkQueryParams` - Query parameters of findFileForSharedLink method headers `FindFileForSharedLinkHeaders` - Headers of findFileForSharedLink method ### Returns This function returns a value of type `FileFull`. Returns a full file resource if the shared link is valid and the user has access to it. ## Get shared link for file Gets the information for a shared link on a file. This operation is performed by calling function `getSharedLinkForFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id--get-shared-link/). ``` try await client.sharedLinksFiles.getSharedLinkForFile(fileId: fileId, queryParams: GetSharedLinkForFileQueryParams(fields: "shared_link")) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetSharedLinkForFileQueryParams` - Query parameters of getSharedLinkForFile method headers `GetSharedLinkForFileHeaders` - Headers of getSharedLinkForFile method ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with the additional shared link information. ## Add shared link to file Adds a shared link to a file. This operation is performed by calling function `addShareLinkToFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--add-shared-link/). ``` try await client.sharedLinksFiles.addShareLinkToFile(fileId: fileId, requestBody: AddShareLinkToFileRequestBody(sharedLink: AddShareLinkToFileRequestBodySharedLinkField(access: AddShareLinkToFileRequestBodySharedLinkAccessField.open, password: "Secret123@")), queryParams: AddShareLinkToFileQueryParams(fields: "shared_link")) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `AddShareLinkToFileRequestBody` - Request body of addShareLinkToFile method queryParams `AddShareLinkToFileQueryParams` - Query parameters of addShareLinkToFile method headers `AddShareLinkToFileHeaders` - Headers of addShareLinkToFile method ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with a new shared link attached. ## Update shared link on file Updates a shared link on a file. This operation is performed by calling function `updateSharedLinkOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--update-shared-link/). ``` try await client.sharedLinksFiles.updateSharedLinkOnFile(fileId: fileId, requestBody: UpdateSharedLinkOnFileRequestBody(sharedLink: UpdateSharedLinkOnFileRequestBodySharedLinkField(access: UpdateSharedLinkOnFileRequestBodySharedLinkAccessField.collaborators)), queryParams: UpdateSharedLinkOnFileQueryParams(fields: "shared_link")) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateSharedLinkOnFileRequestBody` - Request body of updateSharedLinkOnFile method queryParams `UpdateSharedLinkOnFileQueryParams` - Query parameters of updateSharedLinkOnFile method headers `UpdateSharedLinkOnFileHeaders` - Headers of updateSharedLinkOnFile method ### Returns This function returns a value of type `FileFull`. Returns a basic representation of the file, with the updated shared link attached. ## Remove shared link from file Removes a shared link from a file. This operation is performed by calling function `removeSharedLinkFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--remove-shared-link/). *Currently we don't have an example for calling `removeSharedLinkFromFile` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `RemoveSharedLinkFromFileRequestBody` - Request body of removeSharedLinkFromFile method queryParams `RemoveSharedLinkFromFileQueryParams` - Query parameters of removeSharedLinkFromFile method headers `RemoveSharedLinkFromFileHeaders` - Headers of removeSharedLinkFromFile method ### Returns This function returns a value of type `FileFull`. Returns a basic representation of a file, with the shared link removed. --- ## Untitled *Type: page* SharedLinksFoldersManager Find folder for shared link Get shared link for folder Add shared link to folder Update shared link on folder… # SharedLinksFoldersManager - [Find folder for shared link](#find-folder-for-shared-link) - [Get shared link for folder](#get-shared-link-for-folder) - [Add shared link to folder](#add-shared-link-to-folder) - [Update shared link on folder](#update-shared-link-on-folder) - [Remove shared link from folder](#remove-shared-link-from-folder) ## Find folder for shared link Return the folder represented by a shared link. A shared folder can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared folder when only given a shared link. This operation is performed by calling function `findFolderForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--folders/). ``` try await userClient.sharedLinksFolders.findFolderForSharedLink(queryParams: FindFolderForSharedLinkQueryParams(), headers: FindFolderForSharedLinkHeaders(boxapi: "\("shared_link=")\(folderFromApi.sharedLink!.url)\("&shared_link_password=Secret123@")")) ``` ### Arguments queryParams `FindFolderForSharedLinkQueryParams` - Query parameters of findFolderForSharedLink method headers `FindFolderForSharedLinkHeaders` - Headers of findFolderForSharedLink method ### Returns This function returns a value of type `FolderFull`. Returns a full folder resource if the shared link is valid and the user has access to it. ## Get shared link for folder Gets the information for a shared link on a folder. This operation is performed by calling function `getSharedLinkForFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id--get-shared-link/). ``` try await client.sharedLinksFolders.getSharedLinkForFolder(folderId: folder.id, queryParams: GetSharedLinkForFolderQueryParams(fields: "shared_link")) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetSharedLinkForFolderQueryParams` - Query parameters of getSharedLinkForFolder method headers `GetSharedLinkForFolderHeaders` - Headers of getSharedLinkForFolder method ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with the additional shared link information. ## Add shared link to folder Adds a shared link to a folder. This operation is performed by calling function `addShareLinkToFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--add-shared-link/). ``` try await client.sharedLinksFolders.addShareLinkToFolder(folderId: folder.id, requestBody: AddShareLinkToFolderRequestBody(sharedLink: AddShareLinkToFolderRequestBodySharedLinkField(access: AddShareLinkToFolderRequestBodySharedLinkAccessField.open, password: "Secret123@")), queryParams: AddShareLinkToFolderQueryParams(fields: "shared_link")) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `AddShareLinkToFolderRequestBody` - Request body of addShareLinkToFolder method queryParams `AddShareLinkToFolderQueryParams` - Query parameters of addShareLinkToFolder method headers `AddShareLinkToFolderHeaders` - Headers of addShareLinkToFolder method ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with a new shared link attached. ## Update shared link on folder Updates a shared link on a folder. This operation is performed by calling function `updateSharedLinkOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--update-shared-link/). ``` try await client.sharedLinksFolders.updateSharedLinkOnFolder(folderId: folder.id, requestBody: UpdateSharedLinkOnFolderRequestBody(sharedLink: UpdateSharedLinkOnFolderRequestBodySharedLinkField(access: UpdateSharedLinkOnFolderRequestBodySharedLinkAccessField.collaborators)), queryParams: UpdateSharedLinkOnFolderQueryParams(fields: "shared_link")) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateSharedLinkOnFolderRequestBody` - Request body of updateSharedLinkOnFolder method queryParams `UpdateSharedLinkOnFolderQueryParams` - Query parameters of updateSharedLinkOnFolder method headers `UpdateSharedLinkOnFolderHeaders` - Headers of updateSharedLinkOnFolder method ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of the folder, with the updated shared link attached. ## Remove shared link from folder Removes a shared link from a folder. This operation is performed by calling function `removeSharedLinkFromFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--remove-shared-link/). *Currently we don't have an example for calling `removeSharedLinkFromFolder` in integration tests* ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `RemoveSharedLinkFromFolderRequestBody` - Request body of removeSharedLinkFromFolder method queryParams `RemoveSharedLinkFromFolderQueryParams` - Query parameters of removeSharedLinkFromFolder method headers `RemoveSharedLinkFromFolderHeaders` - Headers of removeSharedLinkFromFolder method ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of a folder, with the shared link removed. --- ## Untitled *Type: page* SharedLinksWebLinksManager Find web link for shared link Get shared link for web link Add shared link to web link Update shared link on web… # SharedLinksWebLinksManager - [Find web link for shared link](#find-web-link-for-shared-link) - [Get shared link for web link](#get-shared-link-for-web-link) - [Add shared link to web link](#add-shared-link-to-web-link) - [Update shared link on web link](#update-shared-link-on-web-link) - [Remove shared link from web link](#remove-shared-link-from-web-link) ## Find web link for shared link Returns the web link represented by a shared link. A shared web link can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared web link when only given a shared link. This operation is performed by calling function `findWebLinkForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--web-links/). ``` try await userClient.sharedLinksWebLinks.findWebLinkForSharedLink(queryParams: FindWebLinkForSharedLinkQueryParams(), headers: FindWebLinkForSharedLinkHeaders(boxapi: "\("shared_link=")\(webLinkFromApi.sharedLink!.url)\("&shared_link_password=Secret123@")")) ``` ### Arguments queryParams `FindWebLinkForSharedLinkQueryParams` - Query parameters of findWebLinkForSharedLink method headers `FindWebLinkForSharedLinkHeaders` - Headers of findWebLinkForSharedLink method ### Returns This function returns a value of type `WebLink`. Returns a full web link resource if the shared link is valid and the user has access to it. ## Get shared link for web link Gets the information for a shared link on a web link. This operation is performed by calling function `getSharedLinkForWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id--get-shared-link/). ``` try await client.sharedLinksWebLinks.getSharedLinkForWebLink(webLinkId: webLinkId, queryParams: GetSharedLinkForWebLinkQueryParams(fields: "shared_link")) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" queryParams `GetSharedLinkForWebLinkQueryParams` - Query parameters of getSharedLinkForWebLink method headers `GetSharedLinkForWebLinkHeaders` - Headers of getSharedLinkForWebLink method ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with the additional shared link information. ## Add shared link to web link Adds a shared link to a web link. This operation is performed by calling function `addShareLinkToWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--add-shared-link/). ``` try await client.sharedLinksWebLinks.addShareLinkToWebLink(webLinkId: webLinkId, requestBody: AddShareLinkToWebLinkRequestBody(sharedLink: AddShareLinkToWebLinkRequestBodySharedLinkField(access: AddShareLinkToWebLinkRequestBodySharedLinkAccessField.open, password: "Secret123@")), queryParams: AddShareLinkToWebLinkQueryParams(fields: "shared_link")) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `AddShareLinkToWebLinkRequestBody` - Request body of addShareLinkToWebLink method queryParams `AddShareLinkToWebLinkQueryParams` - Query parameters of addShareLinkToWebLink method headers `AddShareLinkToWebLinkHeaders` - Headers of addShareLinkToWebLink method ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with a new shared link attached. ## Update shared link on web link Updates a shared link on a web link. This operation is performed by calling function `updateSharedLinkOnWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--update-shared-link/). ``` try await client.sharedLinksWebLinks.updateSharedLinkOnWebLink(webLinkId: webLinkId, requestBody: UpdateSharedLinkOnWebLinkRequestBody(sharedLink: UpdateSharedLinkOnWebLinkRequestBodySharedLinkField(access: UpdateSharedLinkOnWebLinkRequestBodySharedLinkAccessField.collaborators)), queryParams: UpdateSharedLinkOnWebLinkQueryParams(fields: "shared_link")) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `UpdateSharedLinkOnWebLinkRequestBody` - Request body of updateSharedLinkOnWebLink method queryParams `UpdateSharedLinkOnWebLinkQueryParams` - Query parameters of updateSharedLinkOnWebLink method headers `UpdateSharedLinkOnWebLinkHeaders` - Headers of updateSharedLinkOnWebLink method ### Returns This function returns a value of type `WebLink`. Returns a basic representation of the web link, with the updated shared link attached. ## Remove shared link from web link Removes a shared link from a web link. This operation is performed by calling function `removeSharedLinkFromWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--remove-shared-link/). *Currently we don't have an example for calling `removeSharedLinkFromWebLink` in integration tests* ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `RemoveSharedLinkFromWebLinkRequestBody` - Request body of removeSharedLinkFromWebLink method queryParams `RemoveSharedLinkFromWebLinkQueryParams` - Query parameters of removeSharedLinkFromWebLink method headers `RemoveSharedLinkFromWebLinkHeaders` - Headers of removeSharedLinkFromWebLink method ### Returns This function returns a value of type `WebLink`. Returns a basic representation of a web link, with the shared link removed. --- ## Untitled *Type: page* ShieldInformationBarrierReportsManager List shield information barrier reports Create shield information barrier report Get shield… # ShieldInformationBarrierReportsManager - [List shield information barrier reports](#list-shield-information-barrier-reports) - [Create shield information barrier report](#create-shield-information-barrier-report) - [Get shield information barrier report by ID](#get-shield-information-barrier-report-by-id) ## List shield information barrier reports Lists shield information barrier reports. This operation is performed by calling function `getShieldInformationBarrierReports`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports/). ``` try await client.shieldInformationBarrierReports.getShieldInformationBarrierReports(queryParams: GetShieldInformationBarrierReportsQueryParams(shieldInformationBarrierId: barrierId)) ``` ### Arguments queryParams `GetShieldInformationBarrierReportsQueryParams` - Query parameters of getShieldInformationBarrierReports method headers `GetShieldInformationBarrierReportsHeaders` - Headers of getShieldInformationBarrierReports method ### Returns This function returns a value of type `ShieldInformationBarrierReports`. Returns a paginated list of shield information barrier report objects. ## Create shield information barrier report Creates a shield information barrier report for a given barrier. This operation is performed by calling function `createShieldInformationBarrierReport`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-reports/). ``` try await client.shieldInformationBarrierReports.createShieldInformationBarrierReport(requestBody: ShieldInformationBarrierReference(shieldInformationBarrier: ShieldInformationBarrierBase(id: barrierId, type: ShieldInformationBarrierBaseTypeField.shieldInformationBarrier))) ``` ### Arguments requestBody `ShieldInformationBarrierReference` - Request body of createShieldInformationBarrierReport method headers `CreateShieldInformationBarrierReportHeaders` - Headers of createShieldInformationBarrierReport method ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report information object. ## Get shield information barrier report by ID Retrieves a shield information barrier report by its ID. This operation is performed by calling function `getShieldInformationBarrierReportById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports-id/). ``` try await client.shieldInformationBarrierReports.getShieldInformationBarrierReportById(shieldInformationBarrierReportId: createdReport.id!) ``` ### Arguments shieldInformationBarrierReportId `String` - The ID of the shield information barrier Report. Example: "3423" headers `GetShieldInformationBarrierReportByIdHeaders` - Headers of getShieldInformationBarrierReportById method ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentMembersManager Get shield information barrier segment member by ID Delete shield information barrier segment… # ShieldInformationBarrierSegmentMembersManager - [Get shield information barrier segment member by ID](#get-shield-information-barrier-segment-member-by-id) - [Delete shield information barrier segment member by ID](#delete-shield-information-barrier-segment-member-by-id) - [List shield information barrier segment members](#list-shield-information-barrier-segment-members) - [Create shield information barrier segment member](#create-shield-information-barrier-segment-member) ## Get shield information barrier segment member by ID Retrieves a shield information barrier segment member by its ID. This operation is performed by calling function `getShieldInformationBarrierSegmentMemberById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members-id/). ``` try await client.shieldInformationBarrierSegmentMembers.getShieldInformationBarrierSegmentMemberById(shieldInformationBarrierSegmentMemberId: segmentMember.id!) ``` ### Arguments shieldInformationBarrierSegmentMemberId `String` - The ID of the shield information barrier segment Member. Example: "7815" headers `GetShieldInformationBarrierSegmentMemberByIdHeaders` - Headers of getShieldInformationBarrierSegmentMemberById method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns the shield information barrier segment member object. ## Delete shield information barrier segment member by ID Deletes a shield information barrier segment member based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentMemberById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-members-id/). ``` try await client.shieldInformationBarrierSegmentMembers.deleteShieldInformationBarrierSegmentMemberById(shieldInformationBarrierSegmentMemberId: segmentMember.id!) ``` ### Arguments shieldInformationBarrierSegmentMemberId `String` - The ID of the shield information barrier segment Member. Example: "7815" headers `DeleteShieldInformationBarrierSegmentMemberByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentMemberById method ### Returns This function returns a value of type ``. Returns an empty response if the segment member was deleted successfully. ## List shield information barrier segment members Lists shield information barrier segment members based on provided segment IDs. This operation is performed by calling function `getShieldInformationBarrierSegmentMembers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members/). ``` try await client.shieldInformationBarrierSegmentMembers.getShieldInformationBarrierSegmentMembers(queryParams: GetShieldInformationBarrierSegmentMembersQueryParams(shieldInformationBarrierSegmentId: segment.id!)) ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentMembersQueryParams` - Query parameters of getShieldInformationBarrierSegmentMembers method headers `GetShieldInformationBarrierSegmentMembersHeaders` - Headers of getShieldInformationBarrierSegmentMembers method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMembers`. Returns a paginated list of shield information barrier segment member objects. ## Create shield information barrier segment member Creates a new shield information barrier segment member. This operation is performed by calling function `createShieldInformationBarrierSegmentMember`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-members/). ``` try await client.shieldInformationBarrierSegmentMembers.createShieldInformationBarrierSegmentMember(requestBody: CreateShieldInformationBarrierSegmentMemberRequestBody(shieldInformationBarrierSegment: CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentField(id: segment.id!, type: CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentTypeField.shieldInformationBarrierSegment), user: UserBase(id: Utils.getEnvironmentVariable(name: "USER_ID")))) ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentMemberRequestBody` - Request body of createShieldInformationBarrierSegmentMember method headers `CreateShieldInformationBarrierSegmentMemberHeaders` - Headers of createShieldInformationBarrierSegmentMember method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns a new shield information barrier segment member object. --- ## Untitled *Type: page* ShieldInformationBarriersManager Get shield information barrier with specified ID Add changed status of shield information barrier with… # ShieldInformationBarriersManager - [Get shield information barrier with specified ID](#get-shield-information-barrier-with-specified-id) - [Add changed status of shield information barrier with specified ID](#add-changed-status-of-shield-information-barrier-with-specified-id) - [List shield information barriers](#list-shield-information-barriers) - [Create shield information barrier](#create-shield-information-barrier) ## Get shield information barrier with specified ID Get shield information barrier based on provided ID. This operation is performed by calling function `getShieldInformationBarrierById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers-id/). ``` try await client.shieldInformationBarriers.getShieldInformationBarrierById(shieldInformationBarrierId: barrierId) ``` ### Arguments shieldInformationBarrierId `String` - The ID of the shield information barrier. Example: "1910967" headers `GetShieldInformationBarrierByIdHeaders` - Headers of getShieldInformationBarrierById method ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the shield information barrier object. ## Add changed status of shield information barrier with specified ID Change status of shield information barrier with the specified ID. This operation is performed by calling function `updateShieldInformationBarrierStatus`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers-change-status/). ``` try await client.shieldInformationBarriers.updateShieldInformationBarrierStatus(requestBody: UpdateShieldInformationBarrierStatusRequestBody(id: barrierId, status: UpdateShieldInformationBarrierStatusRequestBodyStatusField.disabled)) ``` ### Arguments requestBody `UpdateShieldInformationBarrierStatusRequestBody` - Request body of updateShieldInformationBarrierStatus method headers `UpdateShieldInformationBarrierStatusHeaders` - Headers of updateShieldInformationBarrierStatus method ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the updated shield information barrier object. ## List shield information barriers Retrieves a list of shield information barrier objects for the enterprise of JWT. This operation is performed by calling function `getShieldInformationBarriers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers/). ``` try await client.shieldInformationBarriers.getShieldInformationBarriers() ``` ### Arguments queryParams `GetShieldInformationBarriersQueryParams` - Query parameters of getShieldInformationBarriers method headers `GetShieldInformationBarriersHeaders` - Headers of getShieldInformationBarriers method ### Returns This function returns a value of type `ShieldInformationBarriers`. Returns a paginated list of shield information barrier objects, empty list if currently no barrier. ## Create shield information barrier Creates a shield information barrier to separate individuals/groups within the same firm and prevents confidential information passing between them. This operation is performed by calling function `createShieldInformationBarrier`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers/). ``` try await client.shieldInformationBarriers.createShieldInformationBarrier(requestBody: CreateShieldInformationBarrierRequestBody(enterprise: EnterpriseBase(id: enterpriseId))) ``` ### Arguments requestBody `CreateShieldInformationBarrierRequestBody` - Request body of createShieldInformationBarrier method headers `CreateShieldInformationBarrierHeaders` - Headers of createShieldInformationBarrier method ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns a new shield information barrier object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentRestrictionsManager Get shield information barrier segment restriction by ID Delete shield information… # ShieldInformationBarrierSegmentRestrictionsManager - [Get shield information barrier segment restriction by ID](#get-shield-information-barrier-segment-restriction-by-id) - [Delete shield information barrier segment restriction by ID](#delete-shield-information-barrier-segment-restriction-by-id) - [List shield information barrier segment restrictions](#list-shield-information-barrier-segment-restrictions) - [Create shield information barrier segment restriction](#create-shield-information-barrier-segment-restriction) ## Get shield information barrier segment restriction by ID Retrieves a shield information barrier segment restriction based on provided ID. This operation is performed by calling function `getShieldInformationBarrierSegmentRestrictionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions-id/). ``` try await client.shieldInformationBarrierSegmentRestrictions.getShieldInformationBarrierSegmentRestrictionById(shieldInformationBarrierSegmentRestrictionId: segmentRestrictionId) ``` ### Arguments shieldInformationBarrierSegmentRestrictionId `String` - The ID of the shield information barrier segment Restriction. Example: "4563" headers `GetShieldInformationBarrierSegmentRestrictionByIdHeaders` - Headers of getShieldInformationBarrierSegmentRestrictionById method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the shield information barrier segment restriction object. ## Delete shield information barrier segment restriction by ID Delete shield information barrier segment restriction based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentRestrictionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-restrictions-id/). ``` try await client.shieldInformationBarrierSegmentRestrictions.deleteShieldInformationBarrierSegmentRestrictionById(shieldInformationBarrierSegmentRestrictionId: segmentRestrictionId) ``` ### Arguments shieldInformationBarrierSegmentRestrictionId `String` - The ID of the shield information barrier segment Restriction. Example: "4563" headers `DeleteShieldInformationBarrierSegmentRestrictionByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentRestrictionById method ### Returns This function returns a value of type ``. Empty body in response. ## List shield information barrier segment restrictions Lists shield information barrier segment restrictions based on provided segment ID. This operation is performed by calling function `getShieldInformationBarrierSegmentRestrictions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions/). ``` try await client.shieldInformationBarrierSegmentRestrictions.getShieldInformationBarrierSegmentRestrictions(queryParams: GetShieldInformationBarrierSegmentRestrictionsQueryParams(shieldInformationBarrierSegmentId: segmentId)) ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentRestrictionsQueryParams` - Query parameters of getShieldInformationBarrierSegmentRestrictions method headers `GetShieldInformationBarrierSegmentRestrictionsHeaders` - Headers of getShieldInformationBarrierSegmentRestrictions method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestrictions`. Returns a paginated list of shield information barrier segment restriction objects. ## Create shield information barrier segment restriction Creates a shield information barrier segment restriction object. This operation is performed by calling function `createShieldInformationBarrierSegmentRestriction`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-restrictions/). ``` try await client.shieldInformationBarrierSegmentRestrictions.createShieldInformationBarrierSegmentRestriction(requestBody: CreateShieldInformationBarrierSegmentRestrictionRequestBody(restrictedSegment: CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentField(id: segmentToRestrictId, type: CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentTypeField.shieldInformationBarrierSegment), shieldInformationBarrierSegment: CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentField(id: segmentId, type: CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentTypeField.shieldInformationBarrierSegment), type: CreateShieldInformationBarrierSegmentRestrictionRequestBodyTypeField.shieldInformationBarrierSegmentRestriction)) ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentRestrictionRequestBody` - Request body of createShieldInformationBarrierSegmentRestriction method headers `CreateShieldInformationBarrierSegmentRestrictionHeaders` - Headers of createShieldInformationBarrierSegmentRestriction method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the newly created Shield Information Barrier Segment Restriction object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentsManager Get shield information barrier segment with specified ID Delete shield information barrier segment… # ShieldInformationBarrierSegmentsManager - [Get shield information barrier segment with specified ID](#get-shield-information-barrier-segment-with-specified-id) - [Delete shield information barrier segment](#delete-shield-information-barrier-segment) - [Update shield information barrier segment with specified ID](#update-shield-information-barrier-segment-with-specified-id) - [List shield information barrier segments](#list-shield-information-barrier-segments) - [Create shield information barrier segment](#create-shield-information-barrier-segment) ## Get shield information barrier segment with specified ID Retrieves shield information barrier segment based on provided ID.. This operation is performed by calling function `getShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments-id/). ``` try await client.shieldInformationBarrierSegments.getShieldInformationBarrierSegmentById(shieldInformationBarrierSegmentId: segmentId) ``` ### Arguments shieldInformationBarrierSegmentId `String` - The ID of the shield information barrier segment. Example: "3423" headers `GetShieldInformationBarrierSegmentByIdHeaders` - Headers of getShieldInformationBarrierSegmentById method ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the shield information barrier segment object. ## Delete shield information barrier segment Deletes the shield information barrier segment based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segments-id/). ``` try await client.shieldInformationBarrierSegments.deleteShieldInformationBarrierSegmentById(shieldInformationBarrierSegmentId: segmentId) ``` ### Arguments shieldInformationBarrierSegmentId `String` - The ID of the shield information barrier segment. Example: "3423" headers `DeleteShieldInformationBarrierSegmentByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentById method ### Returns This function returns a value of type ``. Empty body in response. ## Update shield information barrier segment with specified ID Updates the shield information barrier segment based on provided ID.. This operation is performed by calling function `updateShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-shield-information-barrier-segments-id/). ``` try await client.shieldInformationBarrierSegments.updateShieldInformationBarrierSegmentById(shieldInformationBarrierSegmentId: segmentId, requestBody: UpdateShieldInformationBarrierSegmentByIdRequestBody(description: updatedSegmentDescription)) ``` ### Arguments shieldInformationBarrierSegmentId `String` - The ID of the shield information barrier segment. Example: "3423" requestBody `UpdateShieldInformationBarrierSegmentByIdRequestBody` - Request body of updateShieldInformationBarrierSegmentById method headers `UpdateShieldInformationBarrierSegmentByIdHeaders` - Headers of updateShieldInformationBarrierSegmentById method ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the updated shield information barrier segment object. ## List shield information barrier segments Retrieves a list of shield information barrier segment objects for the specified Information Barrier ID. This operation is performed by calling function `getShieldInformationBarrierSegments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments/). ``` try await client.shieldInformationBarrierSegments.getShieldInformationBarrierSegments(queryParams: GetShieldInformationBarrierSegmentsQueryParams(shieldInformationBarrierId: barrierId)) ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentsQueryParams` - Query parameters of getShieldInformationBarrierSegments method headers `GetShieldInformationBarrierSegmentsHeaders` - Headers of getShieldInformationBarrierSegments method ### Returns This function returns a value of type `ShieldInformationBarrierSegments`. Returns a paginated list of shield information barrier segment objects. ## Create shield information barrier segment Creates a shield information barrier segment. This operation is performed by calling function `createShieldInformationBarrierSegment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segments/). ``` try await client.shieldInformationBarrierSegments.createShieldInformationBarrierSegment(requestBody: CreateShieldInformationBarrierSegmentRequestBody(shieldInformationBarrier: ShieldInformationBarrierBase(id: barrierId, type: ShieldInformationBarrierBaseTypeField.shieldInformationBarrier), name: segmentName, description: segmentDescription)) ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentRequestBody` - Request body of createShieldInformationBarrierSegment method headers `CreateShieldInformationBarrierSegmentHeaders` - Headers of createShieldInformationBarrierSegment method ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns a new shield information barrier segment object. --- ## Untitled *Type: page* SignTemplatesManager List Box Sign templates Get Box Sign template by ID List Box Sign templates Gets Box Sign templates created by a user… # SignTemplatesManager - [List Box Sign templates](#list-box-sign-templates) - [Get Box Sign template by ID](#get-box-sign-template-by-id) ## List Box Sign templates Gets Box Sign templates created by a user. This operation is performed by calling function `getSignTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates/). ``` try await client.signTemplates.getSignTemplates(queryParams: GetSignTemplatesQueryParams(limit: Int64(2))) ``` ### Arguments queryParams `GetSignTemplatesQueryParams` - Query parameters of getSignTemplates method headers `GetSignTemplatesHeaders` - Headers of getSignTemplates method ### Returns This function returns a value of type `SignTemplates`. Returns a collection of templates. ## Get Box Sign template by ID Fetches details of a specific Box Sign template. This operation is performed by calling function `getSignTemplateById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates-id/). ``` try await client.signTemplates.getSignTemplateById(templateId: signTemplates.entries![0].id!) ``` ### Arguments templateId `String` - The ID of a Box Sign template. Example: "123075213-7d117509-8f05-42e4-a5ef-5190a319d41d" headers `GetSignTemplateByIdHeaders` - Headers of getSignTemplateById method ### Returns This function returns a value of type `SignTemplate`. Returns details of a template. --- ## Untitled *Type: page* ShieldListsManager Get all shield lists in enterprise Create shield list Get single shield list by shield list id Delete single shield list… # ShieldListsManager - [Get all shield lists in enterprise](#get-all-shield-lists-in-enterprise) - [Create shield list](#create-shield-list) - [Get single shield list by shield list id](#get-single-shield-list-by-shield-list-id) - [Delete single shield list by shield list id](#delete-single-shield-list-by-shield-list-id) - [Update shield list](#update-shield-list) ## Get all shield lists in enterprise Retrieves all shield lists in the enterprise. This operation is performed by calling function `getShieldListsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists/). *Currently we don't have an example for calling `getShieldListsV2025R0` in integration tests* ### Arguments headers `GetShieldListsV2025R0Headers` - Headers of getShieldListsV2025R0 method ### Returns This function returns a value of type `ShieldListsV2025R0`. Returns the list of shield list objects. ## Create shield list Creates a shield list. This operation is performed by calling function `createShieldListV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-shield-lists/). *Currently we don't have an example for calling `createShieldListV2025R0` in integration tests* ### Arguments requestBody `ShieldListsCreateV2025R0` - Request body of createShieldListV2025R0 method headers `CreateShieldListV2025R0Headers` - Headers of createShieldListV2025R0 method ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Get single shield list by shield list id Retrieves a single shield list by its ID. This operation is performed by calling function `getShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists-id/). *Currently we don't have an example for calling `getShieldListByIdV2025R0` in integration tests* ### Arguments shieldListId `String` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " headers `GetShieldListByIdV2025R0Headers` - Headers of getShieldListByIdV2025R0 method ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Delete single shield list by shield list id Delete a single shield list by its ID. This operation is performed by calling function `deleteShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-shield-lists-id/). *Currently we don't have an example for calling `deleteShieldListByIdV2025R0` in integration tests* ### Arguments shieldListId `String` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " headers `DeleteShieldListByIdV2025R0Headers` - Headers of deleteShieldListByIdV2025R0 method ### Returns This function returns a value of type ``. Shield List correctly removed. No content in response. ## Update shield list Updates a shield list. This operation is performed by calling function `updateShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-shield-lists-id/). *Currently we don't have an example for calling `updateShieldListByIdV2025R0` in integration tests* ### Arguments shieldListId `String` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " requestBody `ShieldListsUpdateV2025R0` - Request body of updateShieldListByIdV2025R0 method headers `UpdateShieldListByIdV2025R0Headers` - Headers of updateShieldListByIdV2025R0 method ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. --- ## Untitled *Type: page* SignRequestsManager Cancel Box Sign request Resend Box Sign request Get Box Sign request by ID List Box Sign requests Create Box Sign… # SignRequestsManager - [Cancel Box Sign request](#cancel-box-sign-request) - [Resend Box Sign request](#resend-box-sign-request) - [Get Box Sign request by ID](#get-box-sign-request-by-id) - [List Box Sign requests](#list-box-sign-requests) - [Create Box Sign request](#create-box-sign-request) ## Cancel Box Sign request Cancels a sign request. This operation is performed by calling function `cancelSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-cancel/). ``` try await client.signRequests.cancelSignRequest(signRequestId: createdSignRequest.id!) ``` ### Arguments signRequestId `String` - The ID of the signature request. Example: "33243242" headers `CancelSignRequestHeaders` - Headers of cancelSignRequest method ### Returns This function returns a value of type `SignRequest`. Returns a Sign Request object. ## Resend Box Sign request Resends a signature request email to all outstanding signers. This operation is performed by calling function `resendSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-resend/). *Currently we don't have an example for calling `resendSignRequest` in integration tests* ### Arguments signRequestId `String` - The ID of the signature request. Example: "33243242" headers `ResendSignRequestHeaders` - Headers of resendSignRequest method ### Returns This function returns a value of type ``. Returns an empty response when the API call was successful. The email notifications will be sent asynchronously. ## Get Box Sign request by ID Gets a sign request by ID. This operation is performed by calling function `getSignRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests-id/). ``` try await client.signRequests.getSignRequestById(signRequestId: createdSignRequest.id!) ``` ### Arguments signRequestId `String` - The ID of the signature request. Example: "33243242" headers `GetSignRequestByIdHeaders` - Headers of getSignRequestById method ### Returns This function returns a value of type `SignRequest`. Returns a signature request. ## List Box Sign requests Gets signature requests created by a user. If the `sign_files` and/or `parent_folder` are deleted, the signature request will not return in the list. This operation is performed by calling function `getSignRequests`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests/). ``` try await client.signRequests.getSignRequests() ``` ### Arguments queryParams `GetSignRequestsQueryParams` - Query parameters of getSignRequests method headers `GetSignRequestsHeaders` - Headers of getSignRequests method ### Returns This function returns a value of type `SignRequests`. Returns a collection of sign requests. ## Create Box Sign request Creates a signature request. This involves preparing a document for signing and sending the signature request to signers. This operation is performed by calling function `createSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests/). ``` try await client.signRequests.createSignRequest(requestBody: SignRequestCreateRequest(signers: [SignRequestCreateSigner(email: signerEmail, suppressNotifications: true, declinedRedirectUrl: "https://www.box.com", embedUrlExternalUserId: "123", isInPerson: false, loginRequired: false, password: "password", role: SignRequestCreateSignerRoleField.signer)], areRemindersEnabled: true, areTextSignaturesEnabled: true, daysValid: Int64(30), declinedRedirectUrl: "https://www.box.com", emailMessage: "Please sign this document", emailSubject: "Sign this document", externalId: "123", externalSystemName: "BoxSignIntegration", isDocumentPreparationNeeded: false, name: "Sign Request", parentFolder: FolderMini(id: destinationFolder.id), redirectUrl: "https://www.box.com", prefillTags: [SignRequestPrefillTag(dateValue: try Utils.Dates.dateFromString(date: "2035-01-01"), documentTagId: "0")], sourceFiles: [FileBase(id: fileToSign.id)])) ``` ### Arguments requestBody `SignRequestCreateRequest` - Request body of createSignRequest method headers `CreateSignRequestHeaders` - Headers of createSignRequest method ### Returns This function returns a value of type `SignRequest`. Returns a Box Sign request object. --- ## Untitled *Type: page* SkillsManager List Box Skill cards on file Create Box Skill cards on file Update Box Skill cards on file Remove Box Skill cards from file… # SkillsManager - [List Box Skill cards on file](#list-box-skill-cards-on-file) - [Create Box Skill cards on file](#create-box-skill-cards-on-file) - [Update Box Skill cards on file](#update-box-skill-cards-on-file) - [Remove Box Skill cards from file](#remove-box-skill-cards-from-file) - [Update all Box Skill cards on file](#update-all-box-skill-cards-on-file) ## List Box Skill cards on file List the Box Skills metadata cards that are attached to a file. This operation is performed by calling function `getBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-global-boxSkillsCards/). *Currently we don't have an example for calling `getBoxSkillCardsOnFile` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetBoxSkillCardsOnFileHeaders` - Headers of getBoxSkillCardsOnFile method ### Returns This function returns a value of type `SkillCardsMetadata`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Create Box Skill cards on file Applies one or more Box Skills metadata cards to a file. This operation is performed by calling function `createBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-global-boxSkillsCards/). *Currently we don't have an example for calling `createBoxSkillCardsOnFile` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CreateBoxSkillCardsOnFileRequestBody` - Request body of createBoxSkillCardsOnFile method headers `CreateBoxSkillCardsOnFileHeaders` - Headers of createBoxSkillCardsOnFile method ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update Box Skill cards on file Updates one or more Box Skills metadata cards to a file. This operation is performed by calling function `updateBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-global-boxSkillsCards/). *Currently we don't have an example for calling `updateBoxSkillCardsOnFile` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `[UpdateBoxSkillCardsOnFileRequestBody]` - Request body of updateBoxSkillCardsOnFile method headers `UpdateBoxSkillCardsOnFileHeaders` - Headers of updateBoxSkillCardsOnFile method ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the updated metadata template, with the custom template data included. ## Remove Box Skill cards from file Removes any Box Skills cards metadata from a file. This operation is performed by calling function `deleteBoxSkillCardsFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-global-boxSkillsCards/). *Currently we don't have an example for calling `deleteBoxSkillCardsFromFile` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteBoxSkillCardsFromFileHeaders` - Headers of deleteBoxSkillCardsFromFile method ### Returns This function returns a value of type ``. Returns an empty response when the cards are successfully deleted. ## Update all Box Skill cards on file An alternative method that can be used to overwrite and update all Box Skill metadata cards on a file. This operation is performed by calling function `updateAllSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-skill-invocations-id/). *Currently we don't have an example for calling `updateAllSkillCardsOnFile` in integration tests* ### Arguments skillId `String` - The ID of the skill to apply this metadata for. Example: "33243242" requestBody `UpdateAllSkillCardsOnFileRequestBody` - Request body of updateAllSkillCardsOnFile method headers `UpdateAllSkillCardsOnFileHeaders` - Headers of updateAllSkillCardsOnFile method ### Returns This function returns a value of type ``. Returns an empty response when the card has been successfully updated. --- ## Untitled *Type: page* TaskAssignmentsManager List task assignments Assign task Get task assignment Update task assignment Unassign task List task assignments… # TaskAssignmentsManager - [List task assignments](#list-task-assignments) - [Assign task](#assign-task) - [Get task assignment](#get-task-assignment) - [Update task assignment](#update-task-assignment) - [Unassign task](#unassign-task) ## List task assignments Lists all of the assignments for a given task. This operation is performed by calling function `getTaskAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id-assignments/). ``` try await client.taskAssignments.getTaskAssignments(taskId: task.id!) ``` ### Arguments taskId `String` - The ID of the task. Example: "12345" headers `GetTaskAssignmentsHeaders` - Headers of getTaskAssignments method ### Returns This function returns a value of type `TaskAssignments`. Returns a collection of task assignment defining what task on a file has been assigned to which users and by who. ## Assign task Assigns a task to a user. A task can be assigned to more than one user by creating multiple assignments. This operation is performed by calling function `createTaskAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-task-assignments/). ``` try await client.taskAssignments.createTaskAssignment(requestBody: CreateTaskAssignmentRequestBody(task: CreateTaskAssignmentRequestBodyTaskField(type: CreateTaskAssignmentRequestBodyTaskTypeField.task, id: task.id!), assignTo: CreateTaskAssignmentRequestBodyAssignToField(id: currentUser.id))) ``` ### Arguments requestBody `CreateTaskAssignmentRequestBody` - Request body of createTaskAssignment method headers `CreateTaskAssignmentHeaders` - Headers of createTaskAssignment method ### Returns This function returns a value of type `TaskAssignment`. Returns a new task assignment object. ## Get task assignment Retrieves information about a task assignment. This operation is performed by calling function `getTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-task-assignments-id/). ``` try await client.taskAssignments.getTaskAssignmentById(taskAssignmentId: taskAssignment.id!) ``` ### Arguments taskAssignmentId `String` - The ID of the task assignment. Example: "12345" headers `GetTaskAssignmentByIdHeaders` - Headers of getTaskAssignmentById method ### Returns This function returns a value of type `TaskAssignment`. Returns a task assignment, specifying who the task has been assigned to and by whom. ## Update task assignment Updates a task assignment. This endpoint can be used to update the state of a task assigned to a user. This operation is performed by calling function `updateTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-task-assignments-id/). ``` try await client.taskAssignments.updateTaskAssignmentById(taskAssignmentId: taskAssignment.id!, requestBody: UpdateTaskAssignmentByIdRequestBody(message: "updated message", resolutionState: UpdateTaskAssignmentByIdRequestBodyResolutionStateField.approved)) ``` ### Arguments taskAssignmentId `String` - The ID of the task assignment. Example: "12345" requestBody `UpdateTaskAssignmentByIdRequestBody` - Request body of updateTaskAssignmentById method headers `UpdateTaskAssignmentByIdHeaders` - Headers of updateTaskAssignmentById method ### Returns This function returns a value of type `TaskAssignment`. Returns the updated task assignment object. ## Unassign task Deletes a specific task assignment. This operation is performed by calling function `deleteTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-task-assignments-id/). ``` try await client.taskAssignments.deleteTaskAssignmentById(taskAssignmentId: taskAssignment.id!) ``` ### Arguments taskAssignmentId `String` - The ID of the task assignment. Example: "12345" headers `DeleteTaskAssignmentByIdHeaders` - Headers of deleteTaskAssignmentById method ### Returns This function returns a value of type ``. Returns an empty response when the task assignment was successfully deleted. --- ## Untitled *Type: page* StoragePolicyAssignmentsManager List storage policy assignments Assign storage policy Get storage policy assignment Update storage policy… # StoragePolicyAssignmentsManager - [List storage policy assignments](#list-storage-policy-assignments) - [Assign storage policy](#assign-storage-policy) - [Get storage policy assignment](#get-storage-policy-assignment) - [Update storage policy assignment](#update-storage-policy-assignment) - [Unassign storage policy](#unassign-storage-policy) ## List storage policy assignments Fetches all the storage policy assignment for an enterprise or user. This operation is performed by calling function `getStoragePolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments/). ``` try await client.storagePolicyAssignments.getStoragePolicyAssignments(queryParams: GetStoragePolicyAssignmentsQueryParams(resolvedForType: GetStoragePolicyAssignmentsQueryParamsResolvedForTypeField.user, resolvedForId: userId)) ``` ### Arguments queryParams `GetStoragePolicyAssignmentsQueryParams` - Query parameters of getStoragePolicyAssignments method headers `GetStoragePolicyAssignmentsHeaders` - Headers of getStoragePolicyAssignments method ### Returns This function returns a value of type `StoragePolicyAssignments`. Returns a collection of storage policies for the enterprise or user. ## Assign storage policy Creates a storage policy assignment for an enterprise or user. This operation is performed by calling function `createStoragePolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-storage-policy-assignments/). ``` try await client.storagePolicyAssignments.createStoragePolicyAssignment(requestBody: CreateStoragePolicyAssignmentRequestBody(storagePolicy: CreateStoragePolicyAssignmentRequestBodyStoragePolicyField(id: policyId), assignedTo: CreateStoragePolicyAssignmentRequestBodyAssignedToField(id: userId, type: CreateStoragePolicyAssignmentRequestBodyAssignedToTypeField.user))) ``` ### Arguments requestBody `CreateStoragePolicyAssignmentRequestBody` - Request body of createStoragePolicyAssignment method headers `CreateStoragePolicyAssignmentHeaders` - Headers of createStoragePolicyAssignment method ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns the new storage policy assignment created. ## Get storage policy assignment Fetches a specific storage policy assignment. This operation is performed by calling function `getStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments-id/). ``` try await client.storagePolicyAssignments.getStoragePolicyAssignmentById(storagePolicyAssignmentId: storagePolicyAssignment.id) ``` ### Arguments storagePolicyAssignmentId `String` - The ID of the storage policy assignment. Example: "932483" headers `GetStoragePolicyAssignmentByIdHeaders` - Headers of getStoragePolicyAssignmentById method ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns a storage policy assignment object. ## Update storage policy assignment Updates a specific storage policy assignment. This operation is performed by calling function `updateStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-storage-policy-assignments-id/). ``` try await client.storagePolicyAssignments.updateStoragePolicyAssignmentById(storagePolicyAssignmentId: storagePolicyAssignment.id, requestBody: UpdateStoragePolicyAssignmentByIdRequestBody(storagePolicy: UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyField(id: storagePolicy2.id))) ``` ### Arguments storagePolicyAssignmentId `String` - The ID of the storage policy assignment. Example: "932483" requestBody `UpdateStoragePolicyAssignmentByIdRequestBody` - Request body of updateStoragePolicyAssignmentById method headers `UpdateStoragePolicyAssignmentByIdHeaders` - Headers of updateStoragePolicyAssignmentById method ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns an updated storage policy assignment object. ## Unassign storage policy Delete a storage policy assignment. Deleting a storage policy assignment on a user will have the user inherit the enterprise's default storage policy. There is a rate limit for calling this endpoint of only twice per user in a 24 hour time frame. This operation is performed by calling function `deleteStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-storage-policy-assignments-id/). ``` try await client.storagePolicyAssignments.deleteStoragePolicyAssignmentById(storagePolicyAssignmentId: storagePolicyAssignment.id) ``` ### Arguments storagePolicyAssignmentId `String` - The ID of the storage policy assignment. Example: "932483" headers `DeleteStoragePolicyAssignmentByIdHeaders` - Headers of deleteStoragePolicyAssignmentById method ### Returns This function returns a value of type ``. Returns an empty response when the storage policy assignment is successfully deleted. --- ## Untitled *Type: page* TasksManager List tasks on file Create task Get task Update task Remove task List tasks on file Retrieves a list of all the tasks for a file… # TasksManager - [List tasks on file](#list-tasks-on-file) - [Create task](#create-task) - [Get task](#get-task) - [Update task](#update-task) - [Remove task](#remove-task) ## List tasks on file Retrieves a list of all the tasks for a file. This endpoint does not support pagination. This operation is performed by calling function `getFileTasks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-tasks/). ``` try await client.tasks.getFileTasks(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileTasksHeaders` - Headers of getFileTasks method ### Returns This function returns a value of type `Tasks`. Returns a list of tasks on a file. If there are no tasks on this file an empty collection is returned instead. ## Create task Creates a single task on a file. This task is not assigned to any user and will need to be assigned separately. This operation is performed by calling function `createTask`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-tasks/). ``` try await client.tasks.createTask(requestBody: CreateTaskRequestBody(item: CreateTaskRequestBodyItemField(type: CreateTaskRequestBodyItemTypeField.file, id: file.id), message: "test message", dueAt: dateTime, action: CreateTaskRequestBodyActionField.review, completionRule: CreateTaskRequestBodyCompletionRuleField.allAssignees)) ``` ### Arguments requestBody `CreateTaskRequestBody` - Request body of createTask method headers `CreateTaskHeaders` - Headers of createTask method ### Returns This function returns a value of type `Task`. Returns the newly created task. ## Get task Retrieves information about a specific task. This operation is performed by calling function `getTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id/). ``` try await client.tasks.getTaskById(taskId: task.id!) ``` ### Arguments taskId `String` - The ID of the task. Example: "12345" headers `GetTaskByIdHeaders` - Headers of getTaskById method ### Returns This function returns a value of type `Task`. Returns a task object. ## Update task Updates a task. This can be used to update a task's configuration, or to update its completion state. This operation is performed by calling function `updateTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-tasks-id/). ``` try await client.tasks.updateTaskById(taskId: task.id!, requestBody: UpdateTaskByIdRequestBody(message: "updated message")) ``` ### Arguments taskId `String` - The ID of the task. Example: "12345" requestBody `UpdateTaskByIdRequestBody` - Request body of updateTaskById method headers `UpdateTaskByIdHeaders` - Headers of updateTaskById method ### Returns This function returns a value of type `Task`. Returns the updated task object. ## Remove task Removes a task from a file. This operation is performed by calling function `deleteTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-tasks-id/). ``` try await client.tasks.deleteTaskById(taskId: task.id!) ``` ### Arguments taskId `String` - The ID of the task. Example: "12345" headers `DeleteTaskByIdHeaders` - Headers of deleteTaskById method ### Returns This function returns a value of type ``. Returns an empty response when the task was successfully deleted. --- ## Untitled *Type: page* StoragePoliciesManager List storage policies Get storage policy List storage policies Fetches all the storage policies in the enterprise… # StoragePoliciesManager - [List storage policies](#list-storage-policies) - [Get storage policy](#get-storage-policy) ## List storage policies Fetches all the storage policies in the enterprise. This operation is performed by calling function `getStoragePolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies/). ``` try await client.storagePolicies.getStoragePolicies() ``` ### Arguments queryParams `GetStoragePoliciesQueryParams` - Query parameters of getStoragePolicies method headers `GetStoragePoliciesHeaders` - Headers of getStoragePolicies method ### Returns This function returns a value of type `StoragePolicies`. Returns a collection of storage policies. ## Get storage policy Fetches a specific storage policy. This operation is performed by calling function `getStoragePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies-id/). ``` try await client.storagePolicies.getStoragePolicyById(storagePolicyId: storagePolicy.id) ``` ### Arguments storagePolicyId `String` - The ID of the storage policy. Example: "34342" headers `GetStoragePolicyByIdHeaders` - Headers of getStoragePolicyById method ### Returns This function returns a value of type `StoragePolicy`. Returns a storage policy object. --- ## Untitled *Type: page* TermsOfServiceUserStatusesManager List terms of service user statuses Create terms of service status for new user Update terms of service… # TermsOfServiceUserStatusesManager - [List terms of service user statuses](#list-terms-of-service-user-statuses) - [Create terms of service status for new user](#create-terms-of-service-status-for-new-user) - [Update terms of service status for existing user](#update-terms-of-service-status-for-existing-user) ## List terms of service user statuses Retrieves an overview of users and their status for a terms of service, including Whether they have accepted the terms and when. This operation is performed by calling function `getTermsOfServiceUserStatuses`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-service-user-statuses/). ``` try await client.termsOfServiceUserStatuses.getTermsOfServiceUserStatuses(queryParams: GetTermsOfServiceUserStatusesQueryParams(tosId: tos.id, userId: user.id)) ``` ### Arguments queryParams `GetTermsOfServiceUserStatusesQueryParams` - Query parameters of getTermsOfServiceUserStatuses method headers `GetTermsOfServiceUserStatusesHeaders` - Headers of getTermsOfServiceUserStatuses method ### Returns This function returns a value of type `TermsOfServiceUserStatuses`. Returns a list of terms of service statuses. ## Create terms of service status for new user Sets the status for a terms of service for a user. This operation is performed by calling function `createTermsOfServiceStatusForUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-service-user-statuses/). ``` try await client.termsOfServiceUserStatuses.createTermsOfServiceStatusForUser(requestBody: CreateTermsOfServiceStatusForUserRequestBody(tos: CreateTermsOfServiceStatusForUserRequestBodyTosField(id: tos.id), user: CreateTermsOfServiceStatusForUserRequestBodyUserField(id: user.id), isAccepted: false)) ``` ### Arguments requestBody `CreateTermsOfServiceStatusForUserRequestBody` - Request body of createTermsOfServiceStatusForUser method headers `CreateTermsOfServiceStatusForUserHeaders` - Headers of createTermsOfServiceStatusForUser method ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns a terms of service status object. ## Update terms of service status for existing user Updates the status for a terms of service for a user. This operation is performed by calling function `updateTermsOfServiceStatusForUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-service-user-statuses-id/). ``` try await client.termsOfServiceUserStatuses.updateTermsOfServiceStatusForUserById(termsOfServiceUserStatusId: createdTosUserStatus.id, requestBody: UpdateTermsOfServiceStatusForUserByIdRequestBody(isAccepted: true)) ``` ### Arguments termsOfServiceUserStatusId `String` - The ID of the terms of service status. Example: "324234" requestBody `UpdateTermsOfServiceStatusForUserByIdRequestBody` - Request body of updateTermsOfServiceStatusForUserById method headers `UpdateTermsOfServiceStatusForUserByIdHeaders` - Headers of updateTermsOfServiceStatusForUserById method ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns the updated terms of service status object. --- ## Untitled *Type: page* TermsOfServicesManager List terms of services Create terms of service Get terms of service Update terms of service List terms of services… # TermsOfServicesManager - [List terms of services](#list-terms-of-services) - [Create terms of service](#create-terms-of-service) - [Get terms of service](#get-terms-of-service) - [Update terms of service](#update-terms-of-service) ## List terms of services Returns the current terms of service text and settings for the enterprise. This operation is performed by calling function `getTermsOfService`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services/). ``` try await client.termsOfServices.getTermsOfService() ``` ### Arguments queryParams `GetTermsOfServiceQueryParams` - Query parameters of getTermsOfService method headers `GetTermsOfServiceHeaders` - Headers of getTermsOfService method ### Returns This function returns a value of type `TermsOfServices`. Returns a collection of terms of service text and settings for the enterprise. ## Create terms of service Creates a terms of service for a given enterprise and type of user. This operation is performed by calling function `createTermsOfService`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-services/). ``` try await client.termsOfServices.createTermsOfService(requestBody: CreateTermsOfServiceRequestBody(status: CreateTermsOfServiceRequestBodyStatusField.disabled, tosType: CreateTermsOfServiceRequestBodyTosTypeField.managed, text: "Test TOS")) ``` ### Arguments requestBody `CreateTermsOfServiceRequestBody` - Request body of createTermsOfService method headers `CreateTermsOfServiceHeaders` - Headers of createTermsOfService method ### Returns This function returns a value of type `TermsOfService`. Returns a new task object. ## Get terms of service Fetches a specific terms of service. This operation is performed by calling function `getTermsOfServiceById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services-id/). *Currently we don't have an example for calling `getTermsOfServiceById` in integration tests* ### Arguments termsOfServiceId `String` - The ID of the terms of service. Example: "324234" headers `GetTermsOfServiceByIdHeaders` - Headers of getTermsOfServiceById method ### Returns This function returns a value of type `TermsOfService`. Returns a terms of service object. ## Update terms of service Updates a specific terms of service. This operation is performed by calling function `updateTermsOfServiceById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-services-id/). ``` try await client.termsOfServices.updateTermsOfServiceById(termsOfServiceId: tos.id, requestBody: UpdateTermsOfServiceByIdRequestBody(status: UpdateTermsOfServiceByIdRequestBodyStatusField.disabled, text: "TOS")) ``` ### Arguments termsOfServiceId `String` - The ID of the terms of service. Example: "324234" requestBody `UpdateTermsOfServiceByIdRequestBody` - Request body of updateTermsOfServiceById method headers `UpdateTermsOfServiceByIdHeaders` - Headers of updateTermsOfServiceById method ### Returns This function returns a value of type `TermsOfService`. Returns an updated terms of service object. --- ## Untitled *Type: page* TransferManager Transfer owned folders Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into… # TransferManager - [Transfer owned folders](#transfer-owned-folders) ## Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into another user's account Only the root folder (`0`) can be transferred. Folders can only be moved across users by users with administrative permissions. All existing shared links and folder-level collaborations are transferred during the operation. Please note that while collaborations at the individual file-level are transferred during the operation, the collaborations are deleted when the original user is deleted. If the user has a large number of items across all folders, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. If the destination path has a metadata cascade policy attached to any of the parent folders, a metadata cascade operation will be kicked off asynchronously. There is currently no way to check for when this operation is finished. The destination folder's name will be in the format `{User}'s Files and Folders`, where `{User}` is the display name of the user. To make this API call your application will need to have the "Read and write all files and folders stored in Box" scope enabled. Please make sure the destination user has access to `Relay` or `Relay Lite`, and has access to the files and folders involved in the workflows being transferred. Admins will receive an email when the operation is completed. This operation is performed by calling function `transferOwnedFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id-folders-0/). ``` try await client.transfer.transferOwnedFolder(userId: sourceUser.id, requestBody: TransferOwnedFolderRequestBody(ownedBy: TransferOwnedFolderRequestBodyOwnedByField(id: targetUser.id)), queryParams: TransferOwnedFolderQueryParams(notify: false)) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" requestBody `TransferOwnedFolderRequestBody` - Request body of transferOwnedFolder method queryParams `TransferOwnedFolderQueryParams` - Query parameters of transferOwnedFolder method headers `TransferOwnedFolderHeaders` - Headers of transferOwnedFolder method ### Returns This function returns a value of type `FolderFull`. Returns the information for the newly created destination folder. --- ## Untitled *Type: page* TrashedFoldersManager Restore folder Get trashed folder Permanently remove folder Restore folder Restores a folder that has been moved to… # TrashedFoldersManager - [Restore folder](#restore-folder) - [Get trashed folder](#get-trashed-folder) - [Permanently remove folder](#permanently-remove-folder) ## Restore folder Restores a folder that has been moved to the trash. An optional new parent ID can be provided to restore the folder to in case the original folder has been deleted. During this operation, part of the file tree will be locked, mainly the source folder and all of its descendants, as well as the destination folder. For the duration of the operation, no other move, copy, delete, or restore operation can performed on any of the locked folders. This operation is performed by calling function `restoreFolderFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id/). ``` try await client.trashedFolders.restoreFolderFromTrash(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `RestoreFolderFromTrashRequestBody` - Request body of restoreFolderFromTrash method queryParams `RestoreFolderFromTrashQueryParams` - Query parameters of restoreFolderFromTrash method headers `RestoreFolderFromTrashHeaders` - Headers of restoreFolderFromTrash method ### Returns This function returns a value of type `TrashFolderRestored`. Returns a folder object when the folder has been restored. ## Get trashed folder Retrieves a folder that has been moved to the trash. Please note that only if the folder itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `getTrashedFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-trash/). ``` try await client.trashedFolders.getTrashedFolderById(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetTrashedFolderByIdQueryParams` - Query parameters of getTrashedFolderById method headers `GetTrashedFolderByIdHeaders` - Headers of getTrashedFolderById method ### Returns This function returns a value of type `TrashFolder`. Returns the folder that was trashed, including information about when the it was moved to the trash. ## Permanently remove folder Permanently deletes a folder that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-trash/). ``` try await client.trashedFolders.deleteTrashedFolderById(folderId: folder.id) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteTrashedFolderByIdHeaders` - Headers of deleteTrashedFolderById method ### Returns This function returns a value of type ``. Returns an empty response when the folder was permanently deleted. --- ## Untitled *Type: page* TrashedFilesManager Restore file Get trashed file Permanently remove file Restore file Restores a file that has been moved to the trash. An… # TrashedFilesManager - [Restore file](#restore-file) - [Get trashed file](#get-trashed-file) - [Permanently remove file](#permanently-remove-file) ## Restore file Restores a file that has been moved to the trash. An optional new parent ID can be provided to restore the file to in case the original folder has been deleted. This operation is performed by calling function `restoreFileFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id/). ``` try await client.trashedFiles.restoreFileFromTrash(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `RestoreFileFromTrashRequestBody` - Request body of restoreFileFromTrash method queryParams `RestoreFileFromTrashQueryParams` - Query parameters of restoreFileFromTrash method headers `RestoreFileFromTrashHeaders` - Headers of restoreFileFromTrash method ### Returns This function returns a value of type `TrashFileRestored`. Returns a file object when the file has been restored. ## Get trashed file Retrieves a file that has been moved to the trash. Please note that only if the file itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `getTrashedFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-trash/). ``` try await client.trashedFiles.getTrashedFileById(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetTrashedFileByIdQueryParams` - Query parameters of getTrashedFileById method headers `GetTrashedFileByIdHeaders` - Headers of getTrashedFileById method ### Returns This function returns a value of type `TrashFile`. Returns the file that was trashed, including information about when the it was moved to the trash. ## Permanently remove file Permanently deletes a file that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-trash/). ``` try await client.trashedFiles.deleteTrashedFileById(fileId: file.id) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteTrashedFileByIdHeaders` - Headers of deleteTrashedFileById method ### Returns This function returns a value of type ``. Returns an empty response when the file was permanently deleted. --- ## Untitled *Type: page* TrashedWebLinksManager Restore web link Get trashed web link Permanently remove web link Restore web link Restores a web link that has been… # TrashedWebLinksManager - [Restore web link](#restore-web-link) - [Get trashed web link](#get-trashed-web-link) - [Permanently remove web link](#permanently-remove-web-link) ## Restore web link Restores a web link that has been moved to the trash. An optional new parent ID can be provided to restore the web link to in case the original folder has been deleted. This operation is performed by calling function `restoreWeblinkFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links-id/). ``` try await client.trashedWebLinks.restoreWeblinkFromTrash(webLinkId: weblink.id) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `RestoreWeblinkFromTrashRequestBody` - Request body of restoreWeblinkFromTrash method queryParams `RestoreWeblinkFromTrashQueryParams` - Query parameters of restoreWeblinkFromTrash method headers `RestoreWeblinkFromTrashHeaders` - Headers of restoreWeblinkFromTrash method ### Returns This function returns a value of type `TrashWebLinkRestored`. Returns a web link object when it has been restored. ## Get trashed web link Retrieves a web link that has been moved to the trash. This operation is performed by calling function `getTrashedWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id-trash/). ``` try await client.trashedWebLinks.getTrashedWebLinkById(webLinkId: weblink.id) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" queryParams `GetTrashedWebLinkByIdQueryParams` - Query parameters of getTrashedWebLinkById method headers `GetTrashedWebLinkByIdHeaders` - Headers of getTrashedWebLinkById method ### Returns This function returns a value of type `TrashWebLink`. Returns the web link that was trashed, including information about when the it was moved to the trash. ## Permanently remove web link Permanently deletes a web link that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id-trash/). ``` try await client.trashedWebLinks.deleteTrashedWebLinkById(webLinkId: weblink.id) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" headers `DeleteTrashedWebLinkByIdHeaders` - Headers of deleteTrashedWebLinkById method ### Returns This function returns a value of type ``. Returns an empty response when the web link was permanently deleted. --- ## Untitled *Type: page* Uploads Uploads module is used to upload files to Box. It supports uploading files from an InputStream. For now, it only supports uploading… # Uploads Uploads module is used to upload files to Box. It supports uploading files from an `InputStream`. For now, it only supports uploading small files without chunked upload. - [Upload a File](#upload-a-file) ## Upload a File To upload a small file from an `InputStream`, call `client.uploads.uploadFile(requestBody:queryParams:headers)` method. This method returns a `Files` object which contains information about the uploaded files. ``` // Create InputStream for a file based on URL guard let fileStream = InputStream(url: URL(string: "<URL_TO_YOUR_FILE>")!) else { fatalError("Could not read a file") } // Create a request body with the required parameters let requestBody = UploadFileRequestBodyArg( attributes: UploadFileRequestBodyArgAttributesField( name: "filename.txt", parent: UploadFileRequestBodyArgAttributesFieldParentField(id: "0") ), file: fileStream ) // Call uploadFile method let files = try await client.uploads.uploadFile(requestBody: requestBody) // Print some data from the reponse if let file = files.entries?[0] { print("File uploaded with id \(file.id), name \(file.name!)") } ``` If we want to upload a file based on the String type, we need to create an input stream as follows: ``` let stringContent: String = "File content from String" let data: Data = stringContent.data(using: .utf8)! let stream: InputStream = InputStream(data: data) ``` Then we just pass the created `stream` to the `file` argument when initializing the `UploadFileRequestBodyArg` object. --- ## Untitled *Type: page* UsersManager List enterprise users Create user Get current user Get user Update user Delete user List enterprise users Returns a list of all… # UsersManager - [List enterprise users](#list-enterprise-users) - [Create user](#create-user) - [Get current user](#get-current-user) - [Get user](#get-user) - [Update user](#update-user) - [Delete user](#delete-user) ## List enterprise users Returns a list of all users for the Enterprise along with their `user_id`, `public_name`, and `login`. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This operation is performed by calling function `getUsers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users/). ``` try await client.users.getUsers() ``` ### Arguments queryParams `GetUsersQueryParams` - Query parameters of getUsers method headers `GetUsersHeaders` - Headers of getUsers method ### Returns This function returns a value of type `Users`. Returns all of the users in the enterprise. ## Create user Creates a new managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `createUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users/). ``` try await client.users.createUser(requestBody: CreateUserRequestBody(name: userName, login: userLogin, isPlatformAccessOnly: true)) ``` ### Arguments requestBody `CreateUserRequestBody` - Request body of createUser method queryParams `CreateUserQueryParams` - Query parameters of createUser method headers `CreateUserHeaders` - Headers of createUser method ### Returns This function returns a value of type `UserFull`. Returns a user object for the newly created user. ## Get current user Retrieves information about the user who is currently authenticated. In the case of a client-side authenticated OAuth 2.0 application this will be the user who authorized the app. In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default. Use the `As-User` header to change who this API call is made on behalf of. This operation is performed by calling function `getUserMe`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-me/). ``` try await client.users.getUserMe() ``` ### Arguments queryParams `GetUserMeQueryParams` - Query parameters of getUserMe method headers `GetUserMeHeaders` - Headers of getUserMe method ### Returns This function returns a value of type `UserFull`. Returns a single user object. ## Get user Retrieves information about a user in the enterprise. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This endpoint also returns a limited set of information for external users who are collaborated on content owned by the enterprise for authenticated users with the right scopes. In this case, disallowed fields will return null instead. This operation is performed by calling function `getUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id/). ``` try await client.users.getUserById(userId: user.id) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" queryParams `GetUserByIdQueryParams` - Query parameters of getUserById method headers `GetUserByIdHeaders` - Headers of getUserById method ### Returns This function returns a value of type `UserFull`. Returns a single user object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields using the [fields](#get-users-id--request--fields) parameter. ## Update user Updates a managed or app user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `updateUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id/). ``` try await client.users.updateUserById(userId: user.id, requestBody: UpdateUserByIdRequestBody(name: updatedUserName)) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" requestBody `UpdateUserByIdRequestBody` - Request body of updateUserById method queryParams `UpdateUserByIdQueryParams` - Query parameters of updateUserById method headers `UpdateUserByIdHeaders` - Headers of updateUserById method ### Returns This function returns a value of type `UserFull`. Returns the updated user object. ## Delete user Deletes a user. By default this will fail if the user still owns any content. Move their owned content first before proceeding, or use the `force` field to delete the user and their files. This operation is performed by calling function `deleteUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id/). ``` try await client.users.deleteUserById(userId: user.id) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" queryParams `DeleteUserByIdQueryParams` - Query parameters of deleteUserById method headers `DeleteUserByIdHeaders` - Headers of deleteUserById method ### Returns This function returns a value of type ``. Removes the user and returns an empty response. --- ## Untitled *Type: page* UserCollaborationsManager Get collaboration Update collaboration Remove collaboration Create collaboration Get collaboration Retrieves a… # UserCollaborationsManager - [Get collaboration](#get-collaboration) - [Update collaboration](#update-collaboration) - [Remove collaboration](#remove-collaboration) - [Create collaboration](#create-collaboration) ## Get collaboration Retrieves a single collaboration. This operation is performed by calling function `getCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations-id/). ``` try await client.userCollaborations.getCollaborationById(collaborationId: collaborationId) ``` ### Arguments collaborationId `String` - The ID of the collaboration. Example: "1234" queryParams `GetCollaborationByIdQueryParams` - Query parameters of getCollaborationById method headers `GetCollaborationByIdHeaders` - Headers of getCollaborationById method ### Returns This function returns a value of type `Collaboration`. Returns a collaboration object. ## Update collaboration Updates a collaboration. Can be used to change the owner of an item, or to accept collaboration invites. This operation is performed by calling function `updateCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-collaborations-id/). ``` try await client.userCollaborations.updateCollaborationById(collaborationId: collaborationId, requestBody: UpdateCollaborationByIdRequestBody(role: UpdateCollaborationByIdRequestBodyRoleField.viewer)) ``` ### Arguments collaborationId `String` - The ID of the collaboration. Example: "1234" requestBody `UpdateCollaborationByIdRequestBody` - Request body of updateCollaborationById method headers `UpdateCollaborationByIdHeaders` - Headers of updateCollaborationById method ### Returns This function returns a value of type `Collaboration?`. Returns an updated collaboration object unless the owner has changed.If the role is changed to `owner`, the collaboration is deleted and a new collaboration is created. The previous `owner` of the old collaboration will be a `co-owner` on the new collaboration. ## Remove collaboration Deletes a single collaboration. This operation is performed by calling function `deleteCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaborations-id/). ``` try await client.userCollaborations.deleteCollaborationById(collaborationId: collaborationId) ``` ### Arguments collaborationId `String` - The ID of the collaboration. Example: "1234" headers `DeleteCollaborationByIdHeaders` - Headers of deleteCollaborationById method ### Returns This function returns a value of type ``. A blank response is returned if the collaboration was successfully deleted. ## Create collaboration Adds a collaboration for a single user or a single group to a file or folder. Collaborations can be created using email address, user IDs, or a group IDs. If a collaboration is being created with a group, access to this endpoint is dependent on the group's ability to be invited. If collaboration is in `pending` status, the following fields are redacted: - `login` and `name` are hidden if a collaboration was created using `user_id`, - `name` is hidden if a collaboration was created using `login`. This operation is performed by calling function `createCollaboration`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaborations/). ``` try await client.userCollaborations.createCollaboration(requestBody: CreateCollaborationRequestBody(item: CreateCollaborationRequestBodyItemField(type: CreateCollaborationRequestBodyItemTypeField.folder, id: folder.id), accessibleBy: CreateCollaborationRequestBodyAccessibleByField(type: CreateCollaborationRequestBodyAccessibleByTypeField.user, id: user.id), role: CreateCollaborationRequestBodyRoleField.editor)) ``` ### Arguments requestBody `CreateCollaborationRequestBody` - Request body of createCollaboration method queryParams `CreateCollaborationQueryParams` - Query parameters of createCollaboration method headers `CreateCollaborationHeaders` - Headers of createCollaboration method ### Returns This function returns a value of type `Collaboration`. Returns a new collaboration object. --- ## Untitled *Type: page* TrashedItemsManager List trashed items List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute… # TrashedItemsManager - [List trashed items](#list-trashed-items) ## List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute in the full files or folders objects can be passed in with the `fields` parameter to retrieve those specific attributes that are not returned by default. This endpoint defaults to use offset-based pagination, yet also supports marker-based pagination using the `marker` parameter. This operation is performed by calling function `getTrashedItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-trash-items/). ``` try await client.trashedItems.getTrashedItems() ``` ### Arguments queryParams `GetTrashedItemsQueryParams` - Query parameters of getTrashedItems method headers `GetTrashedItemsHeaders` - Headers of getTrashedItems method ### Returns This function returns a value of type `Items`. Returns a list of items that have been deleted. --- ## Untitled *Type: page* WebLinksManager Create web link Get web link Update web link Remove web link Create web link Creates a web link object within a folder. This… # WebLinksManager - [Create web link](#create-web-link) - [Get web link](#get-web-link) - [Update web link](#update-web-link) - [Remove web link](#remove-web-link) ## Create web link Creates a web link object within a folder. This operation is performed by calling function `createWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links/). ``` try await client.webLinks.createWebLink(requestBody: CreateWebLinkRequestBody(url: "https://www.box.com", parent: CreateWebLinkRequestBodyParentField(id: parent.id), name: Utils.getUUID(), description: "Weblink description")) ``` ### Arguments requestBody `CreateWebLinkRequestBody` - Request body of createWebLink method headers `CreateWebLinkHeaders` - Headers of createWebLink method ### Returns This function returns a value of type `WebLink`. Returns the newly created web link object. ## Get web link Retrieve information about a web link. This operation is performed by calling function `getWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id/). ``` try await client.webLinks.getWebLinkById(webLinkId: weblink.id) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" headers `GetWebLinkByIdHeaders` - Headers of getWebLinkById method ### Returns This function returns a value of type `WebLink`. Returns the web link object. ## Update web link Updates a web link object. This operation is performed by calling function `updateWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id/). ``` try await client.webLinks.updateWebLinkById(webLinkId: weblink.id, requestBody: UpdateWebLinkByIdRequestBody(name: updatedName, sharedLink: UpdateWebLinkByIdRequestBodySharedLinkField(access: UpdateWebLinkByIdRequestBodySharedLinkAccessField.open, password: password))) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `UpdateWebLinkByIdRequestBody` - Request body of updateWebLinkById method headers `UpdateWebLinkByIdHeaders` - Headers of updateWebLinkById method ### Returns This function returns a value of type `WebLink`. Returns the updated web link object. ## Remove web link Deletes a web link. This operation is performed by calling function `deleteWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id/). ``` try await client.webLinks.deleteWebLinkById(webLinkId: webLinkId) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" headers `DeleteWebLinkByIdHeaders` - Headers of deleteWebLinkById method ### Returns This function returns a value of type ``. An empty response will be returned when the web link was successfully deleted. --- ## Untitled *Type: page* WebhooksManager List all webhooks Create webhook Get webhook Update webhook Remove webhook List all webhooks Returns all defined webhooks… # WebhooksManager - [List all webhooks](#list-all-webhooks) - [Create webhook](#create-webhook) - [Get webhook](#get-webhook) - [Update webhook](#update-webhook) - [Remove webhook](#remove-webhook) ## List all webhooks Returns all defined webhooks for the requesting application. This API only returns webhooks that are applied to files or folders that are owned by the authenticated user. This means that an admin can not see webhooks created by a service account unless the admin has access to those folders, and vice versa. This operation is performed by calling function `getWebhooks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks/). ``` try await client.webhooks.getWebhooks() ``` ### Arguments queryParams `GetWebhooksQueryParams` - Query parameters of getWebhooks method headers `GetWebhooksHeaders` - Headers of getWebhooks method ### Returns This function returns a value of type `Webhooks`. Returns a list of webhooks. ## Create webhook Creates a webhook. This operation is performed by calling function `createWebhook`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-webhooks/). ``` try await client.webhooks.createWebhook(requestBody: CreateWebhookRequestBody(target: CreateWebhookRequestBodyTargetField(id: folder.id, type: CreateWebhookRequestBodyTargetTypeField.folder), address: "https://example.com/new-webhook", triggers: [CreateWebhookRequestBodyTriggersField.fileUploaded])) ``` ### Arguments requestBody `CreateWebhookRequestBody` - Request body of createWebhook method headers `CreateWebhookHeaders` - Headers of createWebhook method ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Get webhook Retrieves a specific webhook. This operation is performed by calling function `getWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks-id/). ``` try await client.webhooks.getWebhookById(webhookId: webhook.id!) ``` ### Arguments webhookId `String` - The ID of the webhook. Example: "3321123" headers `GetWebhookByIdHeaders` - Headers of getWebhookById method ### Returns This function returns a value of type `Webhook`. Returns a webhook object. ## Update webhook Updates a webhook. This operation is performed by calling function `updateWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-webhooks-id/). ``` try await client.webhooks.updateWebhookById(webhookId: webhook.id!, requestBody: UpdateWebhookByIdRequestBody(address: "https://example.com/updated-webhook")) ``` ### Arguments webhookId `String` - The ID of the webhook. Example: "3321123" requestBody `UpdateWebhookByIdRequestBody` - Request body of updateWebhookById method headers `UpdateWebhookByIdHeaders` - Headers of updateWebhookById method ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Remove webhook Deletes a webhook. This operation is performed by calling function `deleteWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-webhooks-id/). ``` try await client.webhooks.deleteWebhookById(webhookId: webhook.id!) ``` ### Arguments webhookId `String` - The ID of the webhook. Example: "3321123" headers `DeleteWebhookByIdHeaders` - Headers of deleteWebhookById method ### Returns This function returns a value of type ``. An empty response will be returned when the webhook was successfully deleted. --- ## Untitled *Type: page* WorkflowsManager List workflows Starts workflow based on request body List workflows Returns list of workflows that act on a given folder ID… # WorkflowsManager - [List workflows](#list-workflows) - [Starts workflow based on request body](#starts-workflow-based-on-request-body) ## List workflows Returns list of workflows that act on a given `folder ID`, and have a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in to use this endpoint. This operation is performed by calling function `getWorkflows`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-workflows/). ``` try await adminClient.workflows.getWorkflows(queryParams: GetWorkflowsQueryParams(folderId: workflowFolderId)) ``` ### Arguments queryParams `GetWorkflowsQueryParams` - Query parameters of getWorkflows method headers `GetWorkflowsHeaders` - Headers of getWorkflows method ### Returns This function returns a value of type `Workflows`. Returns the workflow. ## Starts workflow based on request body Initiates a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console. This operation is performed by calling function `startWorkflow`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-workflows-id-start/). ``` try await adminClient.workflows.startWorkflow(workflowId: workflowToRun.id!, requestBody: StartWorkflowRequestBody(type: StartWorkflowRequestBodyTypeField.workflowParameters, flow: StartWorkflowRequestBodyFlowField(type: "flow", id: workflowToRun.flows![0].id!), files: [StartWorkflowRequestBodyFilesField(type: StartWorkflowRequestBodyFilesTypeField.file, id: workflowFileId)], folder: StartWorkflowRequestBodyFolderField(type: StartWorkflowRequestBodyFolderTypeField.folder, id: workflowFolderId))) ``` ### Arguments workflowId `String` - The ID of the workflow. Example: "12345" requestBody `StartWorkflowRequestBody` - Request body of startWorkflow method headers `StartWorkflowHeaders` - Headers of startWorkflow method ### Returns This function returns a value of type ``. Starts the workflow. --- ## Untitled *Type: page* Handling null values in Box Swift SDK Gen While using Box Swift SDK it's important to understand how null values behave. This document… # Handling null values in Box Swift SDK Gen While using Box Swift SDK it's important to understand how null values behave. This document provides a general overview of null value behaviour in Box Swift SDK to help developers manage data consistently and predictably. ## Understanding null behaviour The Box Swift SDK follows a consistent pattern for handling null values in update operations. This behavior applies to most endpoints that modify resources such as users, files, folders, and metadata. Fields to be updated are wrapped in a `TriStateField` within the initializer. This allows you to specify whether a field should be sent with a value, sent explicitly as null, or omitted entirely. ### Send field with some value Since these fields are wrapped in the `TriStateField<T>` enum (where `T` is the original type of the property), you can set them using the .value case, like `.value(yourActualValue)`. If the original type is a value type such as `String`, `Int`, or `Bool`, you can also assign the value directly without wrapping it in the enum, this will be handled automatically for you. Let’s take a look at the `RetentionPolicyAssignmentFilterFieldsField` class, whose initializer looks like this: ``` public init(field: TriStateField<String> = nil, value: TriStateField<String> = nil) { ...} ``` To initialize an instance of `RetentionPolicyAssignmentFilterFieldsField` with some values, you can do it in two ways: ``` let filterField = RetentionPolicyAssignmentFilterFieldsField(field: .value("my_field_name"), value: "my actual value") ``` In the example above, we set two parameters: field and value, using different methods. The field is set with the `.value(..)` case, while value, being a `String` type, is provided directly without wrapping it in the enum. By filling in these fields, both will be included in the request. ### Send field with null In some APIs, the `null` value has a different meaning than simply omitting the field. Setting a field to `null` will remove its current value or disassociate it from the resource on the server side. This is the reason we use the `TriStateField` enum, which allows you to explicitly set a field to `null`. To set a field to `null`, you should use the `.null` case of the `TriStateField` enum. This will be translated to `null` in the request body. ### Omit the field If you want to omit a field, there are three ways to achieve that: - Omitting the field in the initializer - Setting it to `nil` - Setting it to `.unset` Any of these options will result in the field being omitted from the request body. For consistency with other cases where fields are optional, setting these fields to nil will be treated the same as omitting them. ## Example Usage The client.files.createUpdateFile() method demonstrates null handling when modifying the lock field while updating the file: ``` public func createUpdateFile(client: BoxClient) async throws { let fileId = "12345" // Locking the file using .value() wrapper let fileWithLock = try await client.files.updateFileById( fileId: fileId, requestBody: UpdateFileByIdRequestBody(lock: .value(UpdateFileByIdRequestBodyLockField(access: .lock))), queryParams: UpdateFileByIdQueryParams(fields: ["lock"]) ) // Unlocking the file using the `.null` let fileWithoutLock = try await client.files.updateFileById( fileId: fileId, requestBody: UpdateFileByIdRequestBody(lock: .null), queryParams: UpdateFileByIdQueryParams(fields: ["lock"]) ) } ``` ## Summary To summarize, if you omit the field, set it to `nil`, or set it to `.unset`, the field remains unchanged. If you set it to `.null`, it clears or removes the value. If you provide a value by wrapping it in `.value(your_value)`, the field is updated to that specified value. --- ## Untitled *Type: page* ZipDownloadsManager Create zip download Download zip archive Get zip download status Download ZIP Create zip download Creates a request to… # ZipDownloadsManager - [Create zip download](#create-zip-download) - [Download zip archive](#download-zip-archive) - [Get zip download status](#get-zip-download-status) - [Download ZIP](#download-zip) ## Create zip download Creates a request to download multiple files and folders as a single `zip` archive file. This API does not return the archive but instead performs all the checks to ensure that the user has access to all the items, and then returns a `download_url` and a `status_url` that can be used to download the archive. The limit for an archive is either the Account's upload limit or 10,000 files, whichever is met first. **Note**: Downloading a large file can be affected by various factors such as distance, network latency, bandwidth, and congestion, as well as packet loss ratio and current server load. For these reasons we recommend that a maximum ZIP archive total size does not exceed 25GB. This operation is performed by calling function `createZipDownload`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-zip-downloads/). ``` try await client.zipDownloads.createZipDownload(requestBody: ZipDownloadRequest(items: [ZipDownloadRequestItemsField(id: file1.id, type: ZipDownloadRequestItemsTypeField.file), ZipDownloadRequestItemsField(id: file2.id, type: ZipDownloadRequestItemsTypeField.file), ZipDownloadRequestItemsField(id: folder1.id, type: ZipDownloadRequestItemsTypeField.folder)], downloadFileName: "zip")) ``` ### Arguments requestBody `ZipDownloadRequest` - Request body of createZipDownload method headers `CreateZipDownloadHeaders` - Headers of createZipDownload method ### Returns This function returns a value of type `ZipDownload`. If the `zip` archive is ready to be downloaded, the API will return a response that will include a `download_url`, a `status_url`, as well as any conflicts that might have occurred when creating the request. ## Download zip archive Returns the contents of a `zip` archive in binary format. This URL does not require any form of authentication and could be used in a user's browser to download the archive to a user's device. By default, this URL is only valid for a few seconds from the creation of the request for this archive. Once a download has started it can not be stopped and resumed, instead a new request for a zip archive would need to be created. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `download_url` field in the response to this endpoint. This operation is performed by calling function `getZipDownloadContent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-content/). ``` try await client.zipDownloads.getZipDownloadContent(downloadUrl: zipDownload.downloadUrl!, downloadDestinationUrl: URL(path: destinationPathString)) ``` ### Arguments downloadUrl `String` - The URL that can be used to download created `zip` archive. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content` downloadDestinationUrl `URL` - The URL on disk where the file will be saved once it has been downloaded. headers `GetZipDownloadContentHeaders` - Headers of getZipDownloadContent method ### Returns This function returns a value of type `URL?`. Returns the content of the items requested for this download, formatted as a stream of files and folders in a `zip` archive. ## Get zip download status Returns the download status of a `zip` archive, allowing an application to inspect the progress of the download as well as the number of items that might have been skipped. This endpoint can only be accessed once the download has started. Subsequently this endpoint is valid for 12 hours from the start of the download. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `status_url` field in the response to this endpoint. This operation is performed by calling function `getZipDownloadStatus`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-status/). ``` try await client.zipDownloads.getZipDownloadStatus(statusUrl: zipDownload.statusUrl!) ``` ### Arguments statusUrl `String` - The URL that can be used to get the status of the `zip` archive being downloaded. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status` headers `GetZipDownloadStatusHeaders` - Headers of getZipDownloadStatus method ### Returns This function returns a value of type `ZipDownloadStatus`. Returns the status of the `zip` archive that is being downloaded. ## Download ZIP Creates a zip and downloads its content This operation is performed by calling function `downloadZip`. ``` try await client.zipDownloads.downloadZip(requestBody: ZipDownloadRequest(items: [ZipDownloadRequestItemsField(id: file1.id, type: ZipDownloadRequestItemsTypeField.file), ZipDownloadRequestItemsField(id: file2.id, type: ZipDownloadRequestItemsTypeField.file), ZipDownloadRequestItemsField(id: folder1.id, type: ZipDownloadRequestItemsTypeField.folder)], downloadFileName: "zip"), downloadDestinationUrl: URL(path: destinationPathString)) ``` ### Arguments requestBody `ZipDownloadRequest` - Zip download request body downloadDestinationUrl `URL` - The URL on disk where the file will be saved once it has been downloaded. headers `DownloadZipHeaders` - Headers of zip download method ### Returns This function returns a value of type `URL?`. --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 0.6.1 (2025-03-1… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### 0.6.1 (2025-03-18) ### Bug Fixes - Add `verification_phone_number` property to create sign request (box/box-openapi[#515](https://github.com/box/box-swift-sdk-gen/issues/515)) ([#391](https://github.com/box/box-swift-sdk-gen/issues/391)) ([717b3a8](https://github.com/box/box-swift-sdk-gen/commit/717b3a8b285dfab92a9446cbd84443caa8dde148)) ### New Features and Enhancements - Add find app item for shared link endpoint (box/box-openapi[#514](https://github.com/box/box-swift-sdk-gen/issues/514)) ([#390](https://github.com/box/box-swift-sdk-gen/issues/390)) ([07b9be5](https://github.com/box/box-swift-sdk-gen/commit/07b9be5d523f3d3fb89bdbb240e4ca9628a3736d)) - Add hubs support to `/ai/ask` (box/box-codegen[#656](https://github.com/box/box-swift-sdk-gen/issues/656)) ([#364](https://github.com/box/box-swift-sdk-gen/issues/364)) ([9a49864](https://github.com/box/box-swift-sdk-gen/commit/9a4986499eaefffdb4f2593968d59eaf030f516f)) - Add Integration Mappings Teams API (box/box-openapi[#517](https://github.com/box/box-swift-sdk-gen/issues/517)) ([#393](https://github.com/box/box-swift-sdk-gen/issues/393)) ([b9ed4e3](https://github.com/box/box-swift-sdk-gen/commit/b9ed4e35d17f85c1d2bc2a4e9e148ae009551348)) - Expose token storage for authentication classes (box/box-codegen[#682](https://github.com/box/box-swift-sdk-gen/issues/682)) ([#400](https://github.com/box/box-swift-sdk-gen/issues/400)) ([08221e5](https://github.com/box/box-swift-sdk-gen/commit/08221e59cabc4042ea1d43bf578c2069ad66b444)) - Support AI Studio API (box/box-codegen[#626](https://github.com/box/box-swift-sdk-gen/issues/626)) ([#375](https://github.com/box/box-swift-sdk-gen/issues/375)) ([802571d](https://github.com/box/box-swift-sdk-gen/commit/802571dd34977ae2ebf674dbdddd3e140829b819)) - Support unknown enum values in Swift (box/box-codegen[#670](https://github.com/box/box-swift-sdk-gen/issues/670)) ([#382](https://github.com/box/box-swift-sdk-gen/issues/382)) ([8fe7ff4](https://github.com/box/box-swift-sdk-gen/commit/8fe7ff45fa4e45f743acd4450270d945b0afd393)) - Support upload with preflight check (box/box-codegen[#676](https://github.com/box/box-swift-sdk-gen/issues/676)) ([#399](https://github.com/box/box-swift-sdk-gen/issues/399)) ([1befb4c](https://github.com/box/box-swift-sdk-gen/commit/1befb4c1b4898375ea3ab353c7149fd10adc1f17)) - Update `/ai/extract_structured` response schema (box/box-codegen[#641](https://github.com/box/box-swift-sdk-gen/issues/641)) ([#358](https://github.com/box/box-swift-sdk-gen/issues/358)) ([430611a](https://github.com/box/box-swift-sdk-gen/commit/430611a0036258d5f3ff8e1c6de0b833255ce0ed)) ## 0.6.0 (2025-01-27) ### Bug Fixes - Add missing token scope (box/box-openapi[#490](https://github.com/box/box-swift-sdk-gen/issues/490)) ([#319](https://github.com/box/box-swift-sdk-gen/issues/319)) ([220134e](https://github.com/box/box-swift-sdk-gen/commit/220134efb4ba42628de51561749ae218707d5121)) - Change signature of `readBufferFromFile` method (box/box-codegen[#575](https://github.com/box/box-swift-sdk-gen/issues/575)) ([#250](https://github.com/box/box-swift-sdk-gen/issues/250)) ([21e08ff](https://github.com/box/box-swift-sdk-gen/commit/21e08ff673da44c0dfe502c5fbbc14e382ef368b)) - Correct types of `paged` and `thumb` properties in File representation (box/box-openapi[#503](https://github.com/box/box-swift-sdk-gen/issues/503)) ([#347](https://github.com/box/box-swift-sdk-gen/issues/347)) ([58ff930](https://github.com/box/box-swift-sdk-gen/commit/58ff9305b34306ca506b08d43b72f95349322172)) - fix `IntegrationMapping` schemas description (box/box-openapi[#463](https://github.com/box/box-swift-sdk-gen/issues/463)) ([#257](https://github.com/box/box-swift-sdk-gen/issues/257)) ([794f315](https://github.com/box/box-swift-sdk-gen/commit/794f31548687b4e78e6f96b1a922e7e32dce0b9b)) - Fix invalid variant config for Integration mapping Slack (box/box-openapi[#492](https://github.com/box/box-swift-sdk-gen/issues/492)) ([#322](https://github.com/box/box-swift-sdk-gen/issues/322)) ([97f4f94](https://github.com/box/box-swift-sdk-gen/commit/97f4f944555997b5e09afd66eb9c07008fae8a94)) - Fix order of fields in the `IntegrationMapping` schema (box/box-openapi[#497](https://github.com/box/box-swift-sdk-gen/issues/497)) ([#335](https://github.com/box/box-swift-sdk-gen/issues/335)) ([cb28e6d](https://github.com/box/box-swift-sdk-gen/commit/cb28e6db015d84b59e6dccf6a2fa90c26de20efa)) - remove unused parameter from `SignRequest` (box/box-openapi[#489](https://github.com/box/box-swift-sdk-gen/issues/489)) ([#310](https://github.com/box/box-swift-sdk-gen/issues/310)) ([879897b](https://github.com/box/box-swift-sdk-gen/commit/879897bec80669a46effc2528ec19ce15d7df3b1)) - Support status codes with no content (box/box-codegen[#604](https://github.com/box/box-swift-sdk-gen/issues/604)) ([#284](https://github.com/box/box-swift-sdk-gen/issues/284)) ([5823d2b](https://github.com/box/box-swift-sdk-gen/commit/5823d2b1591cb1c817e36a43a78cb41498fcf1b4)) - update client error schema to support schema errors (box/box-openapi[#467](https://github.com/box/box-swift-sdk-gen/issues/467)) ([#259](https://github.com/box/box-swift-sdk-gen/issues/259)) ([40e2279](https://github.com/box/box-swift-sdk-gen/commit/40e2279e222df4a88278125a6a9a13ee4605cd69)) - update collaboration, metadata and collection resources (box/box-openapi[#483](https://github.com/box/box-swift-sdk-gen/issues/483)) ([#286](https://github.com/box/box-swift-sdk-gen/issues/286)) ([f5b190a](https://github.com/box/box-swift-sdk-gen/commit/f5b190a648f0c567abe688bd111a5b7c779a036c)) ### New Features and Enhancements - Add `aiAgent` info to `AiResponse` (box/box-openapi[#485](https://github.com/box/box-swift-sdk-gen/issues/485)) ([#304](https://github.com/box/box-swift-sdk-gen/issues/304)) ([b614a6f](https://github.com/box/box-swift-sdk-gen/commit/b614a6fe72689ed56947b05cac26a5b62104a621)) - add AI LLM endpoint AWS `params` (box/box-openapi[#478](https://github.com/box/box-swift-sdk-gen/issues/478)) ([#267](https://github.com/box/box-swift-sdk-gen/issues/267)) ([36ee37d](https://github.com/box/box-swift-sdk-gen/commit/36ee37d96ce0a50292036c02e4663fd124544736)) - Add Box Sign shared requests (box/box-openapi[#504](https://github.com/box/box-swift-sdk-gen/issues/504)) ([#348](https://github.com/box/box-swift-sdk-gen/issues/348)) ([2f5e2f1](https://github.com/box/box-swift-sdk-gen/commit/2f5e2f150d45f833fda2ef6e61e6c946ed0c36ad)) - Add support for replacing the network client implementation (box/box-codegen[#629](https://github.com/box/box-swift-sdk-gen/issues/629)) ([#313](https://github.com/box/box-swift-sdk-gen/issues/313)) ([e08a117](https://github.com/box/box-swift-sdk-gen/commit/e08a117c34e782b83a1fdd7a471938351cd00c6e)) - Expose method for making custom HTTP requests (box/box-codegen[#610](https://github.com/box/box-swift-sdk-gen/issues/610)) ([#297](https://github.com/box/box-swift-sdk-gen/issues/297)) ([f7da2e3](https://github.com/box/box-swift-sdk-gen/commit/f7da2e31f8e49cdd0b0e62e798d7d93bcea6c50b)) - Support `ai/extract` and `ai/extract_structured` endpoints (box/box-codegen[#564](https://github.com/box/box-swift-sdk-gen/issues/564)) ([#239](https://github.com/box/box-swift-sdk-gen/issues/239)) ([9b5d6e9](https://github.com/box/box-swift-sdk-gen/commit/9b5d6e9f31cbcc2411f34be1572ec91c7e4808cf)) - Support Box Doc Gen API (box/box-codegen[#644](https://github.com/box/box-swift-sdk-gen/issues/644)) ([#343](https://github.com/box/box-swift-sdk-gen/issues/343)) ([8ef2533](https://github.com/box/box-swift-sdk-gen/commit/8ef25335ecba4fcf2243c8043edc7edc46dbe932)) - Support get collection by ID endpoint (box/box-codegen[#595](https://github.com/box/box-swift-sdk-gen/issues/595)) ([#276](https://github.com/box/box-swift-sdk-gen/issues/276)) ([112828f](https://github.com/box/box-swift-sdk-gen/commit/112828fc499c3148c385dde6adb4fcfe5b791495)) - Support optional `userId` parameter for updating files, folders and web links (box/box-openapi[#488](https://github.com/box/box-swift-sdk-gen/issues/488)) ([#308](https://github.com/box/box-swift-sdk-gen/issues/308)) ([8bd13d0](https://github.com/box/box-swift-sdk-gen/commit/8bd13d024e7f74a15c3377ddfd54bfcdbec71e2b)) - update client error schema to support schema errors (box/box-openapi[#467](https://github.com/box/box-swift-sdk-gen/issues/467)) ([#266](https://github.com/box/box-swift-sdk-gen/issues/266)) ([4bcf843](https://github.com/box/box-swift-sdk-gen/commit/4bcf8439b03e8f3726e51f210bfa71ed3d8d6793)) - Use `retrieveAuthorizationHeader` method in fetch (box/box-codegen[#565](https://github.com/box/box-swift-sdk-gen/issues/565)) ([#235](https://github.com/box/box-swift-sdk-gen/issues/235)) ([f68e141](https://github.com/box/box-swift-sdk-gen/commit/f68e14174476a40b959280c391475ac8fef644e1)) ## 0.5.0 (2024-09-11) ### Bug Fixes - Fix variants in metadata query results (box/box-openapi[#456](https://github.com/box/box-codegen/issues/456)) ([#232](https://github.com/box/box-codegen/issues/232)) ([be2fa52](https://github.com/box/box-codegen/commit/be2fa52bb0d086f6c9b20fd5c3bdcad4b98f3f37)) ### New Features and Enhancements - add Hubs Beta (box/box-openapi[#453](https://github.com/box/box-codegen/issues/453)) ([#220](https://github.com/box/box-codegen/issues/220)) ([546f487](https://github.com/box/box-codegen/commit/546f487bde9dae2407ff65620eb6e6a81e45b149)) ## 0.4.0 (2024-09-05) ### Bug Fixes - Add missing fields to Sign Template Signer and fix AI schema (box/box-openapi[#451](https://github.com/box/box-codegen/issues/451)) ([#206](https://github.com/box/box-codegen/issues/206)) ([31920e6](https://github.com/box/box-codegen/commit/31920e67692c16b0600c4c9f4c279e22d02e4598)) - Fix `IntegrationMapping` schemas (box/box-codegen[#551](https://github.com/box/box-codegen/issues/551)) ([#203](https://github.com/box/box-codegen/issues/203)) ([0074ee3](https://github.com/box/box-codegen/commit/0074ee326627d01057cf50cb257d2291b646ab08)) ### New Features and Enhancements - Fix chunk upload in Swift (box/box-codegen[#555](https://github.com/box/box-codegen/issues/555)) ([#215](https://github.com/box/box-codegen/issues/215)) ([93ff568](https://github.com/box/box-codegen/commit/93ff5686415d99aa807d57d9e062f5a96380d707)) - Include URL into `FetchOptions` (box/box-codegen[#549](https://github.com/box/box-codegen/issues/549)) ([#208](https://github.com/box/box-codegen/issues/208)) ([b65822d](https://github.com/box/box-codegen/commit/b65822d379b1d5e9be7b179ed754e725f5a499fa)) ### 0.3.1 (2024-08-22) ### Bug Fixes - Extract `IntegrationMappingPartnerItemSlack` to `IntegrationMappingPartnerItemSlackUnion` (box/box-codegen[#530](https://github.com/box/box-codegen/issues/530)) ([#165](https://github.com/box/box-codegen/issues/165)) ([d51df9a](https://github.com/box/box-codegen/commit/d51df9a19d06db886358e94ce70551c283e5cc45)) - Improve chunked upload reliability (box/box-codegen[#529](https://github.com/box/box-codegen/issues/529)) ([#164](https://github.com/box/box-codegen/issues/164)) ([5d87629](https://github.com/box/box-codegen/commit/5d876299aa88b18accde22379950780bff100da0)) - Retry requests with 202 status code and `Retry-After` header (box/box-codegen[#538](https://github.com/box/box-codegen/issues/538)) ([#177](https://github.com/box/box-codegen/issues/177)) ([64f27b3](https://github.com/box/box-codegen/commit/64f27b3858725adaa53a10a6e8df8c0bcfe73fea)) ### New Features and Enhancements - Add `is_active` parameter to user collaboration (box/box-openapi[#437](https://github.com/box/box-codegen/issues/437)) ([#163](https://github.com/box/box-codegen/issues/163)) ([5f726bb](https://github.com/box/box-codegen/commit/5f726bbffd682934ab5731e1620489b1ee54e5a1)) - Add new parameters to Box AI methods and introduce `AiResponseFull` variant (box/box-openapi[#446](https://github.com/box/box-codegen/issues/446)) ([#201](https://github.com/box/box-codegen/issues/201)) ([7c09090](https://github.com/box/box-codegen/commit/7c0909032733742cb5a019c897910ced2e9d6788)) - Add support for Swift 5.6 (box/box-codegen[#541](https://github.com/box/box-codegen/issues/541)) ([#180](https://github.com/box/box-codegen/issues/180)) ([04b7020](https://github.com/box/box-codegen/commit/04b7020f1220f73ad4637e6033d5539c56a64fcd)) - parametrise chunked uploads endpoint urls (box/box-openapi[#444](https://github.com/box/box-codegen/issues/444)) ([#192](https://github.com/box/box-codegen/issues/192)) ([ea18f9e](https://github.com/box/box-codegen/commit/ea18f9e5eb6558edb29ff378bceb5528ccd4fcfb)) - Support AI Agent API (box/box-codegen[#531](https://github.com/box/box-codegen/issues/531)) ([#170](https://github.com/box/box-codegen/issues/170)) ([fc9a00b](https://github.com/box/box-codegen/commit/fc9a00bdcaffeaccfd87caad73fe666fb46c36ab)) ## 0.3.0 (2024-06-28) ### Bug Fixes - Change base urls (box/box-codegen[#491](https://github.com/box/box-codegen/issues/491)) ([#115](https://github.com/box/box-codegen/issues/115)) ([d0a7adb](https://github.com/box/box-codegen/commit/d0a7adb201c823313f0a5de25fa4fc5469590c97)) - Fix Box AI endpoints (box/box-openapi[#418](https://github.com/box/box-codegen/issues/418)) ([#88](https://github.com/box/box-codegen/issues/88)) ([022f83a](https://github.com/box/box-codegen/commit/022f83aaa7fbe3f4292a06527875123ecc7b99f0)) - Fix CI for auto update pull requests (box/box-codegen[#506](https://github.com/box/box-codegen/issues/506)) ([#135](https://github.com/box/box-codegen/issues/135)) ([a62e238](https://github.com/box/box-codegen/commit/a62e238534cb625dbc98cbe59c98939c78b74f4a)) - fix deserialisation of Union with array in Swift (box/box-codegen[#486](https://github.com/box/box-codegen/issues/486)) ([#94](https://github.com/box/box-codegen/issues/94)) ([4f187be](https://github.com/box/box-codegen/commit/4f187bed1e88c93c1258be8723a39b45129ff21f)) - Fix metadata filter resource (box/box-openapi[#419](https://github.com/box/box-codegen/issues/419)) ([#90](https://github.com/box/box-codegen/issues/90)) ([b04f7ce](https://github.com/box/box-codegen/commit/b04f7ceee9bca4f1f19d66401f38636e7737b4b1)) - Fix schemas for updating classification on a file and folder (box/box-openapi[#423](https://github.com/box/box-codegen/issues/423)) ([#104](https://github.com/box/box-codegen/issues/104)) ([caa9d2b](https://github.com/box/box-codegen/commit/caa9d2b7d0a6c2728f543fa19acb7859f21fb5c9)) - improve wording for box sign (box/box-openapi[#424](https://github.com/box/box-codegen/issues/424)) ([#111](https://github.com/box/box-codegen/issues/111)) ([4fa69f0](https://github.com/box/box-codegen/commit/4fa69f01ca3a2a7fc8dcdc71cbecb03c469a83e6)) ### New Features and Enhancements - add missing marker pagination fields and introduce new event type `(box/box-openapi[#431](https://github.com/box/box-codegen/issues/431))` ([#136](https://github.com/box/box-codegen/issues/136)) ([b186b11](https://github.com/box/box-codegen/commit/b186b11a2c591cd4fdd3b50733750a7bb4ec94e9)) - Add support for `visionOS` and add privacy manifest file for swift `(box/box-codegen[#510](https://github.com/box/box-codegen/issues/510))` ([#139](https://github.com/box/box-codegen/issues/139)) ([7fc76fc](https://github.com/box/box-codegen/commit/7fc76fc1799db0a50ad22eb047d013c4597c5277)) - Add support for Date in Swift (box/box-codegen[#488](https://github.com/box/box-codegen/issues/488)) ([#103](https://github.com/box/box-codegen/issues/103)) ([7e1ea1a](https://github.com/box/box-codegen/commit/7e1ea1af553cc8458eb9026c777608f7929e686d)) - Improve chunk upload in Swift `(box/box-codegen[#515](https://github.com/box/box-codegen/issues/515))` ([#143](https://github.com/box/box-codegen/issues/143)) ([b8099ab](https://github.com/box/box-codegen/commit/b8099ab41ea5b8706e14285a0f9db2fd3c0a7a6d)) - move notification suppression to public schema (box/box-openapi[#425](https://github.com/box/box-codegen/issues/425)) ([#113](https://github.com/box/box-codegen/issues/113)) ([069be60](https://github.com/box/box-codegen/commit/069be60613889b45b396bbe22262c5f8df32b158)) - Move schemas to separate modules (box/box-codegen[#483](https://github.com/box/box-codegen/issues/483)) ([#99](https://github.com/box/box-codegen/issues/99)) ([c7a8506](https://github.com/box/box-codegen/commit/c7a85069544c28e2be918eafd9e240f39660ead3)) - Start throwing common errors `(box/box-codegen[#516](https://github.com/box/box-codegen/issues/516))` ([#147](https://github.com/box/box-codegen/issues/147)) ([d12bbb7](https://github.com/box/box-codegen/commit/d12bbb7d06bd3fcf39c31e316f1047065b56baac)) - Support Box AI endpoints (box/box-openapi[#416](https://github.com/box/box-codegen/issues/416)) ([#86](https://github.com/box/box-codegen/issues/86)) ([175ab82](https://github.com/box/box-codegen/commit/175ab82c18dc390bcd4c8e20aea8e405a2e31c4d)) - Support chunk upload in Swift `(box/box-codegen[#513](https://github.com/box/box-codegen/issues/513))` ([#142](https://github.com/box/box-codegen/issues/142)) ([9e0b4e2](https://github.com/box/box-codegen/commit/9e0b4e26a9283b5900ae0fe0fa858394b732f51b)) - support excluding endpoints and schemas in parser (box/box-codegen[#487](https://github.com/box/box-codegen/issues/487)) ([#100](https://github.com/box/box-codegen/issues/100)) ([af9e171](https://github.com/box/box-codegen/commit/af9e171c101703c98ff9a53093d7fc9c306137d9)) --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - this project is generated using [Box Codegen](https://github.com/box/box-codegen) based on[Box OpenAPI 3.0 Specification](https://github.com/box/box-openapi), so if you want found something you want to change in the generated code, you'll need to modify the codegen project and submit a pull request there. --- ## Untitled *Type: page* Box Swift SDK GENERATED Project Status build Platforms Coverage Swift Package Manager Carthage compatible CocoaPods compatible We are… # Box Swift SDK GENERATED [](http://opensource.box.com/badges) [](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_visionOS_Linux-yellowgreen?style=flat-square) [](https://coveralls.io/github/box/box-swift-sdk-gen?branch=main) [](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square) [](https://github.com/Carthage/Carthage) [](https://cocoapods.org/pods/BoxSdkGen) We are excited to introduce the latest generation (currently in Beta) of Box Swift SDK Gen, designed to elevate the developer experience and streamline your integration with the Box Content Cloud. With this SDK, you’ll have access to: 1. Full API Support: The new generation of Box SDKs empowers developers with complete coverage of the Box API ecosystem. You can now access all the latest features and functionalities offered by Box, allowing you to build even more sophisticated and feature-rich applications. 2. Rapid API Updates: Say goodbye to waiting for new Box APIs to be incorporated into the SDK. With our new auto-generation development approach, we can now add new Box APIs to the SDK at a much faster pace (in a matter of days). This means you can leverage the most up-to-date features in your applications without delay. 3. Embedded Documentation: We understand that easy access to information is crucial for developers. With our new approach, we have included comprehensive documentation for all objects and parameters directly in the source code of the SDK. This means you no longer need to look up this information on the developer portal, saving you time and streamlining your development process. 4. Enhanced Convenience Methods: Our commitment to enhancing your development experience continues with the introduction of convenience methods. These methods cover various aspects such as chunk uploads, classification, and much more. 5. Seamless Start: The new SDKs integrate essential functionalities like authentication, automatic retries with exponential backoff, exception handling, request cancellation, and type checking, enabling you to focus solely on your application's business logic. Embrace the new generation of Box SDKs and unlock the full potential of the Box Content Cloud. # Table of contents - [Box Swift SDK GENERATED](#box-swift-sdk-generated) - [Table of contents](#table-of-contents) [Installing](#installing) - [Swift Package Manager](#swift-package-manager) - [Carthage](#carthage) - [CocoaPods](#cocoapods) [Getting Started](#getting-started) [Integration Tests](#integration-tests) [Running integration tests locally](#running-integration-tests-locally) - [Create Platform Application](#create-custom-application) - [Export configuration](#export-configuration) - [Running tests](#running-tests) [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) [Copyright and License](#copyright-and-license) # Installing ## Swift Package Manager The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies. To add a dependency to your Xcode project, click on Xcode project file on `Packages Dependencies` and click on the plus icon to add a package. Then enter the following repository url [https://github.com/box/box-swift-sdk-gen.git](https://github.com/box/box-swift-sdk-gen.git) and click next. Alternatively you can add a dependency to the dependencies value of your Package.swift. For detailed instructions, please see the [official documentation for SPM](https://www.swift.org/package-manager/). ## Carthage Carthage is a decentralized dependency manager which builds your dependencies and provides you with binary frameworks. To add a dependency to `BoxSdkGen`, you need to add the following line to your `Cartfile` : ``` git "https://github.com/box/box-swift-sdk-gen.git" ``` Then run: ``` carthage bootstrap --use-xcframeworks ``` And finally drag the built `xcframework` from Carthage/Build into your project. For more detailed instructions, please see the [official documentation for Carthage](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application). ## CocoaPods CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. To start using `BoxSdkGen` with CocoaPods, you need to add `BoxSdkGen` dependency to your `Podfile`: ``` pod 'BoxSdkGen' ``` Then run the following command in your project directory: ``` $ pod install ``` Now open your [project].xcworkspace and build. For more detailed instructions, please see the [official documentation for Cocoapods](https://guides.cocoapods.org/using/using-cocoapods.html). # Getting Started To get started with the SDK, get a Developer Token from the Configuration page of your app in the Box Developer Console. You can use this token to make test calls for your own Box account. The SDK provides a `BoxDeveloperTokenAuth` class, which allows you to authenticate using your Developer Token. Use instance of `BoxDeveloperTokenAuth` to initialize `BoxClient` object. Using `BoxClient` object you can access managers, which allow you to perform some operations on your Box account. The example below demonstrates how to authenticate with Developer Token and print names of all items inside a root folder. ``` import BoxSdkGen let auth = BoxDeveloperTokenAuth(token: "DEVELOPER_TOKEN_GOES_HERE") let client = BoxClient(auth: auth) let items = try await client.folders.getFolderItems(folderId: "0") if let entries = items.entries { for entry in entries { switch entry { case let .fileMini(file): print("file \(file.name!) [\(file.id)]") case let .folderMini(folder): print("folder \(folder.name!) [\(folder.id)]") case let .webLinkMini(webLink): print("webLink \(webLink.name!) [\(webLink.id)]") } } } ``` The usage docs that show how to make calls to the Box API with the SDK can be found [here](https://github.com/box/box-swift-sdk-gen/tree/main/docs). We recommend, familiarizing yourself with the remaining [authentication methods](https://github.com/box/box-swift-sdk-gen/tree/main/docs/Authentication.md), [uploading files](https://github.com/box/box-swift-sdk-gen/tree/main/docs/Uploads.md) and [downloading files](https://github.com/box/box-swift-sdk-gen/tree/main/docs/Downloads.md). # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created in the Box Developer Console with `Server Authentication (Client Credentials Grant)` selected as authentication method. Once created you can edit properties of the application: - In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. - In section `Advanced Features` enable `Make API calls using the as-user header` and `Generate user access tokens`. Now select `Authorization` and submit application to be reviewed by account admin. ### Export configuration To run integration tests, you need several environment variables specifying your account and the Box application you've created. 1. Set the `CLIENT_ID` environment variable to its corresponding value from the `Configuration` tab in the section `OAuth 2.0 Credentials` of your application. 2. Set the `CLIENT_SECRET` environment variable to its corresponding value from the `Configuration` tab in the section `OAuth 2.0 Credentials` of your application. 3. Set the `ENTERPRISE_ID` environment variable to its corresponding value from the `General Settings` tab the section `App Info` of your application. 4. Set the `USER_ID` environment variable to its corresponding value from the `General Settings` tab the section `App Info` of your application. 5. Set the `BOX_FILE_REQUEST_ID` environment variable to the ID of file request already created in the user account, `BOX_EXTERNAL_USER_EMAIL` with email of free external user which not belongs to any enterprise. 6. Set the `WORKFLOW_FOLDER_ID` environment variable to the ID of the Relay workflow that deletes the file that triggered the workflow. The workflow should have a manual start to be able to start it from the API. 7. Set environment variable: `APP_ITEM_ASSOCIATION_FILE_ID` to the ID of the file with associated app item and `APP_ITEM_ASSOCIATION_FOLDER_ID` to the ID of the folder with associated app item. 8. Set environment variable: `APP_ITEM_SHARED_LINK` to the shared link associated with app item. 9. Set environment variable: `SLACK_AUTOMATION_USER_ID` to the ID of the user responsible for the Slack automation. 10. Set environment variable: `SLACK_ORG_ID` to the ID of the Slack organization. 11. Set environment variable: `SLACK_PARTNER_ITEM_ID` to the ID of the Slack partner item. ### Running tests To run integration tests locally: 1. `swift test` # Questions, Bugs, and Feature Requests? Need to contact us directly? Browse the issues tickets! Or, if that doesn't work, file a new one and we will get back to you. If you have general questions about the Box API, you can post to the [Box Developer Forum](https://forum.box.com/). # Copyright and License Copyright 2023 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Migration Guide: From Box iOS SDK to Box Swift SDK Introduction Installation Swift Package Manager Carthage Highlighting the Key Differences… # Migration Guide: From Box iOS SDK to Box Swift SDK - [Introduction](#introduction) [Installation](#installation) - [Swift Package Manager](#swift-package-manager) - [Carthage](#carthage) [Highlighting the Key Differences](#highlighting-the-key-differences) - [Async await support](#async-await-support) - [Consistent method signature](#consistent-method-signature) [Diving into Authentication](#diving-into-authentication) - [Developer Token](#developer-token) [Client Credentials Grant](#client-credentials-grant) - [Service Account Token Acquisition](#service-account-token-acquisition) - [User Token Acquisition](#user-token-acquisition) - [Smooth Switching between Service Account and User](#smooth-switching-between-service-account-and-user) [OAuth 2.0 Authentication](#oauth-20-authentication) - [Built-in flow](#built-in-flow) [Manual flow](#manual-flow) - [Get Authorization URL](#get-authorization-url) - [Authentication](#authentication) [Customizable Token Storage](#customizable-token-storage) [Downscoping Tokens](#downscoping-tokens) [Revoking Tokens](#revoking-tokens) ## Introduction Welcome to the `Box Swift SDK`, the pinnacle of Box's SDK evolution tailored for developers eager to integrate with the Box API using Swift. This next-generation toolkit is meticulously crafted with contemporary development practices, ensuring an unparalleled, seamless experience. While the `Box iOS SDK` served its purpose well, the `Box Swift SDK` elevates the experience to new heights. One of its standout features is its auto-generation directly from the Open API Specification. This guarantees that developers are always equipped with the latest Box API features, eliminating any lag or discrepancies. This guide is your compass, offering insights and directions for a smooth migration from the legacy `Box iOS SDK` to the state-of-the-art `Box Swift SDK`. As we journey through, we'll spotlight the key differences, enhanced functionalities, and the myriad benefits that await. For those who wish to delve deeper into the intricacies and advantages of the new SDK, the [official README](https://github.com/box/box-swift-sdk-gen/blob/main/README.md) is a treasure trove of information. ## Installation ### Swift Package Manager [The Swift Package Manager](https://www.swift.org/package-manager/) is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies. To add a dependency to your Xcode project, click on Xcode project file on `Packages Dependencies` and click on the plus icon to add a package. Then enter the following repository url [https://github.com/box/box-swift-sdk-gen.git](https://github.com/box/box-swift-sdk-gen.git) and click next. Alternatively you can add a dependency to the dependencies value of your `Package.swift`: ``` dependencies: [ .package(url: "https://github.com/box/box-swift-sdk-gen.git", from: "0.1.0") ] ``` ### Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager which builds your dependencies and provides you with binary frameworks. To add a dependency to `Box Swift SDK`, you need to add the following line to your `Cartfile` : ``` git "https://github.com/box/box-swift-sdk-gen.git" ``` Then run: ``` carthage bootstrap --use-xcframeworks ``` And finally drag the built `xcframework` from Carthage/Build into your project. ## Highlighting the Key Differences ### Async await support One of the main changes between the new and old SDK is the addition of async/await support for all API methods. **Legacy (`Box iOS SDK`):** In the older SDK, API interactions allowed for passing `callback` as the last argument: ``` client.users.getCurrent(fields: ["name", "login"]) { result in guard case let .success(user) = result else { print("Error getting user information") return } // now you can safely access to user object print("Authenticated as \(user.name), with login \(user.login)") } ``` **Modern (`Box Swift SDK`):** The new SDK ensures consistent use of async/await throughout the entire SDK, making asynchronous code more readable and easier to understand compared to nested callback functions. Let's compare an example of a similar method as above, but using added support for async/await: ``` let user = try await client.users.getUserMe() ``` ### Consistent method signature To facilitate easier work with the new SDK, we have changed the API method signatures to be consistent and unified. **Legacy (`Box iOS SDK`):** In the old SDK, API methods had numerous parameters, requiring access to all necessary data when calling a particular method. ``` public func update( fileId: String, name: String? = nil, description: String? = nil, parentId: String? = nil, sharedLink: NullableParameter<SharedLinkData>? = nil, tags: [String]? = nil, collections: [String]? = nil, lock: NullableParameter<LockData>? = nil, dispositionAt: Date? = nil, ifMatch: String? = nil, fields: [String]? = nil, completion: @escaping Callback<File> ) ``` **Modern (`Box Swift SDK`):** In the new SDK, we have adopted an approach of aggregating parameters into types based on their nature (path, body, query, headers). This can be seen in the example corresponding to the above: ``` public func updateFileById( fileId: String, requestBody: UpdateFileByIdRequestBodyArg = UpdateFileByIdRequestBodyArg(), queryParams: UpdateFileByIdQueryParamsArg = UpdateFileByIdQueryParamsArg(), headers: UpdateFileByIdHeadersArg = UpdateFileByIdHeadersArg() ) async throws -> FileFull ``` According to the convention, if an API endpoint requires a parameter placed in the URL path, it will appear at the beginning of our method, such as `fileId` in this case. When a request allows for a body, as in `POST` or `PUT`, the method includes a parameter named `requestBody`. Following that, the method signature may include the `queryParams` parameter, followed by `headers`. The types of parameters `requestBody`, `queryParams`, and `headers` are specific to each endpoint and, in their definition, encompass all fields allowed by the API. It's worth noting here that when all fields of a particular type are optional, the entire parameter becomes optional as well. This allows us to pass only the parameters we actually want to provide when calling a given method, without the risk of not providing a sufficient number of parameters. ## Diving into Authentication Authentication is a crucial aspect of any SDK. Let's delve into the authentication methods supported by both SDKs and understand the enhancements in the new version: ### Developer Token The Developer Token remains a straightforward method for authentication: **Legacy (`Box iOS SDK`):** ``` let client = BoxSDK.getClient(token: "YOUR_DEVELOPER_TOKEN") ``` **Modern (`Box Swift SDK`):** ``` let auth = BoxDeveloperTokenAuth(token: "YOUR_DEVELOPER_TOKEN") let client = BoxClient(auth: auth) ``` ### Client Credentials Grant The Client Credentials Grant method is a popular choice for many developers. Let's see how it's been changed: #### Service Account Token Acquisition **Legacy (`Box iOS SDK`):** ``` let sdk = BoxSDK(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET") let client = try await sdk.getCCGClientForAccountService(enterpriseId: "YOUR_ENTERPRISE_ID") ``` **Modern (`Box Swift SDK`):** ``` let config = CCGConfig( clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", enterpriseId: "YOUR_ENTERPRISE_ID" ) let auth = BoxCCGAuth(config: config) let client = BoxClient(auth: auth) ``` #### User Token Acquisition **Legacy (`Box iOS SDK`):** ``` let sdk = BoxSDK(clientId: "YOUR_CLIENT_SECRET", clientSecret: "YOUR_CLIENT_SECRET") let client = try await sdk.getCCGClientForUser(userId: "YOUR_USER_ID") ``` **Modern (`Box Swift SDK`):** ``` let config = CCGConfig( clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", userId: "YOUR_USER_ID" ) let auth = BoxCCGAuth(config); let client = BoxClient(auth: auth) ``` #### Smooth Switching between Service Account and User Transitioning between account types is now more intuitive: **Modern (`Box Swift SDK`):** ``` auth.asEnterprise(enterpriseId: "YOUR_ENTERPRISE_ID") ``` ### OAuth 2.0 Authentication Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. #### Built-in flow Both the old SDK and the new one provide a built-in flow for opening a secure web view, into which the user enters their Box login credentials. However, let's examine the differences between them. **Legacy (`Box iOS SDK`):** ``` let sdk = BoxSDK(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", callbackURL: "YOUR_REDIRECT_URL") let client = try await sdk.getOAuth2Client(tokenStore: KeychainTokenStore()) ``` **Modern (`Box Swift SDK`):** ``` let config = OAuthConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", tokenStorage: KeychainTokenStorage()) let oauth = BoxOAuth(config: config) try await oauth.runLoginFlow(options: AuthorizeUrlParams(redirectUri: "YOUR_REDIRECT_URL"), context: self) let client = BoxClient(auth: oauth) ``` #### Manual flow As an alternative to the built-in flow, where everything is done automatically, you can opt for the manual one, which has been added only to the new `Box Swift SDK`. ##### Get Authorization URL First, you need to create the authorization URL based on the provided client data and redirect the user to this URL. ``` let config = OAuthConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET") let authorizationUrl = auth.getAuthorizeUrl() ``` ##### Authentication After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirectUri` which will contain an authorization code. This code can then be used along with your client ID and client secret to establish an API connection. You need to provide the authorization code to the SDK to obtain an access token, then you can use the SDK as usual. ``` auth.getTokensAuthorizationCodeGrant(authorizationCode: "YOUR_AUTHORIZATION_CODE") let client = BoxClient(auth: oauth) ``` ### Customizable Token Storage Both the old and the new SDK allow for the creation of a custom Token Storage, which can be provided when creating an instance of the `AuthConfig` class. However, let's examine the differences in their implementation. **Legacy (`Box iOS SDK`):** In the old SDK, the custom token storage must conform to the `TokenStore` protocol, with the API of the methods being callback-based: ``` public class MyCustomTokenStore: TokenStore { public func read(completion: @escaping (Result<TokenInfo, Error>) -> Void) { // YOUR IMPLEMENTATION GOES HERE } public func write(tokenInfo: TokenInfo, completion: @escaping (Result<Void, Error>) -> Void) { // YOUR IMPLEMENTATION GOES HERE } public func clear(completion: @escaping (Result<Void, Error>) -> Void) { // YOUR IMPLEMENTATION GOES HERE } } ``` **Modern (`Box Swift SDK`):** In the new SDK, a custom token storage must conform to the `TokenStore`, where the API is async/await: ``` public class MyCustomTokenStore: TokenStorage { public func store(token: AccessToken) async throws { // YOUR IMPLEMENTATION GOES HERE } public func get() async throws -> AccessToken? { // YOUR IMPLEMENTATION GOES HERE } public func clear() async throws { // YOUR IMPLEMENTATION GOES HERE } } let tokenStorage = MyCustomTokenStore(); let config = OAuthConfig(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", tokenStorage: tokenStorage); ``` ### Downscoping Tokens Downscoping is a way to exchange an existing Access Token for a new one that is more restricted. Let's see how it's been changed: **Legacy (`Box iOS SDK`):** ``` client.exchangeToken(scope: ["item_preview"], resource: "https://api.box.com/2.0/files/123456789") { result in guard case let .success(tokenInfo) = result else { print("Error exchanging tokens") return } // tokenInfo contains the downscoped accessToken print("Got new access token: \(tokenInfo.accessToken)") } ``` **Modern (`Box Swift SDK`):** In the `Box Swift SDK`, downscoping is available only for OAuth and CCG authentication. Therefore, to downscope a token, we need to call the `downscopeToken` method directly on an instance of the `BoxOAuth` or `BoxCCGAuth` class, and not on the client instance as was the case in the old SDK. ``` let accessToken: AccessToken = try await auth.downscopeToken(scopes: ["item_preview"], resource: "https://api.box.com/2.0/files/123456789") ``` ### Revoking Tokens **Legacy (`Box iOS SDK`):** ``` client.destroy() { result in guard case .success = result else { print("Tokens could not be revoked!") } print("Tokens were successfully revoked") } ``` **Modern (`Box Swift SDK`):** Similarly to downscoping, revoke is available only for OAuth and CCG authentication. ``` try await auth.revokeToken() ``` --- ## Untitled *Type: page* Authentication Authentication Authentication methods Developer Token JWT Auth Authenticate Enterprise Authenticate user Client Credentials… # Authentication - [Authentication](#authentication) [Authentication methods](#authentication-methods) - [Developer Token](#developer-token) [JWT Auth](#jwt-auth) - [Authenticate Enterprise](#authenticate-enterprise) - [Authenticate user](#authenticate-user) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) - [Switching between Service Account and User](#switching-between-service-account-and-user) [OAuth 2.0 Auth](#oauth-20-auth) - [Authentication with OAuth2](#authentication-with-oauth2) - [Injecting existing token into BoxOAuth](#injecting-existing-token-into-boxoauth) [Retrieve current access token](#retrieve-current-access-token) [Refresh access token](#refresh-access-token) [Revoke token](#revoke-token) [Downscope token](#downscope-token) [Token storage](#token-storage) - [In-memory token storage](#in-memory-token-storage) - [Custom storage](#custom-storage) # Authentication methods ## Developer Token The fastest way to get started using the API is with developer token. A developer token is simply a short-lived access token that cannot be refreshed and can only be used with your own account. Therefore, they're only useful for testing an app and aren't suitable for production. You can obtain a developer token from your application's [developer console](https://app.box.com/developers/console) page. To create a `BoxClient` with a developer token, construct an `BoxDeveloperTokenAuth` object with the `token` set to the developer token and construct the client with that. ``` BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("YOUR-DEVELOPER-TOKEN"); BoxClient client = new BoxClient(auth); ``` ## JWT Auth Before using JWT Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with JWT](https://developer.box.com/guides/authentication/jwt/jwt-setup/) ### Authenticate Enterprise JWT auth allows your application to authenticate itself with the Box API for a given enterprise. By default, your application has a [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account/) that represents it and can perform API calls. The Service Account is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. If you generated your public and private keys automatically through the [Box Developer Console](https://app.box.com/developers/console), you can use the JSON file created there to configure your SDK instance and create a client to make calls as the Service Account. Call one of static `BoxJwtAuth` method: `JWTConfig.fromConfigFile("PATH_TO_CONFIG_FILE")` and pass JSON file local path or `JWTConfig.fromConfigJsonString(CONFIG_JSON_STRING)` and pass JSON config file content as string. ``` JWTConfig config = JWTConfig.fromConfigFile("src/example/config/config.json"); BoxJWTAuth auth = new BoxJWTAuth(config); BoxClient client = new BoxClient(auth); ``` Otherwise, you'll need to provide the necessary configuration fields directly to the `JWTConfig` constructor: ``` JWTConfig config = new JWTConfig.Builder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "JWT_KEY_ID", "PRIVATE_KEY", "PRIVATE_KEY_PASSWORD") .enterpriseId("123456") .build(); BoxJWTAuth auth = new BoxJWTAuth(config); BoxClient client = new BoxClient(auth); ``` ### Authenticate user App auth applications also often have associated [App Users](https://developer.box.com/guides/getting-started/user-types/app-users/), which are created and managed directly by the application — they do not have normal login credentials, and can only be accessed through the Box API by the application that created them. You may authenticate as the Service Account to provision and manage users, or as an individual app user to make calls as that user. See the [API documentation](https://developer.box.com/) for detailed instructions on how to use app auth. Clients for making calls as an App User can be created with the same JSON JWT config file generated through the [Box Developer Console](https://app.box.com/developers/console). Calling `jwtAuth.withUserSubject('USER_ID')` method will return a new auth object, which is authenticated as the user with provided id, leaving the original object unchanged. ``` JWTConfig config = JWTConfig.fromConfigFile("src/example/config/config.json"); BoxJWTAuth auth = new BoxJWTAuth(config); BoxJWTAuth userAuth = auth.withUserSubject("USER_ID"); BoxClient userClient = new BoxClient(userAuth); ``` Alternatively, clients for making calls as an App User can be created with the same `JWTConfig` constructor as in the above examples, similarly to creating a Service Account client. Simply pass the `userId` instead of `enterpriseId` when constructing the auth config instance: ``` JWTConfig config = new JWTConfig.Builder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "JWT_KEY_ID", "PRIVATE_KEY", "PRIVATE_KEY_PASSWORD") .userId("123456") .build(); BoxJWTAuth auth = new BoxJWTAuth(config); BoxClient client = new BoxClient(auth); ``` ## Client Credentials Grant Before using Client Credentials Grant Auth make sure you set up correctly your Box platform app. The guide with all required steps can be found here: [Setup with Client Credentials Grant](https://developer.box.com/guides/authentication/client-credentials/client-credentials-setup/) Client Credentials Grant Auth method allows you to obtain an access token by having client credentials and secret with enterprise or user ID, which allows you to work using service or user account. You can use `CCGAuth` to initialize a client object the same way as for other authentication types: ``` CCGConfig config = new CCGConfig.Builder("YOUR_CLIENT", "YOUR_CLIENT_SECRET") .userId("USER_ID") .build(); BoxCCGAuth auth = new BoxCCGAuth(config); BoxClient client = new BoxClient(auth); UserFull user = client.users.getUserMe(); System.out.println(user.getName()); ``` Obtained token is valid for specified amount of time, it will be refreshed automatically by default. ### Obtaining Service Account token The [Service Account](https://developer.box.com/guides/getting-started/user-types/service-account//) is separate from the Box accounts of the application developer and the enterprise admin of any enterprise that has authorized the app — files stored in that account are not accessible in any other account by default, and vice versa. To obtain service account you will have to provide enterprise ID with client id and secret: ``` CCGConfig config = new CCGConfig.Builder("YOUR_CLIENT", "YOUR_CLIENT_SECRET") .enterpriseId("ENTERPRISE_ID") .build(); BoxCCGAuth auth = new BoxCCGAuth(config); BoxClient client = new BoxClient(auth); ``` ### Obtaining User token In order to enable obtaining user token you have to go to your application configuration that can be found [here](https://app.box.com/developers/console). In `Configuration` tab, in section `Advanced Features` select `Generate user access tokens`. Do not forget to re-authorize application if it was already authorized. To obtain user account you will have to provide user ID with client id and secret. ``` CCGConfig config = new CCGConfig.Builder("YOUR_CLIENT", "YOUR_CLIENT_SECRET") .userId("USER_ID") .build(); BoxCCGAuth auth = new BoxCCGAuth(config); BoxClient client = new BoxClient(auth); ``` ### Switching between Service Account and User You can easily switch to be authenticated as a Service Account or as a User. To create a new auth object authenticated as Service Account you can call: ``` BoxCCGAuth enterpriseAuth = auth.withEnterpriseSubject("ENTERPRISE_ID"); BoxClient enterpriseClient = new BoxClient(enterpriseAuth); ``` To authenticate with user subject call: ``` BoxCCGAuth userAuth = auth.withUserSubject("USER_ID"); BoxClient userClient = new BoxClient(userAuth); ``` The new token will be automatically fetched with a next API call. ## OAuth 2.0 Auth ### Authentication with OAuth2 If your application needs to integrate with existing Box users who will provide their login credentials to grant your application access to their account, you will need to go through the standard OAuth2 login flow. A detailed guide for this process is available in the [Authentication with OAuth API documentation](https://developer.box.com/en/guides/authentication/oauth2/). Using an auth code is the most common way of authenticating with the Box API for existing Box users, to integrate with their accounts. Your application must provide a way for the user to login to Box (usually with a browser or web view) in order to obtain an auth code. ``` BoxOAuth oauth = new OAuthConfig("CLIENT_ID", "CLIENT_SECRET"); String authorizationUrl = auoauthth.getAuthorizeUrl(); ``` After a user logs in and grants your application access to their Box account, they will be redirected to your application's `redirect_uri` which will contain an auth code. This auth code can then be used along with your client ID and client secret to establish an API connection. You need to provide the auth code to the SDK to obtain an access token. Calling `oauth.getTokensAuthorizationCodeGrant('code')` will exchange the auth code for an access token and save it in the `BoxOAuth` token storage. The SDK will automatically refresh the token when needed. All you need to do is create a client object with the `BoxOAuth` object and start making API calls. ``` auth.retrieveToken(); ``` # Refresh access token Access tokens are short-lived and need to be refreshed periodically. The SDK will automatically refresh the token when needed. If you want to manually refresh the token, you can use the following code: ``` auth.refreshToken(); ``` # Revoke token Access tokens for a client can be revoked when needed. This call invalidates old token. For BoxCcgAuth and BoxJwtAuth you can still reuse the `auth` object to retrieve a new token. If you make any new call after revoking the token, a new token will be automatically retrieved. For BoxOAuth it would be necessary to manually go through the authentication process again. For BoxDeveloperTokenAuth, it is necessary to provide a DeveloperTokenConfig during initialization, containing the client ID and client secret. To revoke current client's tokens in the storage use the following code: ``` auth.revokeToken(); // client's tokens have been revoked ``` # Downscope token You can exchange a client's access token for one with a lower scope, in order to restrict the permissions for a child client or to pass to a less secure location (e.g. a browser-based app). A downscoped token does not include a refresh token. In such a scenario, to obtain a new downscoped token, refresh the original token and utilize the newly acquired token to obtain the downscoped token. More information about downscoping tokens can be found [here](https://developer.box.com/guides/authentication/tokens/downscope/). If you want to learn more about available scopes please go [here](https://developer.box.com/guides/api-calls/permissions-and-errors/scopes/#scopes-for-downscoping). For example to get a new token with only `item_preview` scope, restricted to a single file, suitable for the [Content Preview UI Element](https://developer.box.com/en/guides/embed/ui-elements/preview/) you can use the following code. You can also initialize `BoxDeveloperTokenAuth` with the retrieved access token and use it to create a new Client. ``` String resource = "https://api.box.com/2.0/files/123456789"; List<String> scopes = List.of("item_preview"); AccessToken downscopedToken = auth.downscopeToken(scopes, resource, null, null); BoxDeveloperTokenAuth downscopedAuth = new BoxDeveloperTokenAuth(downscopedToken.getAccessToken()); BoxClient downscopedClient = new BoxClient(downscopedAuth); ``` # Token storage ## In-memory token storage By default, the SDK stores the access token in volatile memory. When rerunning your application, the access token won't be reused from the previous run; a new token has to be obtained again. To use in-memory token storage, you don't need to do anything more than create an Auth class using AuthConfig, for example, for OAuth: ``` OAuthConfig config = new OAuthConfig("CLIENT_ID", "CLIENT_SECRET"); BoxOAuth auth = new BoxOAuth(config); ``` ## Custom storage You can also provide a custom token storage class. All you need to do is create a class that implements `TokenStorage` interface and pass an instance of your class to the AuthConfig constructor. ``` TokenStorage customTokenStorage = new TokenStorage() { @Override public void store(AccessToken accessToken) { // Store the access token } @Override public AccessToken get() { // Retrieve the access token return null; } @Override public void clear() { // Clear the access token } }; OAuthConfig config = new OAuthConfig.Builder("CLIENT_ID", "CLIENT_SECRET") .tokenStorage(customTokenStorage) .build(); BoxOAuth auth = new BoxOAuth(config); ``` --- ## Untitled *Type: page* Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers… # Client This is the central entrypoint for all SDK interaction. The BoxClient houses all the API endpoints divided across resource managers. - [Client](#client) [Make custom HTTP request](#make-custom-http-request) - [JSON request](#json-request) - [Multi-part request](#multi-part-request) - [Binary response](#binary-response) [Additional headers](#additional-headers) - [As-User header](#as-user-header) - [Suppress notifications](#suppress-notifications) - [Custom headers](#custom-headers) [Custom Base URLs](#custom-base-urls) [Interceptors](#interceptors) # Make custom HTTP request You can make custom HTTP requests using the `client.makeRequest()` method. This method allows you to make any HTTP request to the Box API. It will automatically use authentication and network configuration settings from the client. The method accepts a `FetchOptions` object as an argument and returns a `FetchResponse` object. ## JSON request The following example demonstrates how to make a custom POST request to create a new folder in the root folder. ``` FetchOptions fetchOptions = new FetchOptions.Builder("https://api.box.com/2.0/users/me", "GET") .params(new HashMap<>() {{ put("fields", "name"); }}) .build(); FetchResponse response = client.makeRequest(fetchOptions); System.out.println("Status code: " + response.getStatus()); System.out.println("Response body: " + response.getContent()); ``` ## Multi-part request The following example demonstrates how to make a custom multipart request that uploads a file to a folder. ``` List<MultipartItem> multipartItems = List.of( new MultipartItem.Builder("attributes") .data(JsonManager.serialize("{\"name\": \"newFileName\", \"parent\": { \"id\": \"0\" }}")) .build(), new MultipartItem.Builder("file") .fileStream(new FileInputStream(new File("file.txt"))) .build() ); FetchOptions fetchOptions = new FetchOptions.Builder("https://upload.box.com/api/2.0/files/content", "POST") .contentType("multipart/form-data") .multipartData(multipartItems) .build(); FetchResponse response = client.makeRequest(fetchOptions); System.out.println("Status code: " + response.getStatus()); System.out.println("Response body: " + response.getContent()); ``` ## Binary response The following example demonstrates how to make a custom request that expects a binary response. It is required to specify the `responseFormat` parameter in the `FetchOptions` object to "binary". ``` FetchOptions fetchOptions = new FetchOptions.Builder("https://upload.box.com/api/2.0/files/12345/content", "GET") .responseFormat(ResponseFormat.BINARY) .build(); FetchResponse response = client.makeRequest(fetchOptions); System.out.println("Status code: " + response.getStatus()); System.out.println("Response body: " + response.getContent()); ``` # Additional headers BoxClient provides a convenient methods, which allow passing additional headers, which will be included in every API call made by the client. ## As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an As-User: USER-ID header. For more details see the [documentation on As-User](https://developer.box.com/en/guides/authentication/oauth2/as-user/). The following example assume that the client has been instantiated with an access token belonging to an admin-level user or Service Account with appropriate privileges to make As-User calls. Calling the `client.withAsUserHeader()` method creates a new client to impersonate user with the provided ID. All calls made with the new client will be made in context of the impersonated user, leaving the original client unmodified. ``` BoxClient userClient = client.withAsUserHeader('1234567'); ``` ## Suppress notifications If you are making administrative API calls (that is, your application has “Manage an Enterprise” scope, and the user signing in is a co-admin with the correct "Edit settings for your company" permission) then you can suppress both email and webhook notifications. This can be used, for example, for a virus-scanning tool to download copies of everyone’s files in an enterprise, without every collaborator on the file getting an email. All actions will still appear in users' updates feed and audit logs. **Note:** This functionality is only available for approved applications. Calling the `client.withSuppressedNotifications()` method creates a new client. For all calls made with the new client the notifications will be suppressed. ``` BoxClient newClient = client.withSuppressedNotifications(); ``` ## Custom headers You can also specify the custom set of headers, which will be included in every API call made by client. Calling the `client.withExtraHeaders()` method creates a new client, leaving the original client unmodified. ``` BoxClient newClient = client.withExtraHeaders(new HashMap<>() {{ put("X-My-Header", "124"); }}); ``` # Custom Base URLs You can also specify the custom base URLs, which will be used for API calls made by client. Calling the `client.withCustomBaseUrls()` method creates a new client, leaving the original client unmodified. ``` BaseUrls baseUrls = new BaseUrls.Builder() .baseUrl("https://new-base-url.com") .uploadUrl("https://my-company-upload-url.com") .oauth2Url("https://my-company.com/oauth2") .build(); BoxClient clientWithCustomBaseUrl = client.withCustomBaseUrls(baseUrls); ``` # Interceptors You can specify custom interceptors - methods that will be called just before making a request and right after receiving a response from the server. Using these function allows you to modify the request payload and response. Interceptor interface accepts two methods with the following signatures: ``` FetchOptions beforeRequest(FetchOptions fetchOptions) FetchResponse afterRequest(FetchResponse fetchResponse) ``` You can apply more than one interceptor to the client by passing a list of interceptors to apply. Calling the `client.withInterceptors()` method creates a new client, leaving the original client unmodified. ``` List<Interceptor> interceptors = new ArrayList<>() { { add(new Interceptor() { @Override public FetchOptions beforeRequest(FetchOptions fetchOptions) { return fetchOptions; } @Override public FetchResponse afterRequest(FetchResponse fetchResponse) { return fetchResponse; } }); } }; BoxClient clientWithInterceptor = client.withInterceptors(interceptors); ``` --- ## Untitled *Type: page* Configuration Configuration Max retry attempts Custom retry strategy Max retry attempts The default maximum number of retries in case of… # Configuration [Configuration](#configuration) - [Max retry attempts](#max-retry-attempts) - [Custom retry strategy](#custom-retry-strategy) ## Max retry attempts The default maximum number of retries in case of failed API call is 5. To change this number you should initialize `BoxRetryStrategy` with the new value and pass it to `NetworkSession`. ``` BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); NetworkSession session = new NetworkSession.Builder() .retryStrategy(new BoxRetryStrategy.Builder().maxAttempts(3).build()) .build(); BoxClient client = new BoxClient.Builder(auth) .networkSession(session) .build(); ``` ## Custom retry strategy You can also implement your own retry strategy by subclassing `RetryStrategy` and overriding `shouldRetry` and `retryAfter` methods. This example shows how to set custom strategy that retries on 5xx status codes and waits 1 second between retries. ``` BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); RetryStrategy customRetryStrategy = new RetryStrategy() { @Override public boolean shouldRetry(FetchOptions fetchOptions, FetchResponse fetchResponse, int attemptNumber) { return fetchResponse.status >= 500; } @Override public double retryAfter(FetchOptions fetchOptions, FetchResponse fetchResponse, int attemptNumber) { return 1.0; } }; NetworkSession session = new NetworkSession.Builder() .retryStrategy(customRetryStrategy) .build(); BoxClient client = new BoxClient.Builder(auth) .networkSession(session) .build(); ``` --- ## Untitled *Type: page* Documentation High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available… # Documentation ## High-level Documentation General explanations of the available functionality and examples of how to use the SDK are available by topic: - [Ai](https://developer.box.com/2fd076d80717584cc7609bb1a8844440/ai.md) - [Aistudio](https://developer.box.com/fa2d3be0c146c06c8c58f985db6475b6/aistudio.md) - [Appitemassociations](https://developer.box.com/85856398ed7d5c853d641b74caaca122/appitemassociations.md) - [Archives](https://developer.box.com/b58b7d17d359bd844dd15016b155939c/archives.md) - [Authorization](https://developer.box.com/e7dc87f3544ce5b0fe8f08b557128d58/authorization.md) - [Avatars](https://developer.box.com/fd145549136dcb0a9e11fe6034847a1c/avatars.md) - [Chunkeduploads](https://developer.box.com/130fb5e9921cd03b0c5d839a3ca4d953/chunkeduploads.md) - [Classifications](https://developer.box.com/4ca4df76aa5144810dace8e84b0f6b45/classifications.md) - [Collaborationallowlistentries](https://developer.box.com/71bb138bfca1ea3387dfe19ac0639247/collaborationallowlistentries.md) - [Collaborationallowlistexempttargets](https://developer.box.com/572fad0c8059c8d1c36da673481d6d4b/collaborationallowlistexempttargets.md) - [Collections](https://developer.box.com/e4cfdb96dde46c847e36333380084e90/collections.md) - [Comments](https://developer.box.com/5c33921f78e20d1b81f52c4f96fc49e8/comments.md) - [Devicepinners](https://developer.box.com/997dc738393181b6bea47214a8ae6151/devicepinners.md) - [Docgen](https://developer.box.com/496e96b4e7d943dd4b5aaafd71204d89/docgen.md) - [Docgentemplate](https://developer.box.com/2205b28a3cd3e0f0f62afe664b7a5460/docgentemplate.md) - [Downloads](https://developer.box.com/fb9fc134cc1570b12c358da6344fc81c/downloads.md) - [Emailaliases](https://developer.box.com/13d5f1b719753acd7397f0226e047035/emailaliases.md) - [Events](https://developer.box.com/69a64646f74690c80bb27bc8462549ee/events.md) - [Fileclassifications](https://developer.box.com/388e0106ae9ab177124b291de3a54a06/fileclassifications.md) - [Filemetadata](https://developer.box.com/d9276a1316eea9a27a6f05e188af9a3d/filemetadata.md) - [Filerequests](https://developer.box.com/a8faeceec641bd9651cba877685f0574/filerequests.md) - [Files](https://developer.box.com/48f80c0470b95727ac28a47a0e35502f/files.md) - [Fileversionlegalholds](https://developer.box.com/8e6226fef8570d0f624c146be2b0251f/fileversionlegalholds.md) - [Fileversionretentions](https://developer.box.com/2532c854bbb48feddbf46f58874c5bc7/fileversionretentions.md) - [Fileversions](https://developer.box.com/51cf816105ab25742efa00b3f78b7309/fileversions.md) - [Filewatermarks](https://developer.box.com/f1aa57f4b9c2692a953105262df9dfc8/filewatermarks.md) - [Folderclassifications](https://developer.box.com/b705acfcd1309c02d81279143764576f/folderclassifications.md) - [Folderlocks](https://developer.box.com/e7bab8893ba0270ed64b859df253b941/folderlocks.md) - [Foldermetadata](https://developer.box.com/daa05bb98fd6df0cf3bf5cdc0b9767ea/foldermetadata.md) - [Folders](https://developer.box.com/b037c3ca8b8a64aaa54ba229e37bbf46/folders.md) - [Folderwatermarks](https://developer.box.com/8b89b08d0a164d2ab84c7fad7052105e/folderwatermarks.md) - [Groups](https://developer.box.com/5340618d953cb195925cc49a49fb3cae/groups.md) - [Hubcollaborations](https://developer.box.com/2387680bf34201481becb964cfe6c9c7/hubcollaborations.md) - [Hubitems](https://developer.box.com/e53c1af6db0691378acdf4518e2a9030/hubitems.md) - [Hubs](https://developer.box.com/e035f335e69a479c810fa1b9c3fdcc23/hubs.md) - [Integrationmappings](https://developer.box.com/d3608783843bf3ab3e123a86329d313d/integrationmappings.md) - [Invites](https://developer.box.com/be73744888a25b129f1d7825a7e3dfc9/invites.md) - [Legalholdpolicies](https://developer.box.com/520eb3d80bc63080848a7dcd0bbfe46b/legalholdpolicies.md) - [Legalholdpolicyassignments](https://developer.box.com/a7ea003be24c1102f3f7c395d092187c/legalholdpolicyassignments.md) - [Listcollaborations](https://developer.box.com/3c91fadbb61cf1d040da3502dfc59e04/listcollaborations.md) - [Memberships](https://developer.box.com/4ca38d921501f32d38c17646224bbf48/memberships.md) - [Metadatacascadepolicies](https://developer.box.com/c536763ae55a5653f4ecc8237931c371/metadatacascadepolicies.md) - [Metadatatemplates](https://developer.box.com/2c952b95509e7d56689d7b7c05df8ca4/metadatatemplates.md) - [Recentitems](https://developer.box.com/614ddb4bdf92189c2e2e6ae044d5b6c1/recentitems.md) - [Retentionpolicies](https://developer.box.com/256a5da6e2760654b626684b7d52207c/retentionpolicies.md) - [Retentionpolicyassignments](https://developer.box.com/f459d6ab4a4f2ff17b9e2e75308d32e1/retentionpolicyassignments.md) - [Search](https://developer.box.com/c965a74fd5e1c9f554e879ff136f1619/search.md) - [Sessiontermination](https://developer.box.com/65edb887c7d8dcd83a645b59a8c46f59/sessiontermination.md) - [Sharedlinksappitems](https://developer.box.com/d8ba79121d7f8ce2c82a07bb3f1b69cc/sharedlinksappitems.md) - [Sharedlinksfiles](https://developer.box.com/bfbc782c303925a0072caf21ee600683/sharedlinksfiles.md) - [Sharedlinksfolders](https://developer.box.com/22577ede84a66f86f549ec3f01043a05/sharedlinksfolders.md) - [Sharedlinksweblinks](https://developer.box.com/86e2ac7a5bed03ecd336b7f270a3304f/sharedlinksweblinks.md) - [Shieldinformationbarrierreports](https://developer.box.com/0364b7ccf11087c30fd01cb3d83fe5cf/shieldinformationbarrierreports.md) - [Shieldinformationbarriers](https://developer.box.com/247235b29132fa9cc0e56122442d45c9/shieldinformationbarriers.md) - [Shieldinformationbarriersegmentmembers](https://developer.box.com/88dfa1c093c9987a692145a709cc9768/shieldinformationbarriersegmentmembers.md) - [Shieldinformationbarriersegmentrestrictions](https://developer.box.com/ac0d7fa59520a072894bed726203defa/shieldinformationbarriersegmentrestrictions.md) - [Shieldinformationbarriersegments](https://developer.box.com/d416676f5bdc63073a0769713f43de48/shieldinformationbarriersegments.md) - [Shieldlists](https://developer.box.com/55f00b5f5fe4195f85b00785a0db2f6b/shieldlists.md) - [Signrequests](https://developer.box.com/e7f9e20f2e50007ab91ccc7e02f94417/signrequests.md) - [Signtemplates](https://developer.box.com/be3e240ab326283907d771b284781009/signtemplates.md) - [Skills](https://developer.box.com/f26d39ba616089c327cc6584f0ae47ca/skills.md) - [Storagepolicies](https://developer.box.com/a2712cd5a1f86fc34c74001920d32c0e/storagepolicies.md) - [Storagepolicyassignments](https://developer.box.com/fc7ddf2c255ed81e4bd713988d5ab0cd/storagepolicyassignments.md) - [Taskassignments](https://developer.box.com/d8945b755387ae48269013f7edb0fd04/taskassignments.md) - [Tasks](https://developer.box.com/8df11c3da98dc1845e65f3c5d394deaa/tasks.md) - [Termsofservices](https://developer.box.com/f5b6328dd46e8848971a39edc636f846/termsofservices.md) - [Termsofserviceuserstatuses](https://developer.box.com/cedace8955ea8386a594561065ddf445/termsofserviceuserstatuses.md) - [Transfer](https://developer.box.com/fe7c2f557e7f8d18273592244f634992/transfer.md) - [Trashedfiles](https://developer.box.com/fd902f5cf3f6ef41bf4939516f155adc/trashedfiles.md) - [Trashedfolders](https://developer.box.com/b551a1c1eb5baab5ed5431f1c0df0dd3/trashedfolders.md) - [Trasheditems](https://developer.box.com/14bb21e4093e736a1dc37e48abcde43f/trasheditems.md) - [Trashedweblinks](https://developer.box.com/3200803434a63dac4a2f5c15dca95acd/trashedweblinks.md) - [Uploads](https://developer.box.com/07cade95cf4f09fd6c250ef6a340a8fa/uploads.md) - [Usercollaborations](https://developer.box.com/f1c7eb9e8d5bee890e5a5048eb2031b3/usercollaborations.md) - [Users](https://developer.box.com/5f56c8fe4b29ea2d3f535c1b27e9d7c2/users.md) - [Webhooks](https://developer.box.com/361f9b686eb003437b76ba31889a6b30/webhooks.md) - [Weblinks](https://developer.box.com/b3c5748c2a0d9e6445fea45b7cfa99fb/weblinks.md) - [Workflows](https://developer.box.com/3c1a2bf21694518697961d88c0b0f848/workflows.md) - [Zipdownloads](https://developer.box.com/222b78060cc6ce2f6e00c7a553a06ee5/zipdownloads.md) --- ## Untitled *Type: page* AiManager Ask question Generate text Get AI agent default configuration Extract metadata (freeform) Extract metadata (structured) Ask… # AiManager - [Ask question](#ask-question) - [Generate text](#generate-text) - [Get AI agent default configuration](#get-ai-agent-default-configuration) - [Extract metadata (freeform)](#extract-metadata-freeform) - [Extract metadata (structured)](#extract-metadata-structured) ## Ask question Sends an AI request to supported LLMs and returns an answer specifically focused on the user's question given the provided context. This operation is performed by calling function `createAiAsk`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-ask/). ``` client.getAi().createAiAsk(new AiAsk.Builder(AiAskModeField.SINGLE_ITEM_QA, "which direction sun rises", Arrays.asList(new AiItemAsk.Builder(fileToAsk.getId(), AiItemAskTypeField.FILE).content("Sun rises in the East").build())).aiAgent(aiAskAgentConfig).build()) ``` ### Arguments requestBody `AiAsk` - Request body of createAiAsk method headers `CreateAiAskHeaders` - Headers of createAiAsk method ### Returns This function returns a value of type `AiResponseFull`. A successful response including the answer from the LLM.No content is available to answer the question. This is returned when the request item is a hub, but content in the hubs is not indexed. To ensure content in the hub is indexed, make sure Box AI for Hubs in the Admin Console was enabled before hub creation. ## Generate text Sends an AI request to supported Large Language Models (LLMs) and returns generated text based on the provided prompt. This operation is performed by calling function `createAiTextGen`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-text-gen/). ``` client.getAi().createAiTextGen(new AiTextGen.Builder("Parapharse the document.s", Arrays.asList(new AiTextGenItemsField.Builder(fileToAsk.getId()).type(AiTextGenItemsTypeField.FILE).content("The Earth goes around the sun. Sun rises in the East in the morning.").build())).dialogueHistory(Arrays.asList(new AiDialogueHistory.Builder().prompt("What does the earth go around?").answer("The sun").createdAt(dateTimeFromString("2021-01-01T00:00:00Z")).build(), new AiDialogueHistory.Builder().prompt("On Earth, where does the sun rise?").answer("East").createdAt(dateTimeFromString("2021-01-01T00:00:00Z")).build())).aiAgent(aiTextGenAgentConfig).build()) ``` ### Arguments requestBody `AiTextGen` - Request body of createAiTextGen method headers `CreateAiTextGenHeaders` - Headers of createAiTextGen method ### Returns This function returns a value of type `AiResponse`. A successful response including the answer from the LLM. ## Get AI agent default configuration Get the AI agent default config. This operation is performed by calling function `getAiAgentDefaultConfig`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agent-default/). ``` client.getAi().getAiAgentDefaultConfig(new GetAiAgentDefaultConfigQueryParams.Builder(GetAiAgentDefaultConfigQueryParamsModeField.ASK).language("en-US").build()) ``` ### Arguments queryParams `GetAiAgentDefaultConfigQueryParams` - Query parameters of getAiAgentDefaultConfig method headers `GetAiAgentDefaultConfigHeaders` - Headers of getAiAgentDefaultConfig method ### Returns This function returns a value of type `AiAgentAskOrAiAgentExtractOrAiAgentExtractStructuredOrAiAgentTextGen`. A successful response including the default agent configuration. This response can be one of the following four objects: - AI agent for questions - AI agent for text generation - AI agent for freeform metadata extraction - AI agent for structured metadata extraction. The response depends on the agent configuration requested in this endpoint. ## Extract metadata (freeform) Sends an AI request to supported Large Language Models (LLMs) and extracts metadata in form of key-value pairs. In this request, both the prompt and the output can be freeform. Metadata template setup before sending the request is not required. This operation is performed by calling function `createAiExtract`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract/). ``` client.getAi().createAiExtract(new AiExtract.Builder("firstName, lastName, location, yearOfBirth, company", Arrays.asList(new AiItemBase(file.getId()))).aiAgent(agentIgnoringOverridingEmbeddingsModel).build()) ``` ### Arguments requestBody `AiExtract` - Request body of createAiExtract method headers `CreateAiExtractHeaders` - Headers of createAiExtract method ### Returns This function returns a value of type `AiResponse`. A response including the answer from the LLM. ## Extract metadata (structured) Sends an AI request to supported Large Language Models (LLMs) and returns extracted metadata as a set of key-value pairs. For this request, you either need a metadata template or a list of fields you want to extract. Input is **either** a metadata template or a list of fields to ensure the structure. To learn more about creating templates, see [Creating metadata templates in the Admin Console](https://support.box.com/hc/en-us/articles/360044194033-Customizing-Metadata-Templates) or use the [metadata template API](g://metadata/templates/create). This operation is performed by calling function `createAiExtractStructured`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-extract-structured/). ``` client.getAi().createAiExtractStructured(new AiExtractStructured.Builder(Arrays.asList(new AiItemBase(file.getId()))).fields(Arrays.asList(new AiExtractStructuredFieldsField.Builder("firstName").description("Person first name").displayName("First name").prompt("What is the your first name?").type("string").build(), new AiExtractStructuredFieldsField.Builder("lastName").description("Person last name").displayName("Last name").prompt("What is the your last name?").type("string").build(), new AiExtractStructuredFieldsField.Builder("dateOfBirth").description("Person date of birth").displayName("Birth date").prompt("What is the date of your birth?").type("date").build(), new AiExtractStructuredFieldsField.Builder("age").description("Person age").displayName("Age").prompt("How old are you?").type("float").build(), new AiExtractStructuredFieldsField.Builder("hobby").description("Person hobby").displayName("Hobby").prompt("What is your hobby?").type("multiSelect").options(Arrays.asList(new AiExtractStructuredFieldsOptionsField("guitar"), new AiExtractStructuredFieldsOptionsField("books"))).build())).aiAgent(agentIgnoringOverridingEmbeddingsModel).build()) ``` ### Arguments requestBody `AiExtractStructured` - Request body of createAiExtractStructured method headers `CreateAiExtractStructuredHeaders` - Headers of createAiExtractStructured method ### Returns This function returns a value of type `AiExtractStructuredResponse`. A successful response including the answer from the LLM. --- ## Untitled *Type: page* AppItemAssociationsManager List file app item associations List folder app item associations List file app item associations This is a beta… # AppItemAssociationsManager - [List file app item associations](#list-file-app-item-associations) - [List folder app item associations](#list-folder-app-item-associations) ## List file app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the file is associated with. This includes app items associated with ancestors of the file. Assuming the context user has access to the file, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `getFileAppItemAssociations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-app-item-associations/). ``` client.getAppItemAssociations().getFileAppItemAssociations(fileId) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileAppItemAssociationsQueryParams` - Query parameters of getFileAppItemAssociations method headers `GetFileAppItemAssociationsHeaders` - Headers of getFileAppItemAssociations method ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this file, an empty collection will be returned. This list includes app items on ancestors of this File. ## List folder app item associations **This is a beta feature, which means that its availability might be limited.** Returns all app items the folder is associated with. This includes app items associated with ancestors of the folder. Assuming the context user has access to the folder, the type/ids are revealed even if the context user does not have **View** permission on the app item. This operation is performed by calling function `getFolderAppItemAssociations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-app-item-associations/). ``` client.getAppItemAssociations().getFolderAppItemAssociations(folderId) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderAppItemAssociationsQueryParams` - Query parameters of getFolderAppItemAssociations method headers `GetFolderAppItemAssociationsHeaders` - Headers of getFolderAppItemAssociations method ### Returns This function returns a value of type `AppItemAssociations`. Returns a collection of app item objects. If there are no app items on this folder an empty collection will be returned. This list includes app items on ancestors of this folder. --- ## Untitled *Type: page* ArchivesManager List archives Create archive Delete archive List archives Retrieves archives for an enterprise. This operation is performed… # ArchivesManager - [List archives](#list-archives) - [Create archive](#create-archive) - [Delete archive](#delete-archive) ## List archives Retrieves archives for an enterprise. This operation is performed by calling function `getArchivesV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-archives/). ``` client.getArchives().getArchivesV2025R0(new GetArchivesV2025R0QueryParams.Builder().limit(100L).build()) ``` ### Arguments queryParams `GetArchivesV2025R0QueryParams` - Query parameters of getArchivesV2025R0 method headers `GetArchivesV2025R0Headers` - Headers of getArchivesV2025R0 method ### Returns This function returns a value of type `ArchivesV2025R0`. Returns a list of archives in the enterprise. ## Create archive Creates an archive. This operation is performed by calling function `createArchiveV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-archives/). ``` client.getArchives().createArchiveV2025R0(new CreateArchiveV2025R0RequestBody(archiveName)) ``` ### Arguments requestBody `CreateArchiveV2025R0RequestBody` - Request body of createArchiveV2025R0 method headers `CreateArchiveV2025R0Headers` - Headers of createArchiveV2025R0 method ### Returns This function returns a value of type `ArchiveV2025R0`. Returns a new archive object. ## Delete archive Permanently deletes an archive. This operation is performed by calling function `deleteArchiveByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-archives-id/). ``` client.getArchives().deleteArchiveByIdV2025R0(archive.getId()) ``` ### Arguments archiveId `String` - The ID of the archive. Example: "982312" headers `DeleteArchiveByIdV2025R0Headers` - Headers of deleteArchiveByIdV2025R0 method ### Returns This function returns a value of type `void`. Returns an empty response when the archive has been deleted. --- ## Untitled *Type: page* AiStudioManager List AI agents Create AI agent Update AI agent Get AI agent by agent ID Delete AI agent List AI agents Lists AI agents based… # AiStudioManager - [List AI agents](#list-ai-agents) - [Create AI agent](#create-ai-agent) - [Update AI agent](#update-ai-agent) - [Get AI agent by agent ID](#get-ai-agent-by-agent-id) - [Delete AI agent](#delete-ai-agent) ## List AI agents Lists AI agents based on the provided parameters. This operation is performed by calling function `getAiAgents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents/). ``` client.getAiStudio().getAiAgents() ``` ### Arguments queryParams `GetAiAgentsQueryParams` - Query parameters of getAiAgents method headers `GetAiAgentsHeaders` - Headers of getAiAgents method ### Returns This function returns a value of type `AiMultipleAgentResponse`. A successful response including the agents list. ## Create AI agent Creates an AI agent. At least one of the following capabilities must be provided: `ask`, `text_gen`, `extract`. This operation is performed by calling function `createAiAgent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-ai-agents/). ``` client.getAiStudio().createAiAgent(new CreateAiAgent.Builder(agentName, "enabled").ask(new AiStudioAgentAsk("enabled", "desc1")).build()) ``` ### Arguments requestBody `CreateAiAgent` - Request body of createAiAgent method headers `CreateAiAgentHeaders` - Headers of createAiAgent method ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Update AI agent Updates an AI agent. This operation is performed by calling function `updateAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-ai-agents-id/). ``` client.getAiStudio().updateAiAgentById(createdAgent.getId(), new CreateAiAgent.Builder(agentName, "enabled").ask(new AiStudioAgentAsk("disabled", "desc2")).build()) ``` ### Arguments agentId `String` - The ID of the agent to update. Example: "1234" requestBody `CreateAiAgent` - Request body of updateAiAgentById method headers `UpdateAiAgentByIdHeaders` - Headers of updateAiAgentById method ### Returns This function returns a value of type `AiSingleAgentResponseFull`. Definition of created AI agent. ## Get AI agent by agent ID Gets an AI Agent using the `agent_id` parameter. This operation is performed by calling function `getAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-ai-agents-id/). ``` client.getAiStudio().getAiAgentById(createdAgent.getId(), new GetAiAgentByIdQueryParams.Builder().fields(Arrays.asList("ask")).build()) ``` ### Arguments agentId `String` - The agent id to get. Example: "1234" queryParams `GetAiAgentByIdQueryParams` - Query parameters of getAiAgentById method headers `GetAiAgentByIdHeaders` - Headers of getAiAgentById method ### Returns This function returns a value of type `AiSingleAgentResponseFull`. A successful response including the agent. ## Delete AI agent Deletes an AI agent using the provided parameters. This operation is performed by calling function `deleteAiAgentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-ai-agents-id/). ``` client.getAiStudio().deleteAiAgentById(createdAgent.getId()) ``` ### Arguments agentId `String` - The ID of the agent to delete. Example: "1234" headers `DeleteAiAgentByIdHeaders` - Headers of deleteAiAgentById method ### Returns This function returns a value of type `void`. A successful response with no content. --- ## Untitled *Type: page* AuthorizationManager Authorize user Request access token Refresh access token Revoke access token Authorize user Authorize a user by sending… # AuthorizationManager - [Authorize user](#authorize-user) - [Request access token](#request-access-token) - [Refresh access token](#refresh-access-token) - [Revoke access token](#revoke-access-token) ## Authorize user Authorize a user by sending them through the [Box](https://box.com) website and request their permission to act on their behalf. This is the first step when authenticating a user using OAuth 2.0. To request a user's authorization to use the Box APIs on their behalf you will need to send a user to the URL with this format. This operation is performed by calling function `authorizeUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-authorize/). *Currently we don't have an example for calling `authorizeUser` in integration tests* ### Arguments queryParams `AuthorizeUserQueryParams` - Query parameters of authorizeUser method headers `AuthorizeUserHeaders` - Headers of authorizeUser method ### Returns This function returns a value of type `void`. Does not return any data, but rather should be used in the browser. ## Request access token Request an Access Token using either a client-side obtained OAuth 2.0 authorization code or a server-side JWT assertion. An Access Token is a string that enables Box to verify that a request belongs to an authorized session. In the normal order of operations you will begin by requesting authentication from the [authorize](#get-authorize) endpoint and Box will send you an authorization code. You will then send this code to this endpoint to exchange it for an Access Token. The returned Access Token can then be used to to make Box API calls. This operation is performed by calling function `requestAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token/). *Currently we don't have an example for calling `requestAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2Token` - Request body of requestAccessToken method headers `RequestAccessTokenHeaders` - Headers of requestAccessToken method ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Refresh access token Refresh an Access Token using its client ID, secret, and refresh token. This operation is performed by calling function `refreshAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-token--refresh/). *Currently we don't have an example for calling `refreshAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2TokenRefreshAccessToken` - Request body of refreshAccessToken method headers `RefreshAccessTokenHeaders` - Headers of refreshAccessToken method ### Returns This function returns a value of type `AccessToken`. Returns a new Access Token that can be used to make authenticated API calls by passing along the token in a authorization header as follows `Authorization: Bearer <Token>`. ## Revoke access token Revoke an active Access Token, effectively logging a user out that has been previously authenticated. This operation is performed by calling function `revokeAccessToken`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-oauth2-revoke/). *Currently we don't have an example for calling `revokeAccessToken` in integration tests* ### Arguments requestBody `PostOAuth2Revoke` - Request body of revokeAccessToken method headers `RevokeAccessTokenHeaders` - Headers of revokeAccessToken method ### Returns This function returns a value of type `void`. Returns an empty response when the token was successfully revoked. --- ## Untitled *Type: page* ChunkedUploadsManager This is a manager for chunked uploads (allowed for files at least 20MB). Create upload session Create upload session… # ChunkedUploadsManager This is a manager for chunked uploads (allowed for files at least 20MB). - [Create upload session](#create-upload-session) - [Create upload session for existing file](#create-upload-session-for-existing-file) - [Get upload session by URL](#get-upload-session-by-url) - [Get upload session](#get-upload-session) - [Upload part of file by URL](#upload-part-of-file-by-url) - [Upload part of file](#upload-part-of-file) - [Remove upload session by URL](#remove-upload-session-by-url) - [Remove upload session](#remove-upload-session) - [List parts by URL](#list-parts-by-url) - [List parts](#list-parts) - [Commit upload session by URL](#commit-upload-session-by-url) - [Commit upload session](#commit-upload-session) - [Upload big file](#upload-big-file) ## Create upload session Creates an upload session for a new file. This operation is performed by calling function `createFileUploadSession`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions/). ``` client.getChunkedUploads().createFileUploadSession(new CreateFileUploadSessionRequestBody(parentFolderId, fileSize, fileName)) ``` ### Arguments requestBody `CreateFileUploadSessionRequestBody` - Request body of createFileUploadSession method headers `CreateFileUploadSessionHeaders` - Headers of createFileUploadSession method ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Create upload session for existing file Creates an upload session for an existing file. This operation is performed by calling function `createFileUploadSessionForExistingFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-upload-sessions/). *Currently we don't have an example for calling `createFileUploadSessionForExistingFile` in integration tests* ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CreateFileUploadSessionForExistingFileRequestBody` - Request body of createFileUploadSessionForExistingFile method headers `CreateFileUploadSessionForExistingFileHeaders` - Headers of createFileUploadSessionForExistingFile method ### Returns This function returns a value of type `UploadSession`. Returns a new upload session. ## Get upload session by URL Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `getFileUploadSessionByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` client.getChunkedUploads().getFileUploadSessionByUrl(statusUrl) ``` ### Arguments url `String` - URL of getFileUploadSessionById method headers `GetFileUploadSessionByUrlHeaders` - Headers of getFileUploadSessionById method ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Get upload session Return information about an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) endpoint. This operation is performed by calling function `getFileUploadSessionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id/). ``` client.getChunkedUploads().getFileUploadSessionById(uploadSessionId) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" headers `GetFileUploadSessionByIdHeaders` - Headers of getFileUploadSessionById method ### Returns This function returns a value of type `UploadSession`. Returns an upload session object. ## Upload part of file by URL Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `uploadFilePartByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` client.getChunkedUploads().uploadFilePartByUrl(acc.getUploadPartUrl(), generateByteStreamFromBuffer(chunkBuffer), new UploadFilePartByUrlHeaders(digest, contentRange)) ``` ### Arguments url `String` - URL of uploadFilePart method requestBody `InputStream` - Request body of uploadFilePart method headers `UploadFilePartByUrlHeaders` - Headers of uploadFilePart method ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Upload part of file Uploads a chunk of a file for an upload session. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `uploadFilePart`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-upload-sessions-id/). ``` client.getChunkedUploads().uploadFilePart(acc.getUploadSessionId(), generateByteStreamFromBuffer(chunkBuffer), new UploadFilePartHeaders(digest, contentRange)) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" requestBody `InputStream` - Request body of uploadFilePart method headers `UploadFilePartHeaders` - Headers of uploadFilePart method ### Returns This function returns a value of type `UploadedPart`. Chunk has been uploaded successfully. ## Remove upload session by URL Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `deleteFileUploadSessionByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` client.getChunkedUploads().deleteFileUploadSessionByUrl(abortUrl) ``` ### Arguments url `String` - URL of deleteFileUploadSessionById method headers `DeleteFileUploadSessionByUrlHeaders` - Headers of deleteFileUploadSessionById method ### Returns This function returns a value of type `void`. A blank response is returned if the session was successfully aborted. ## Remove upload session Abort an upload session and discard all data uploaded. This cannot be reversed. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `deleteFileUploadSessionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-upload-sessions-id/). ``` client.getChunkedUploads().deleteFileUploadSessionById(uploadSessionId) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" headers `DeleteFileUploadSessionByIdHeaders` - Headers of deleteFileUploadSessionById method ### Returns This function returns a value of type `void`. A blank response is returned if the session was successfully aborted. ## List parts by URL Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `getFileUploadSessionPartsByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` client.getChunkedUploads().getFileUploadSessionPartsByUrl(listPartsUrl) ``` ### Arguments url `String` - URL of getFileUploadSessionParts method queryParams `GetFileUploadSessionPartsByUrlQueryParams` - Query parameters of getFileUploadSessionParts method headers `GetFileUploadSessionPartsByUrlHeaders` - Headers of getFileUploadSessionParts method ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## List parts Return a list of the chunks uploaded to the upload session so far. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `getFileUploadSessionParts`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-upload-sessions-id-parts/). ``` client.getChunkedUploads().getFileUploadSessionParts(uploadSessionId) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" queryParams `GetFileUploadSessionPartsQueryParams` - Query parameters of getFileUploadSessionParts method headers `GetFileUploadSessionPartsHeaders` - Headers of getFileUploadSessionParts method ### Returns This function returns a value of type `UploadParts`. Returns a list of parts that have been uploaded. ## Commit upload session by URL Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `createFileUploadSessionCommitByUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` client.getChunkedUploads().createFileUploadSessionCommitByUrl(commitUrl, new CreateFileUploadSessionCommitByUrlRequestBody(parts), new CreateFileUploadSessionCommitByUrlHeaders(digest)) ``` ### Arguments url `String` - URL of createFileUploadSessionCommit method requestBody `CreateFileUploadSessionCommitByUrlRequestBody` - Request body of createFileUploadSessionCommit method headers `CreateFileUploadSessionCommitByUrlHeaders` - Headers of createFileUploadSessionCommit method ### Returns This function returns a value of type `Files`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Commit upload session Close an upload session and create a file from the uploaded chunks. The actual endpoint URL is returned by the [`Create upload session`](e://post-files-upload-sessions) and [`Get upload session`](e://get-files-upload-sessions-id) endpoints. This operation is performed by calling function `createFileUploadSessionCommit`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-upload-sessions-id-commit/). ``` client.getChunkedUploads().createFileUploadSessionCommit(uploadSessionId, new CreateFileUploadSessionCommitRequestBody(parts), new CreateFileUploadSessionCommitHeaders(digest)) ``` ### Arguments uploadSessionId `String` - The ID of the upload session. Example: "D5E3F7A" requestBody `CreateFileUploadSessionCommitRequestBody` - Request body of createFileUploadSessionCommit method headers `CreateFileUploadSessionCommitHeaders` - Headers of createFileUploadSessionCommit method ### Returns This function returns a value of type `Files`. Returns the file object in a list.Returns when all chunks have been uploaded but not yet processed. Inspect the upload session to get more information about the progress of processing the chunks, then retry committing the file when all chunks have processed. ## Upload big file Starts the process of chunk uploading a big file. Should return a File object representing uploaded file. This operation is performed by calling function `uploadBigFile`. ``` client.getChunkedUploads().uploadBigFile(fileByteStream, fileName, fileSize, parentFolderId) ``` ### Arguments file `InputStream` - The stream of the file to upload. fileName `String` - The name of the file, which will be used for storage in Box. fileSize `long` - The total size of the file for the chunked upload in bytes. parentFolderId `String` - The ID of the folder where the file should be uploaded. ### Returns This function returns a value of type `FileFull`. --- ## Untitled *Type: page* AvatarsManager Get user avatar Add or update user avatar Delete user avatar Get user avatar Retrieves an image of a the user's avatar. This… # AvatarsManager - [Get user avatar](#get-user-avatar) - [Add or update user avatar](#add-or-update-user-avatar) - [Delete user avatar](#delete-user-avatar) ## Get user avatar Retrieves an image of a the user's avatar. This operation is performed by calling function `getUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-avatar/). ``` client.getAvatars().getUserAvatar(user.getId()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" headers `GetUserAvatarHeaders` - Headers of getUserAvatar method ### Returns This function returns a value of type `InputStream`. When an avatar can be found for the user the image data will be returned in the body of the response. ## Add or update user avatar Adds or updates a user avatar. This operation is performed by calling function `createUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-avatar/). ``` client.getAvatars().createUserAvatar(user.getId(), new CreateUserAvatarRequestBody.Builder(decodeBase64ByteStream("iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg==")).picFileName("avatar.png").picContentType("image/png").build()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" requestBody `CreateUserAvatarRequestBody` - Request body of createUserAvatar method headers `CreateUserAvatarHeaders` - Headers of createUserAvatar method ### Returns This function returns a value of type `UserAvatar`. `ok`: Returns the `pic_urls` object with URLs to existing user avatars that were updated.`created`: Returns the `pic_urls` object with URLS to user avatars uploaded to Box with the request. ## Delete user avatar Removes an existing user avatar. You cannot reverse this operation. This operation is performed by calling function `deleteUserAvatar`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-avatar/). ``` client.getAvatars().deleteUserAvatar(user.getId()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" headers `DeleteUserAvatarHeaders` - Headers of deleteUserAvatar method ### Returns This function returns a value of type `void`. `no_content`: Removes the avatar and returns an empty response. --- ## Untitled *Type: page* CollaborationAllowlistEntriesManager List allowed collaboration domains Add domain to list of allowed collaboration domains Get allowed… # CollaborationAllowlistEntriesManager - [List allowed collaboration domains](#list-allowed-collaboration-domains) - [Add domain to list of allowed collaboration domains](#add-domain-to-list-of-allowed-collaboration-domains) - [Get allowed collaboration domain](#get-allowed-collaboration-domain) - [Remove domain from list of allowed collaboration domains](#remove-domain-from-list-of-allowed-collaboration-domains) ## List allowed collaboration domains Returns the list domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `getCollaborationWhitelistEntries`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries/). ``` client.getCollaborationAllowlistEntries().getCollaborationWhitelistEntries() ``` ### Arguments queryParams `GetCollaborationWhitelistEntriesQueryParams` - Query parameters of getCollaborationWhitelistEntries method headers `GetCollaborationWhitelistEntriesHeaders` - Headers of getCollaborationWhitelistEntries method ### Returns This function returns a value of type `CollaborationAllowlistEntries`. Returns a collection of domains that are allowed for collaboration. ## Add domain to list of allowed collaboration domains Creates a new entry in the list of allowed domains to allow collaboration for. This operation is performed by calling function `createCollaborationWhitelistEntry`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-entries/). ``` client.getCollaborationAllowlistEntries().createCollaborationWhitelistEntry(new CreateCollaborationWhitelistEntryRequestBody(domain, CreateCollaborationWhitelistEntryRequestBodyDirectionField.INBOUND)) ``` ### Arguments requestBody `CreateCollaborationWhitelistEntryRequestBody` - Request body of createCollaborationWhitelistEntry method headers `CreateCollaborationWhitelistEntryHeaders` - Headers of createCollaborationWhitelistEntry method ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns a new entry on the list of allowed domains. ## Get allowed collaboration domain Returns a domain that has been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `getCollaborationWhitelistEntryById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-entries-id/). ``` client.getCollaborationAllowlistEntries().getCollaborationWhitelistEntryById(newEntry.getId()) ``` ### Arguments collaborationWhitelistEntryId `String` - The ID of the entry in the list. Example: "213123" headers `GetCollaborationWhitelistEntryByIdHeaders` - Headers of getCollaborationWhitelistEntryById method ### Returns This function returns a value of type `CollaborationAllowlistEntry`. Returns an entry on the list of allowed domains. ## Remove domain from list of allowed collaboration domains Removes a domain from the list of domains that have been deemed safe to create collaborations for within the current enterprise. This operation is performed by calling function `deleteCollaborationWhitelistEntryById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-entries-id/). ``` client.getCollaborationAllowlistEntries().deleteCollaborationWhitelistEntryById(entry.getId()) ``` ### Arguments collaborationWhitelistEntryId `String` - The ID of the entry in the list. Example: "213123" headers `DeleteCollaborationWhitelistEntryByIdHeaders` - Headers of deleteCollaborationWhitelistEntryById method ### Returns This function returns a value of type `void`. A blank response is returned if the entry was successfully deleted. --- ## Untitled *Type: page* ClassificationsManager List all classifications Add classification Update classification Add initial classifications List all… # ClassificationsManager - [List all classifications](#list-all-classifications) - [Add classification](#add-classification) - [Update classification](#update-classification) - [Add initial classifications](#add-initial-classifications) ## List all classifications Retrieves the classification metadata template and lists all the classifications available to this enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `getClassificationTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema/). ``` client.getClassifications().getClassificationTemplate() ``` ### Arguments headers `GetClassificationTemplateHeaders` - Headers of getClassificationTemplate method ### Returns This function returns a value of type `ClassificationTemplate`. Returns the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification Adds one or more new classifications to the list of classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `addClassification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--add/). ``` client.getClassifications().addClassification(Arrays.asList(new AddClassificationRequestBody(new AddClassificationRequestBodyDataField.Builder(getUuid()).staticConfig(new AddClassificationRequestBodyDataStaticConfigField.Builder().classification(new AddClassificationRequestBodyDataStaticConfigClassificationField.Builder().classificationDefinition("Other description").colorId(4L).build()).build()).build()))) ``` ### Arguments requestBody `List<AddClassificationRequestBody>` - Request body of addClassification method headers `AddClassificationHeaders` - Headers of addClassification method ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Update classification Updates the labels and descriptions of one or more classifications available to the enterprise. This API can also be called by including the enterprise ID in the URL explicitly, for example `/metadata_templates/enterprise_12345/securityClassification-6VMVochwUWo/schema`. This operation is performed by calling function `updateClassification`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-enterprise-securityClassification-6VMVochwUWo-schema--update/). ``` client.getClassifications().updateClassification(Arrays.asList(new UpdateClassificationRequestBody(classification.getKey(), new UpdateClassificationRequestBodyDataField.Builder(updatedClassificationName).staticConfig(new UpdateClassificationRequestBodyDataStaticConfigField.Builder().classification(new UpdateClassificationRequestBodyDataStaticConfigClassificationField.Builder().classificationDefinition(updatedClassificationDescription).colorId(2L).build()).build()).build()))) ``` ### Arguments requestBody `List<UpdateClassificationRequestBody>` - Request body of updateClassification method headers `UpdateClassificationHeaders` - Headers of updateClassification method ### Returns This function returns a value of type `ClassificationTemplate`. Returns the updated `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add initial classifications When an enterprise does not yet have any classifications, this API call initializes the classification template with an initial set of classifications. If an enterprise already has a classification, the template will already exist and instead an API call should be made to add additional classifications. This operation is performed by calling function `createClassificationTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema--classifications/). *Currently we don't have an example for calling `createClassificationTemplate` in integration tests* ### Arguments requestBody `CreateClassificationTemplateRequestBody` - Request body of createClassificationTemplate method headers `CreateClassificationTemplateHeaders` - Headers of createClassificationTemplate method ### Returns This function returns a value of type `ClassificationTemplate`. Returns a new `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. --- ## Untitled *Type: page* CollaborationAllowlistExemptTargetsManager List users exempt from collaboration domain restrictions Create user exemption from collaboration… # CollaborationAllowlistExemptTargetsManager - [List users exempt from collaboration domain restrictions](#list-users-exempt-from-collaboration-domain-restrictions) - [Create user exemption from collaboration domain restrictions](#create-user-exemption-from-collaboration-domain-restrictions) - [Get user exempt from collaboration domain restrictions](#get-user-exempt-from-collaboration-domain-restrictions) - [Remove user from list of users exempt from domain restrictions](#remove-user-from-list-of-users-exempt-from-domain-restrictions) ## List users exempt from collaboration domain restrictions Returns a list of users who have been exempt from the collaboration domain restrictions. This operation is performed by calling function `getCollaborationWhitelistExemptTargets`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets/). ``` client.getCollaborationAllowlistExemptTargets().getCollaborationWhitelistExemptTargets() ``` ### Arguments queryParams `GetCollaborationWhitelistExemptTargetsQueryParams` - Query parameters of getCollaborationWhitelistExemptTargets method headers `GetCollaborationWhitelistExemptTargetsHeaders` - Headers of getCollaborationWhitelistExemptTargets method ### Returns This function returns a value of type `CollaborationAllowlistExemptTargets`. Returns a collection of user exemptions. ## Create user exemption from collaboration domain restrictions Exempts a user from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `createCollaborationWhitelistExemptTarget`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaboration-whitelist-exempt-targets/). ``` client.getCollaborationAllowlistExemptTargets().createCollaborationWhitelistExemptTarget(new CreateCollaborationWhitelistExemptTargetRequestBody(new CreateCollaborationWhitelistExemptTargetRequestBodyUserField(user.getId()))) ``` ### Arguments requestBody `CreateCollaborationWhitelistExemptTargetRequestBody` - Request body of createCollaborationWhitelistExemptTarget method headers `CreateCollaborationWhitelistExemptTargetHeaders` - Headers of createCollaborationWhitelistExemptTarget method ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns a new exemption entry. ## Get user exempt from collaboration domain restrictions Returns a users who has been exempt from the collaboration domain restrictions. This operation is performed by calling function `getCollaborationWhitelistExemptTargetById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaboration-whitelist-exempt-targets-id/). ``` client.getCollaborationAllowlistExemptTargets().getCollaborationWhitelistExemptTargetById(newExemptTarget.getId()) ``` ### Arguments collaborationWhitelistExemptTargetId `String` - The ID of the exemption to the list. Example: "984923" headers `GetCollaborationWhitelistExemptTargetByIdHeaders` - Headers of getCollaborationWhitelistExemptTargetById method ### Returns This function returns a value of type `CollaborationAllowlistExemptTarget`. Returns the user's exempted from the list of collaboration domains. ## Remove user from list of users exempt from domain restrictions Removes a user's exemption from the restrictions set out by the allowed list of domains for collaborations. This operation is performed by calling function `deleteCollaborationWhitelistExemptTargetById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaboration-whitelist-exempt-targets-id/). ``` client.getCollaborationAllowlistExemptTargets().deleteCollaborationWhitelistExemptTargetById(exemptTarget.getId()) ``` ### Arguments collaborationWhitelistExemptTargetId `String` - The ID of the exemption to the list. Example: "984923" headers `DeleteCollaborationWhitelistExemptTargetByIdHeaders` - Headers of deleteCollaborationWhitelistExemptTargetById method ### Returns This function returns a value of type `void`. A blank response is returned if the exemption was successfully deleted. --- ## Untitled *Type: page* CollectionsManager List all collections List collection items Get collection by ID List all collections Retrieves all collections for a… # CollectionsManager - [List all collections](#list-all-collections) - [List collection items](#list-collection-items) - [Get collection by ID](#get-collection-by-id) ## List all collections Retrieves all collections for a given user. Currently, only the `favorites` collection is supported. This operation is performed by calling function `getCollections`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections/). *Currently we don't have an example for calling `getCollections` in integration tests* ### Arguments queryParams `GetCollectionsQueryParams` - Query parameters of getCollections method headers `GetCollectionsHeaders` - Headers of getCollections method ### Returns This function returns a value of type `Collections`. Returns all collections for the given user. ## List collection items Retrieves the files and/or folders contained within this collection. This operation is performed by calling function `getCollectionItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id-items/). *Currently we don't have an example for calling `getCollectionItems` in integration tests* ### Arguments collectionId `String` - The ID of the collection. Example: "926489" queryParams `GetCollectionItemsQueryParams` - Query parameters of getCollectionItems method headers `GetCollectionItemsHeaders` - Headers of getCollectionItems method ### Returns This function returns a value of type `ItemsOffsetPaginated`. Returns an array of items in the collection. ## Get collection by ID Retrieves a collection by its ID. This operation is performed by calling function `getCollectionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collections-id/). *Currently we don't have an example for calling `getCollectionById` in integration tests* ### Arguments collectionId `String` - The ID of the collection. Example: "926489" headers `GetCollectionByIdHeaders` - Headers of getCollectionById method ### Returns This function returns a value of type `Collection`. Returns an array of items in the collection. --- ## Untitled *Type: page* DevicePinnersManager Get device pin Remove device pin List enterprise device pins Get device pin Retrieves information about an individual… # DevicePinnersManager - [Get device pin](#get-device-pin) - [Remove device pin](#remove-device-pin) - [List enterprise device pins](#list-enterprise-device-pins) ## Get device pin Retrieves information about an individual device pin. This operation is performed by calling function `getDevicePinnerById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-device-pinners-id/). ``` client.getDevicePinners().getDevicePinnerById(devicePinnerId) ``` ### Arguments devicePinnerId `String` - The ID of the device pin. Example: "2324234" headers `GetDevicePinnerByIdHeaders` - Headers of getDevicePinnerById method ### Returns This function returns a value of type `DevicePinner`. Returns information about a single device pin. ## Remove device pin Deletes an individual device pin. This operation is performed by calling function `deleteDevicePinnerById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-device-pinners-id/). ``` client.getDevicePinners().deleteDevicePinnerById(devicePinnerId) ``` ### Arguments devicePinnerId `String` - The ID of the device pin. Example: "2324234" headers `DeleteDevicePinnerByIdHeaders` - Headers of deleteDevicePinnerById method ### Returns This function returns a value of type `void`. Returns an empty response when the pin has been deleted. ## List enterprise device pins Retrieves all the device pins within an enterprise. The user must have admin privileges, and the application needs the "manage enterprise" scope to make this call. This operation is performed by calling function `getEnterpriseDevicePinners`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-enterprises-id-device-pinners/). ``` client.getDevicePinners().getEnterpriseDevicePinners(enterpriseId) ``` ### Arguments enterpriseId `String` - The ID of the enterprise. Example: "3442311" queryParams `GetEnterpriseDevicePinnersQueryParams` - Query parameters of getEnterpriseDevicePinners method headers `GetEnterpriseDevicePinnersHeaders` - Headers of getEnterpriseDevicePinners method ### Returns This function returns a value of type `DevicePinners`. Returns a list of device pins for a given enterprise. --- ## Untitled *Type: page* DocgenManager Get Box Doc Gen job by ID List all Box Doc Gen jobs Get Box Doc Gen jobs by batch ID Generate document using Box Doc Gen… # DocgenManager - [Get Box Doc Gen job by ID](#get-box-doc-gen-job-by-id) - [List all Box Doc Gen jobs](#list-all-box-doc-gen-jobs) - [Get Box Doc Gen jobs by batch ID](#get-box-doc-gen-jobs-by-batch-id) - [Generate document using Box Doc Gen template](#generate-document-using-box-doc-gen-template) ## Get Box Doc Gen job by ID Get details of the Box Doc Gen job. This operation is performed by calling function `getDocgenJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs-id/). ``` client.getDocgen().getDocgenJobByIdV2025R0(docgenJobItemFromList.getId()) ``` ### Arguments jobId `String` - Box Doc Gen job ID. Example: 123 headers `GetDocgenJobByIdV2025R0Headers` - Headers of getDocgenJobByIdV2025R0 method ### Returns This function returns a value of type `DocGenJobV2025R0`. Details of the Box Doc Gen job. ## List all Box Doc Gen jobs Lists all Box Doc Gen jobs for a user. This operation is performed by calling function `getDocgenJobsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-jobs/). ``` client.getDocgen().getDocgenJobsV2025R0(new GetDocgenJobsV2025R0QueryParams.Builder().limit(500L).build()) ``` ### Arguments queryParams `GetDocgenJobsV2025R0QueryParams` - Query parameters of getDocgenJobsV2025R0 method headers `GetDocgenJobsV2025R0Headers` - Headers of getDocgenJobsV2025R0 method ### Returns This function returns a value of type `DocGenJobsFullV2025R0`. A list of Box Doc Gen jobs. ## Get Box Doc Gen jobs by batch ID Lists Box Doc Gen jobs in a batch. This operation is performed by calling function `getDocgenBatchJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-batch-jobs-id/). ``` client.getDocgen().getDocgenBatchJobByIdV2025R0(docgenBatch.getId()) ``` ### Arguments batchId `String` - Box Doc Gen batch ID. Example: 123 queryParams `GetDocgenBatchJobByIdV2025R0QueryParams` - Query parameters of getDocgenBatchJobByIdV2025R0 method headers `GetDocgenBatchJobByIdV2025R0Headers` - Headers of getDocgenBatchJobByIdV2025R0 method ### Returns This function returns a value of type `DocGenJobsV2025R0`. Returns a list of Box Doc Gen jobs in a Box Doc Gen batch. ## Generate document using Box Doc Gen template Generates a document using a Box Doc Gen template. This operation is performed by calling function `createDocgenBatchV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-batches/). ``` client.getDocgen().createDocgenBatchV2025R0(new DocGenBatchCreateRequestV2025R0(new FileReferenceV2025R0(uploadedFile.getId()), "api", new DocGenBatchCreateRequestV2025R0DestinationFolderField(folder.getId()), "pdf", Arrays.asList(new DocGenDocumentGenerationDataV2025R0("test", mapOf(entryOf("abc", "xyz")))))) ``` ### Arguments requestBody `DocGenBatchCreateRequestV2025R0` - Request body of createDocgenBatchV2025R0 method headers `CreateDocgenBatchV2025R0Headers` - Headers of createDocgenBatchV2025R0 method ### Returns This function returns a value of type `DocGenBatchBaseV2025R0`. The created Batch ID. --- ## Untitled *Type: page* CommentsManager List file comments Get comment Update comment Remove comment Create comment List file comments Retrieves a list of comments… # CommentsManager - [List file comments](#list-file-comments) - [Get comment](#get-comment) - [Update comment](#update-comment) - [Remove comment](#remove-comment) - [Create comment](#create-comment) ## List file comments Retrieves a list of comments for a file. This operation is performed by calling function `getFileComments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-comments/). ``` client.getComments().getFileComments(fileId) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileCommentsQueryParams` - Query parameters of getFileComments method headers `GetFileCommentsHeaders` - Headers of getFileComments method ### Returns This function returns a value of type `Comments`. Returns a collection of comment objects. If there are no comments on this file an empty collection will be returned. ## Get comment Retrieves the message and metadata for a specific comment, as well as information on the user who created the comment. This operation is performed by calling function `getCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-comments-id/). ``` client.getComments().getCommentById(newComment.getId()) ``` ### Arguments commentId `String` - The ID of the comment. Example: "12345" queryParams `GetCommentByIdQueryParams` - Query parameters of getCommentById method headers `GetCommentByIdHeaders` - Headers of getCommentById method ### Returns This function returns a value of type `CommentFull`. Returns a full comment object. ## Update comment Update the message of a comment. This operation is performed by calling function `updateCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-comments-id/). ``` client.getComments().updateCommentById(newReplyComment.getId(), new UpdateCommentByIdRequestBody.Builder().message(newMessage).build()) ``` ### Arguments commentId `String` - The ID of the comment. Example: "12345" requestBody `UpdateCommentByIdRequestBody` - Request body of updateCommentById method queryParams `UpdateCommentByIdQueryParams` - Query parameters of updateCommentById method headers `UpdateCommentByIdHeaders` - Headers of updateCommentById method ### Returns This function returns a value of type `CommentFull`. Returns the updated comment object. ## Remove comment Permanently deletes a comment. This operation is performed by calling function `deleteCommentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-comments-id/). ``` client.getComments().deleteCommentById(newComment.getId()) ``` ### Arguments commentId `String` - The ID of the comment. Example: "12345" headers `DeleteCommentByIdHeaders` - Headers of deleteCommentById method ### Returns This function returns a value of type `void`. Returns an empty response when the comment has been deleted. ## Create comment Adds a comment by the user to a specific file, or as a reply to an other comment. This operation is performed by calling function `createComment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-comments/). ``` client.getComments().createComment(new CreateCommentRequestBody(message, new CreateCommentRequestBodyItemField(fileId, CreateCommentRequestBodyItemTypeField.FILE))) ``` ### Arguments requestBody `CreateCommentRequestBody` - Request body of createComment method queryParams `CreateCommentQueryParams` - Query parameters of createComment method headers `CreateCommentHeaders` - Headers of createComment method ### Returns This function returns a value of type `CommentFull`. Returns the newly created comment object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* DocgenTemplateManager Create Box Doc Gen template List Box Doc Gen templates Delete Box Doc Gen template Get Box Doc Gen template by ID List… # DocgenTemplateManager - [Create Box Doc Gen template](#create-box-doc-gen-template) - [List Box Doc Gen templates](#list-box-doc-gen-templates) - [Delete Box Doc Gen template](#delete-box-doc-gen-template) - [Get Box Doc Gen template by ID](#get-box-doc-gen-template-by-id) - [List all Box Doc Gen template tags in template](#list-all-box-doc-gen-template-tags-in-template) - [Get list of all Box Doc Gen jobs for template](#get-list-of-all-box-doc-gen-jobs-for-template) ## Create Box Doc Gen template Marks a file as a Box Doc Gen template. This operation is performed by calling function `createDocgenTemplateV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-docgen-templates/). ``` client.getDocgenTemplate().createDocgenTemplateV2025R0(new DocGenTemplateCreateRequestV2025R0(new FileReferenceV2025R0(file.getId()))) ``` ### Arguments requestBody `DocGenTemplateCreateRequestV2025R0` - Request body of createDocgenTemplateV2025R0 method headers `CreateDocgenTemplateV2025R0Headers` - Headers of createDocgenTemplateV2025R0 method ### Returns This function returns a value of type `DocGenTemplateBaseV2025R0`. The file which has now been marked as a Box Doc Gen template. ## List Box Doc Gen templates Lists Box Doc Gen templates on which the user is a collaborator. This operation is performed by calling function `getDocgenTemplatesV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates/). ``` client.getDocgenTemplate().getDocgenTemplatesV2025R0() ``` ### Arguments queryParams `GetDocgenTemplatesV2025R0QueryParams` - Query parameters of getDocgenTemplatesV2025R0 method headers `GetDocgenTemplatesV2025R0Headers` - Headers of getDocgenTemplatesV2025R0 method ### Returns This function returns a value of type `DocGenTemplatesV2025R0`. Returns a collection of templates. ## Delete Box Doc Gen template Unmarks file as Box Doc Gen template. This operation is performed by calling function `deleteDocgenTemplateByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-docgen-templates-id/). ``` client.getDocgenTemplate().deleteDocgenTemplateByIdV2025R0(createdDocgenTemplate.getFile().getId()) ``` ### Arguments templateId `String` - ID of the file which will no longer be marked as a Box Doc Gen template. Example: "123" headers `DeleteDocgenTemplateByIdV2025R0Headers` - Headers of deleteDocgenTemplateByIdV2025R0 method ### Returns This function returns a value of type `void`. Returns an empty response when a file is no longer marked as a Box Doc Gen template. ## Get Box Doc Gen template by ID Lists details of a specific Box Doc Gen template. This operation is performed by calling function `getDocgenTemplateByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id/). ``` client.getDocgenTemplate().getDocgenTemplateByIdV2025R0(createdDocgenTemplate.getFile().getId()) ``` ### Arguments templateId `String` - The ID of a Box Doc Gen template. Example: 123 headers `GetDocgenTemplateByIdV2025R0Headers` - Headers of getDocgenTemplateByIdV2025R0 method ### Returns This function returns a value of type `DocGenTemplateV2025R0`. Returns a template. ## List all Box Doc Gen template tags in template Lists all tags in a Box Doc Gen template. This operation is performed by calling function `getDocgenTemplateTagsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-templates-id-tags/). ``` client.getDocgenTemplate().getDocgenTemplateTagsV2025R0(fetchedDocgenTemplate.getFile().getId()) ``` ### Arguments templateId `String` - ID of template. Example: 123 queryParams `GetDocgenTemplateTagsV2025R0QueryParams` - Query parameters of getDocgenTemplateTagsV2025R0 method headers `GetDocgenTemplateTagsV2025R0Headers` - Headers of getDocgenTemplateTagsV2025R0 method ### Returns This function returns a value of type `DocGenTagsV2025R0`. A list of document generation template tags.Processing tags for the file. ## Get list of all Box Doc Gen jobs for template Lists the users jobs which use this template. This operation is performed by calling function `getDocgenTemplateJobByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-docgen-template-jobs-id/). ``` client.getDocgenTemplate().getDocgenTemplateJobByIdV2025R0(fetchedDocgenTemplate.getFile().getId()) ``` ### Arguments templateId `String` - Id of template to fetch jobs for. Example: 123 queryParams `GetDocgenTemplateJobByIdV2025R0QueryParams` - Query parameters of getDocgenTemplateJobByIdV2025R0 method headers `GetDocgenTemplateJobByIdV2025R0Headers` - Headers of getDocgenTemplateJobByIdV2025R0 method ### Returns This function returns a value of type `DocGenJobsV2025R0`. A single Box Doc Gen template. --- ## Untitled *Type: page* DownloadsManager Download file URL Download file Download file Download file URL Get the download URL without downloading the content. This… # DownloadsManager - [Download file URL](#download-file-url) - [Download file](#download-file) - [Download file](#download-file) ## Download file URL Get the download URL without downloading the content. This operation is performed by calling function `getDownloadFileUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-content/). ``` client.getDownloads().getDownloadFileUrl(uploadedFile.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetDownloadFileUrlQueryParams` - Query parameters of downloadFile method headers `GetDownloadFileUrlHeaders` - Headers of downloadFile method ### Returns This function returns a value of type `String`. Returns the requested file if the client has the follow redirects setting enabled to automatically follow HTTP `3xx` responses as redirects. If not, the request will return `302` instead. For details, see the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. ## Download file Returns the contents of a file in binary format. This operation is performed by calling function `downloadFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-content/). ``` client.getDownloads().downloadFile(uploadedFile.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `DownloadFileQueryParams` - Query parameters of downloadFile method headers `DownloadFileHeaders` - Headers of downloadFile method ### Returns This function returns a value of type `InputStream`. Returns the requested file if the client has the follow redirects setting enabled to automatically follow HTTP `3xx` responses as redirects. If not, the request will return `302` instead. For details, see the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will be returned indicating the time in seconds after which the file will be available for the client to download. This response can occur when the file was uploaded immediately before the download request. ## Download file Download file to a given output stream This operation is performed by calling function `downloadFileToOutputStream`. ``` client.getDownloads().downloadFileToOutputStream(uploadedFile.getId(), fileOutputStream) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" outputStream `OutputStream` - Download file to a given output stream queryParams `DownloadFileToOutputStreamQueryParams` - Query parameters of downloadFile method headers `DownloadFileToOutputStreamHeaders` - Headers of downloadFile method ### Returns This function returns a value of type `void`. --- ## Untitled *Type: page* EmailAliasesManager List user's email aliases Create email alias Remove email alias List user's email aliases Retrieves all email aliases… # EmailAliasesManager - [List user's email aliases](#list-users-email-aliases) - [Create email alias](#create-email-alias) - [Remove email alias](#remove-email-alias) ## List user's email aliases Retrieves all email aliases for a user. The collection does not include the primary login for the user. This operation is performed by calling function `getUserEmailAliases`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-email-aliases/). ``` client.getEmailAliases().getUserEmailAliases(newUser.getId()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" headers `GetUserEmailAliasesHeaders` - Headers of getUserEmailAliases method ### Returns This function returns a value of type `EmailAliases`. Returns a collection of email aliases. ## Create email alias Adds a new email alias to a user account.. This operation is performed by calling function `createUserEmailAlias`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-id-email-aliases/). ``` client.getEmailAliases().createUserEmailAlias(newUser.getId(), new CreateUserEmailAliasRequestBody(newAliasEmail)) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" requestBody `CreateUserEmailAliasRequestBody` - Request body of createUserEmailAlias method headers `CreateUserEmailAliasHeaders` - Headers of createUserEmailAlias method ### Returns This function returns a value of type `EmailAlias`. Returns the newly created email alias object. ## Remove email alias Removes an email alias from a user. This operation is performed by calling function `deleteUserEmailAliasById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id-email-aliases-id/). ``` client.getEmailAliases().deleteUserEmailAliasById(newUser.getId(), newAlias.getId()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" emailAliasId `String` - The ID of the email alias. Example: "23432" headers `DeleteUserEmailAliasByIdHeaders` - Headers of deleteUserEmailAliasById method ### Returns This function returns a value of type `void`. Removes the alias and returns an empty response. --- ## Untitled *Type: page* EventsManager Get events long poll endpoint List user and enterprise events Get events long poll endpoint Returns a list of real-time… # EventsManager - [Get events long poll endpoint](#get-events-long-poll-endpoint) - [List user and enterprise events](#list-user-and-enterprise-events) ## Get events long poll endpoint Returns a list of real-time servers that can be used for long-polling updates to the [event stream](#get-events). Long polling is the concept where a HTTP request is kept open until the server sends a response, then repeating the process over and over to receive updated responses. Long polling the event stream can only be used for user events, not for enterprise events. To use long polling, first use this endpoint to retrieve a list of long poll URLs. Next, make a long poll request to any of the provided URLs. When an event occurs in monitored account a response with the value `new_change` will be sent. The response contains no other details as it only serves as a prompt to take further action such as sending a request to the [events endpoint](#get-events) with the last known `stream_position`. After the server sends this response it closes the connection. You must now repeat the long poll process to begin listening for events again. If no events occur for a while and the connection times out you will receive a response with the value `reconnect`. When you receive this response you’ll make another call to this endpoint to restart the process. If you receive no events in `retry_timeout` seconds then you will need to make another request to the real-time server (one of the URLs in the response for this endpoint). This might be necessary due to network errors. Finally, if you receive a `max_retries` error when making a request to the real-time server, you should start over by making a call to this endpoint first. This operation is performed by calling function `getEventsWithLongPolling`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-events/). ``` client.getEvents().getEventsWithLongPolling() ``` ### Arguments headers `GetEventsWithLongPollingHeaders` - Headers of getEventsWithLongPolling method ### Returns This function returns a value of type `RealtimeServers`. Returns a paginated array of servers that can be used instead of the regular endpoints for long-polling events. ## List user and enterprise events Returns up to a year of past events for a given user or for the entire enterprise. By default this returns events for the authenticated user. To retrieve events for the entire enterprise, set the `stream_type` to `admin_logs_streaming` for live monitoring of new events, or `admin_logs` for querying across historical events. The user making the API call will need to have admin privileges, and the application will need to have the scope `manage enterprise properties` checked. This operation is performed by calling function `getEvents`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-events/). ``` client.getEvents().getEvents() ``` ### Arguments queryParams `GetEventsQueryParams` - Query parameters of getEvents method headers `GetEventsHeaders` - Headers of getEvents method ### Returns This function returns a value of type `Events`. Returns a list of event objects. Events objects are returned in pages, with each page (chunk) including a list of event objects. The response includes a `chunk_size` parameter indicating how many events were returned in this chunk, as well as the next `stream_position` that can be queried. --- ## Untitled *Type: page* FileClassificationsManager Get classification on file Add classification to file Update classification on file Remove classification from… # FileClassificationsManager - [Get classification on file](#get-classification-on-file) - [Add classification to file](#add-classification-to-file) - [Update classification on file](#update-classification-on-file) - [Remove classification from file](#remove-classification-from-file) ## Get classification on file Retrieves the classification metadata instance that has been applied to a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `getClassificationOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.getFileClassifications().getClassificationOnFile(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetClassificationOnFileHeaders` - Headers of getClassificationOnFile method ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to file Adds a classification to a file by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `addClassificationToFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.getFileClassifications().addClassificationToFile(file.getId(), new AddClassificationToFileRequestBody.Builder().boxSecurityClassificationKey(classification.getKey()).build()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `AddClassificationToFileRequestBody` - Request body of addClassificationToFile method headers `AddClassificationToFileHeaders` - Headers of addClassificationToFile method ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the file. ## Update classification on file Updates a classification on a file. The classification can only be updated if a classification has already been applied to the file before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `updateClassificationOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.getFileClassifications().updateClassificationOnFile(file.getId(), Arrays.asList(new UpdateClassificationOnFileRequestBody(secondClassification.getKey()))) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `List<UpdateClassificationOnFileRequestBody>` - Request body of updateClassificationOnFile method headers `UpdateClassificationOnFileHeaders` - Headers of updateClassificationOnFile method ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from file Removes any classifications from a file. This API can also be called by including the enterprise ID in the URL explicitly, for example `/files/:id//enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `deleteClassificationFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.getFileClassifications().deleteClassificationFromFile(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteClassificationFromFileHeaders` - Headers of deleteClassificationFromFile method ### Returns This function returns a value of type `void`. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* FileMetadataManager List metadata instances on file Get metadata instance on file Create metadata instance on file Update metadata instance… # FileMetadataManager - [List metadata instances on file](#list-metadata-instances-on-file) - [Get metadata instance on file](#get-metadata-instance-on-file) - [Create metadata instance on file](#create-metadata-instance-on-file) - [Update metadata instance on file](#update-metadata-instance-on-file) - [Remove metadata instance from file](#remove-metadata-instance-from-file) ## List metadata instances on file Retrieves all metadata for a given file. This operation is performed by calling function `getFileMetadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata/). ``` client.getFileMetadata().getFileMetadata(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileMetadataHeaders` - Headers of getFileMetadata method ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Get metadata instance on file Retrieves the instance of a metadata template that has been applied to a file. This operation is performed by calling function `getFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-id-id/). ``` client.getFileMetadata().getFileMetadataById(file.getId(), GetFileMetadataByIdScope.GLOBAL, "properties") ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `GetFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `GetFileMetadataByIdHeaders` - Headers of getFileMetadataById method ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on file Applies an instance of a metadata template to a file. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. This operation is performed by calling function `createFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-id-id/). ``` client.getFileMetadata().createFileMetadataById(file.getId(), CreateFileMetadataByIdScope.ENTERPRISE, templateKey, mapOf(entryOf("name", "John"), entryOf("age", 23), entryOf("birthDate", "2001-01-03T02:20:50.520Z"), entryOf("countryCode", "US"), entryOf("sports", Arrays.asList("basketball", "tennis")))) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `CreateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `Map<String, Object>` - Request body of createFileMetadataById method headers `CreateFileMetadataByIdHeaders` - Headers of createFileMetadataById method ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update metadata instance on file Updates a piece of metadata on a file. The metadata instance can only be updated if the template has already been applied to the file before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `updateFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-id-id/). ``` client.getFileMetadata().updateFileMetadataById(file.getId(), UpdateFileMetadataByIdScope.ENTERPRISE, templateKey, Arrays.asList(new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/name").value("Jack").build(), new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/age").value(24L).build(), new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/birthDate").value("2000-01-03T02:20:50.520Z").build(), new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/countryCode").value("CA").build(), new UpdateFileMetadataByIdRequestBody.Builder().op(UpdateFileMetadataByIdRequestBodyOpField.REPLACE).path("/sports").value(Arrays.asList("football")).build())) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `UpdateFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `List<UpdateFileMetadataByIdRequestBody>` - Request body of updateFileMetadataById method headers `UpdateFileMetadataByIdHeaders` - Headers of updateFileMetadataById method ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from file Deletes a piece of file metadata. This operation is performed by calling function `deleteFileMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-id-id/). ``` client.getFileMetadata().deleteFileMetadataById(file.getId(), DeleteFileMetadataByIdScope.ENTERPRISE, templateKey) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" scope `DeleteFileMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `DeleteFileMetadataByIdHeaders` - Headers of deleteFileMetadataById method ### Returns This function returns a value of type `void`. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* FileVersionLegalHoldsManager Get file version legal hold List file version legal holds Get file version legal hold Retrieves information… # FileVersionLegalHoldsManager - [Get file version legal hold](#get-file-version-legal-hold) - [List file version legal holds](#list-file-version-legal-holds) ## Get file version legal hold Retrieves information about the legal hold policies assigned to a file version. This operation is performed by calling function `getFileVersionLegalHoldById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds-id/). ``` client.getFileVersionLegalHolds().getFileVersionLegalHoldById(fileVersionLegalHoldId) ``` ### Arguments fileVersionLegalHoldId `String` - The ID of the file version legal hold. Example: "2348213" headers `GetFileVersionLegalHoldByIdHeaders` - Headers of getFileVersionLegalHoldById method ### Returns This function returns a value of type `FileVersionLegalHold`. Returns the legal hold policy assignments for the file version. ## List file version legal holds Get a list of file versions on legal hold for a legal hold assignment. Due to ongoing re-architecture efforts this API might not return all file versions for this policy ID. Instead, this API will only return file versions held in the legacy architecture. Two new endpoints will available to request any file versions held in the new architecture. For file versions held in the new architecture, the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API can be used to return all past file versions available for this policy assignment, and the `GET /legal_hold_policy_assignments/:id/files_on_hold` API can be used to return any current (latest) versions of a file under legal hold. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. Once the re-architecture is completed this API will be deprecated. This operation is performed by calling function `getFileVersionLegalHolds`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-legal-holds/). ``` client.getFileVersionLegalHolds().getFileVersionLegalHolds(new GetFileVersionLegalHoldsQueryParams(policyId)) ``` ### Arguments queryParams `GetFileVersionLegalHoldsQueryParams` - Query parameters of getFileVersionLegalHolds method headers `GetFileVersionLegalHoldsHeaders` - Headers of getFileVersionLegalHolds method ### Returns This function returns a value of type `FileVersionLegalHolds`. Returns the list of file version legal holds for a specific legal hold policy. --- ## Untitled *Type: page* FilesManager Get file information Update file Delete file Copy file Get file thumbnail URL Get file thumbnail Get file information Retrieves… # FilesManager - [Get file information](#get-file-information) - [Update file](#update-file) - [Delete file](#delete-file) - [Copy file](#copy-file) - [Get file thumbnail URL](#get-file-thumbnail-url) - [Get file thumbnail](#get-file-thumbnail) ## Get file information Retrieves the details about a file. This operation is performed by calling function `getFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id/). ``` client.getFiles().getFileById(uploadedFile.getId(), new GetFileByIdQueryParams.Builder().fields(Arrays.asList("is_externally_owned", "has_collaborations")).build()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileByIdQueryParams` - Query parameters of getFileById method headers `GetFileByIdHeaders` - Headers of getFileById method ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update file Updates a file. This can be used to rename or move a file, create a shared link, or lock a file. This operation is performed by calling function `updateFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id/). ``` client.getFiles().updateFileById(fileToUpdate.getId(), new UpdateFileByIdRequestBody.Builder().name(updatedName).description("Updated description").build()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateFileByIdRequestBody` - Request body of updateFileById method queryParams `UpdateFileByIdQueryParams` - Query parameters of updateFileById method headers `UpdateFileByIdHeaders` - Headers of updateFileById method ### Returns This function returns a value of type `FileFull`. Returns a file object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Delete file Deletes a file, either permanently or by moving it to the trash. The the enterprise settings determine whether the item will be permanently deleted from Box or moved to the trash. This operation is performed by calling function `deleteFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id/). ``` client.getFiles().deleteFileById(thumbnailFile.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteFileByIdHeaders` - Headers of deleteFileById method ### Returns This function returns a value of type `void`. Returns an empty response when the file has been successfully deleted. ## Copy file Creates a copy of a file. This operation is performed by calling function `copyFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-copy/). ``` client.getFiles().copyFile(fileOrigin.getId(), new CopyFileRequestBody.Builder(new CopyFileRequestBodyParentField("0")).name(copiedFileName).build()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CopyFileRequestBody` - Request body of copyFile method queryParams `CopyFileQueryParams` - Query parameters of copyFile method headers `CopyFileHeaders` - Headers of copyFile method ### Returns This function returns a value of type `FileFull`. Returns a new file object representing the copied file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Get file thumbnail URL Get the download URL without downloading the content. This operation is performed by calling function `getFileThumbnailUrl`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` client.getFiles().getFileThumbnailUrl(thumbnailFile.getId(), GetFileThumbnailUrlExtension.PNG) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension `GetFileThumbnailUrlExtension` - The file format for the thumbnail. Example: "png" queryParams `GetFileThumbnailUrlQueryParams` - Query parameters of getFileThumbnailById method headers `GetFileThumbnailUrlHeaders` - Headers of getFileThumbnailById method ### Returns This function returns a value of type `String`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. ## Get file thumbnail Retrieves a thumbnail, or smaller image representation, of a file. Sizes of `32x32`,`64x64`, `128x128`, and `256x256` can be returned in the `.png` format and sizes of `32x32`, `160x160`, and `320x320` can be returned in the `.jpg` format. Thumbnails can be generated for the image and video file formats listed [found on our community site](https://community.box.com/t5/Migrating-and-Previewing-Content/File-Types-and-Fonts-Supported-in-Box-Content-Preview/ta-p/327). This operation is performed by calling function `getFileThumbnailById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-thumbnail-id/). ``` client.getFiles().getFileThumbnailById(thumbnailFile.getId(), GetFileThumbnailByIdExtension.PNG) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" extension `GetFileThumbnailByIdExtension` - The file format for the thumbnail. Example: "png" queryParams `GetFileThumbnailByIdQueryParams` - Query parameters of getFileThumbnailById method headers `GetFileThumbnailByIdHeaders` - Headers of getFileThumbnailById method ### Returns This function returns a value of type `InputStream`. When a thumbnail can be created the thumbnail data will be returned in the body of the response.Sometimes generating a thumbnail can take a few seconds. In these situations the API returns a `Location`-header pointing to a placeholder graphic for this file type. The placeholder graphic can be used in a user interface until the thumbnail generation has completed. The `Retry-After`-header indicates when to the thumbnail will be ready. At that time, retry this endpoint to retrieve the thumbnail. --- ## Untitled *Type: page* FileVersionRetentionsManager List file version retentions Get retention on file List file version retentions Retrieves all file version… # FileVersionRetentionsManager - [List file version retentions](#list-file-version-retentions) - [Get retention on file](#get-retention-on-file) ## List file version retentions Retrieves all file version retentions for the given enterprise. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `getFileVersionRetentions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions/). ``` client.getFileVersionRetentions().getFileVersionRetentions() ``` ### Arguments queryParams `GetFileVersionRetentionsQueryParams` - Query parameters of getFileVersionRetentions method headers `GetFileVersionRetentionsHeaders` - Headers of getFileVersionRetentions method ### Returns This function returns a value of type `FileVersionRetentions`. Returns a list of all file version retentions for the enterprise. ## Get retention on file Returns information about a file version retention. **Note**: File retention API is now **deprecated**. To get information about files and file versions under retention, see [files under retention](e://get-retention-policy-assignments-id-files-under-retention) or [file versions under retention](e://get-retention-policy-assignments-id-file-versions-under-retention) endpoints. This operation is performed by calling function `getFileVersionRetentionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-version-retentions-id/). ``` client.getFileVersionRetentions().getFileVersionRetentionById(fileVersionRetention.getId()) ``` ### Arguments fileVersionRetentionId `String` - The ID of the file version retention. Example: "3424234" headers `GetFileVersionRetentionByIdHeaders` - Headers of getFileVersionRetentionById method ### Returns This function returns a value of type `FileVersionRetention`. Returns a file version retention object. --- ## Untitled *Type: page* FileVersionsManager List all file versions Get file version Remove file version Restore file version Promote file version List all file… # FileVersionsManager - [List all file versions](#list-all-file-versions) - [Get file version](#get-file-version) - [Remove file version](#remove-file-version) - [Restore file version](#restore-file-version) - [Promote file version](#promote-file-version) ## List all file versions Retrieve a list of the past versions for a file. Versions are only tracked by Box users with premium accounts. To fetch the ID of the current version of a file, use the `GET /file/:id` API. This operation is performed by calling function `getFileVersions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions/). ``` client.getFileVersions().getFileVersions(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileVersionsQueryParams` - Query parameters of getFileVersions method headers `GetFileVersionsHeaders` - Headers of getFileVersions method ### Returns This function returns a value of type `FileVersions`. Returns an array of past versions for this file. ## Get file version Retrieve a specific version of a file. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `getFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-versions-id/). ``` client.getFileVersions().getFileVersionById(file.getId(), fileVersions.getEntries().get(0).getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `String` - The ID of the file version. Example: "1234" queryParams `GetFileVersionByIdQueryParams` - Query parameters of getFileVersionById method headers `GetFileVersionByIdHeaders` - Headers of getFileVersionById method ### Returns This function returns a value of type `FileVersionFull`. Returns a specific version of a file. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Remove file version Move a file version to the trash. Versions are only tracked for Box users with premium accounts. This operation is performed by calling function `deleteFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-versions-id/). ``` client.getFileVersions().deleteFileVersionById(file.getId(), fileVersion.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `String` - The ID of the file version. Example: "1234" headers `DeleteFileVersionByIdHeaders` - Headers of deleteFileVersionById method ### Returns This function returns a value of type `void`. Returns an empty response when the file has been successfully deleted. ## Restore file version Restores a specific version of a file after it was deleted. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `updateFileVersionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-versions-id/). ``` client.getFileVersions().updateFileVersionById(file.getId(), fileVersion.getId(), new UpdateFileVersionByIdRequestBody.Builder().trashedAt(null).build()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" fileVersionId `String` - The ID of the file version. Example: "1234" requestBody `UpdateFileVersionByIdRequestBody` - Request body of updateFileVersionById method headers `UpdateFileVersionByIdHeaders` - Headers of updateFileVersionById method ### Returns This function returns a value of type `FileVersionFull`. Returns a restored file version object. ## Promote file version Promote a specific version of a file. If previous versions exist, this method can be used to promote one of the older versions to the top of the version history. This creates a new copy of the old version and puts it at the top of the versions history. The file will have the exact same contents as the older version, with the the same hash digest, `etag`, and name as the original. Other properties such as comments do not get updated to their former values. Don't use this endpoint to restore Box Notes, as it works with file formats such as PDF, DOC, PPTX or similar. This operation is performed by calling function `promoteFileVersion`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-versions-current/). ``` client.getFileVersions().promoteFileVersion(file.getId(), new PromoteFileVersionRequestBody.Builder().id(fileVersions.getEntries().get(0).getId()).type(PromoteFileVersionRequestBodyTypeField.FILE_VERSION).build()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `PromoteFileVersionRequestBody` - Request body of promoteFileVersion method queryParams `PromoteFileVersionQueryParams` - Query parameters of promoteFileVersion method headers `PromoteFileVersionHeaders` - Headers of promoteFileVersion method ### Returns This function returns a value of type `FileVersionFull`. Returns a newly created file version object. --- ## Untitled *Type: page* FileRequestsManager Get file request Update file request Delete file request Copy file request Get file request Retrieves the information… # FileRequestsManager - [Get file request](#get-file-request) - [Update file request](#update-file-request) - [Delete file request](#delete-file-request) - [Copy file request](#copy-file-request) ## Get file request Retrieves the information about a file request. This operation is performed by calling function `getFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-file-requests-id/). ``` client.getFileRequests().getFileRequestById(fileRequestId) ``` ### Arguments fileRequestId `String` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" headers `GetFileRequestByIdHeaders` - Headers of getFileRequestById method ### Returns This function returns a value of type `FileRequest`. Returns a file request object. ## Update file request Updates a file request. This can be used to activate or deactivate a file request. This operation is performed by calling function `updateFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-file-requests-id/). ``` client.getFileRequests().updateFileRequestById(copiedFileRequest.getId(), new FileRequestUpdateRequest.Builder().title("updated title").description("updated description").build()) ``` ### Arguments fileRequestId `String` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" requestBody `FileRequestUpdateRequest` - Request body of updateFileRequestById method headers `UpdateFileRequestByIdHeaders` - Headers of updateFileRequestById method ### Returns This function returns a value of type `FileRequest`. Returns the updated file request object. ## Delete file request Deletes a file request permanently. This operation is performed by calling function `deleteFileRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-file-requests-id/). ``` client.getFileRequests().deleteFileRequestById(updatedFileRequest.getId()) ``` ### Arguments fileRequestId `String` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" headers `DeleteFileRequestByIdHeaders` - Headers of deleteFileRequestById method ### Returns This function returns a value of type `void`. Returns an empty response when the file request has been successfully deleted. ## Copy file request Copies an existing file request that is already present on one folder, and applies it to another folder. This operation is performed by calling function `createFileRequestCopy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-file-requests-id-copy/). ``` client.getFileRequests().createFileRequestCopy(fileRequestId, new FileRequestCopyRequest(new FileRequestCopyRequestFolderField.Builder(fileRequest.getFolder().getId()).type(FileRequestCopyRequestFolderTypeField.FOLDER).build())) ``` ### Arguments fileRequestId `String` - The unique identifier that represent a file request. The ID for any file request can be determined by visiting a file request builder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/filerequest/123` the `file_request_id` is `123`. Example: "123" requestBody `FileRequestCopyRequest` - Request body of createFileRequestCopy method headers `CreateFileRequestCopyHeaders` - Headers of createFileRequestCopy method ### Returns This function returns a value of type `FileRequest`. Returns updated file request object. --- ## Untitled *Type: page* FileWatermarksManager Get watermark on file Apply watermark to file Remove watermark from file Get watermark on file Retrieve the watermark… # FileWatermarksManager - [Get watermark on file](#get-watermark-on-file) - [Apply watermark to file](#apply-watermark-to-file) - [Remove watermark from file](#remove-watermark-from-file) ## Get watermark on file Retrieve the watermark for a file. This operation is performed by calling function `getFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-watermark/). ``` client.getFileWatermarks().getFileWatermark(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileWatermarkHeaders` - Headers of getFileWatermark method ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this file. ## Apply watermark to file Applies or update a watermark on a file. This operation is performed by calling function `updateFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-watermark/). ``` client.getFileWatermarks().updateFileWatermark(file.getId(), new UpdateFileWatermarkRequestBody(new UpdateFileWatermarkRequestBodyWatermarkField.Builder().imprint(UpdateFileWatermarkRequestBodyWatermarkImprintField.DEFAULT).build())) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateFileWatermarkRequestBody` - Request body of updateFileWatermark method headers `UpdateFileWatermarkHeaders` - Headers of updateFileWatermark method ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this file.Returns a new watermark if no watermark existed on this file yet. ## Remove watermark from file Removes the watermark from a file. This operation is performed by calling function `deleteFileWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-watermark/). ``` client.getFileWatermarks().deleteFileWatermark(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteFileWatermarkHeaders` - Headers of deleteFileWatermark method ### Returns This function returns a value of type `void`. Removes the watermark and returns an empty response. --- ## Untitled *Type: page* FolderClassificationsManager Get classification on folder Add classification to folder Update classification on folder Remove classification… # FolderClassificationsManager - [Get classification on folder](#get-classification-on-folder) - [Add classification to folder](#add-classification-to-folder) - [Update classification on folder](#update-classification-on-folder) - [Remove classification from folder](#remove-classification-from-folder) ## Get classification on folder Retrieves the classification metadata instance that has been applied to a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `getClassificationOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.getFolderClassifications().getClassificationOnFolder(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetClassificationOnFolderHeaders` - Headers of getClassificationOnFolder method ### Returns This function returns a value of type `Classification`. Returns an instance of the `securityClassification` metadata template, which contains a `Box__Security__Classification__Key` field that lists all the classifications available to this enterprise. ## Add classification to folder Adds a classification to a folder by specifying the label of the classification to add. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `addClassificationToFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.getFolderClassifications().addClassificationToFolder(folder.getId(), new AddClassificationToFolderRequestBody.Builder().boxSecurityClassificationKey(classification.getKey()).build()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `AddClassificationToFolderRequestBody` - Request body of addClassificationToFolder method headers `AddClassificationToFolderHeaders` - Headers of addClassificationToFolder method ### Returns This function returns a value of type `Classification`. Returns the classification template instance that was applied to the folder. ## Update classification on folder Updates a classification on a folder. The classification can only be updated if a classification has already been applied to the folder before. When editing classifications, only values are defined for the enterprise will be accepted. This operation is performed by calling function `updateClassificationOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.getFolderClassifications().updateClassificationOnFolder(folder.getId(), Arrays.asList(new UpdateClassificationOnFolderRequestBody(secondClassification.getKey()))) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `List<UpdateClassificationOnFolderRequestBody>` - Request body of updateClassificationOnFolder method headers `UpdateClassificationOnFolderHeaders` - Headers of updateClassificationOnFolder method ### Returns This function returns a value of type `Classification`. Returns the updated classification metadata template instance. ## Remove classification from folder Removes any classifications from a folder. This API can also be called by including the enterprise ID in the URL explicitly, for example `/folders/:id/enterprise_12345/securityClassification-6VMVochwUWo`. This operation is performed by calling function `deleteClassificationFromFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-enterprise-securityClassification-6VMVochwUWo/). ``` client.getFolderClassifications().deleteClassificationFromFolder(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteClassificationFromFolderHeaders` - Headers of deleteClassificationFromFolder method ### Returns This function returns a value of type `void`. Returns an empty response when the classification is successfully deleted. --- ## Untitled *Type: page* FolderLocksManager List folder locks Create folder lock Delete folder lock List folder locks Retrieves folder lock details for a given… # FolderLocksManager - [List folder locks](#list-folder-locks) - [Create folder lock](#create-folder-lock) - [Delete folder lock](#delete-folder-lock) ## List folder locks Retrieves folder lock details for a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `getFolderLocks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folder-locks/). ``` client.getFolderLocks().getFolderLocks(new GetFolderLocksQueryParams(folder.getId())) ``` ### Arguments queryParams `GetFolderLocksQueryParams` - Query parameters of getFolderLocks method headers `GetFolderLocksHeaders` - Headers of getFolderLocks method ### Returns This function returns a value of type `FolderLocks`. Returns details for all folder locks applied to the folder, including the lock type and user that applied the lock. ## Create folder lock Creates a folder lock on a folder, preventing it from being moved and/or deleted. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `createFolderLock`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folder-locks/). ``` client.getFolderLocks().createFolderLock(new CreateFolderLockRequestBody.Builder(new CreateFolderLockRequestBodyFolderField("folder", folder.getId())).lockedOperations(new CreateFolderLockRequestBodyLockedOperationsField(true, true)).build()) ``` ### Arguments requestBody `CreateFolderLockRequestBody` - Request body of createFolderLock method headers `CreateFolderLockHeaders` - Headers of createFolderLock method ### Returns This function returns a value of type `FolderLock`. Returns the instance of the folder lock that was applied to the folder, including the user that applied the lock and the operations set. ## Delete folder lock Deletes a folder lock on a given folder. You must be authenticated as the owner or co-owner of the folder to use this endpoint. This operation is performed by calling function `deleteFolderLockById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folder-locks-id/). ``` client.getFolderLocks().deleteFolderLockById(folderLock.getId()) ``` ### Arguments folderLockId `String` - The ID of the folder lock. Example: "12345" headers `DeleteFolderLockByIdHeaders` - Headers of deleteFolderLockById method ### Returns This function returns a value of type `void`. Returns an empty response when the folder lock is successfully deleted. --- ## Untitled *Type: page* FolderMetadataManager List metadata instances on folder Get metadata instance on folder Create metadata instance on folder Update metadata… # FolderMetadataManager - [List metadata instances on folder](#list-metadata-instances-on-folder) - [Get metadata instance on folder](#get-metadata-instance-on-folder) - [Create metadata instance on folder](#create-metadata-instance-on-folder) - [Update metadata instance on folder](#update-metadata-instance-on-folder) - [Remove metadata instance from folder](#remove-metadata-instance-from-folder) ## List metadata instances on folder Retrieves all metadata for a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getFolderMetadata`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata/). ``` client.getFolderMetadata().getFolderMetadata(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetFolderMetadataHeaders` - Headers of getFolderMetadata method ### Returns This function returns a value of type `Metadatas`. Returns all the metadata associated with a folder. This API does not support pagination and will therefore always return all of the metadata associated to the folder. ## Get metadata instance on folder Retrieves the instance of a metadata template that has been applied to a folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-metadata-id-id/). ``` client.getFolderMetadata().getFolderMetadataById(folder.getId(), GetFolderMetadataByIdScope.GLOBAL, "properties") ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `GetFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `GetFolderMetadataByIdHeaders` - Headers of getFolderMetadataById method ### Returns This function returns a value of type `MetadataFull`. An instance of the metadata template that includes additional "key:value" pairs defined by the user or an application. ## Create metadata instance on folder Applies an instance of a metadata template to a folder. In most cases only values that are present in the metadata template will be accepted, except for the `global.properties` template which accepts any key-value pair. To display the metadata template in the Box web app the enterprise needs to be configured to enable **Cascading Folder Level Metadata** for the user in the admin console. This operation is performed by calling function `createFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-metadata-id-id/). ``` client.getFolderMetadata().createFolderMetadataById(folder.getId(), CreateFolderMetadataByIdScope.ENTERPRISE, templateKey, mapOf(entryOf("name", "John"), entryOf("age", 23), entryOf("birthDate", "2001-01-03T02:20:50.520Z"), entryOf("countryCode", "US"), entryOf("sports", Arrays.asList("basketball", "tennis")))) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `CreateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `Map<String, Object>` - Request body of createFolderMetadataById method headers `CreateFolderMetadataByIdHeaders` - Headers of createFolderMetadataById method ### Returns This function returns a value of type `MetadataFull`. Returns the instance of the template that was applied to the folder, including the data that was applied to the template. ## Update metadata instance on folder Updates a piece of metadata on a folder. The metadata instance can only be updated if the template has already been applied to the folder before. When editing metadata, only values that match the metadata template schema will be accepted. The update is applied atomically. If any errors occur during the application of the operations, the metadata instance will not be changed. This operation is performed by calling function `updateFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-metadata-id-id/). ``` client.getFolderMetadata().updateFolderMetadataById(folder.getId(), UpdateFolderMetadataByIdScope.ENTERPRISE, templateKey, Arrays.asList(new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/name").value("Jack").build(), new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/age").value(24L).build(), new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/birthDate").value("2000-01-03T02:20:50.520Z").build(), new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/countryCode").value("CA").build(), new UpdateFolderMetadataByIdRequestBody.Builder().op(UpdateFolderMetadataByIdRequestBodyOpField.REPLACE).path("/sports").value(Arrays.asList("football")).build())) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `UpdateFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `List<UpdateFolderMetadataByIdRequestBody>` - Request body of updateFolderMetadataById method headers `UpdateFolderMetadataByIdHeaders` - Headers of updateFolderMetadataById method ### Returns This function returns a value of type `MetadataFull`. Returns the updated metadata template instance, with the custom template data included. ## Remove metadata instance from folder Deletes a piece of folder metadata. This operation is performed by calling function `deleteFolderMetadataById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-metadata-id-id/). ``` client.getFolderMetadata().deleteFolderMetadataById(folder.getId(), DeleteFolderMetadataByIdScope.ENTERPRISE, templateKey) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" scope `DeleteFolderMetadataByIdScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `DeleteFolderMetadataByIdHeaders` - Headers of deleteFolderMetadataById method ### Returns This function returns a value of type `void`. Returns an empty response when the metadata is successfully deleted. --- ## Untitled *Type: page* FoldersManager Get folder information Update folder Delete folder List items in folder Create folder Copy folder Get folder information… # FoldersManager - [Get folder information](#get-folder-information) - [Update folder](#update-folder) - [Delete folder](#delete-folder) - [List items in folder](#list-items-in-folder) - [Create folder](#create-folder) - [Copy folder](#copy-folder) ## Get folder information Retrieves details for a folder, including the first 100 entries in the folder. Passing `sort`, `direction`, `offset`, and `limit` parameters in query allows you to manage the list of returned [folder items](r://folder--full#param-item-collection). To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items) endpoint. This operation is performed by calling function `getFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id/). ``` client.getFolders().getFolderById("0") ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderByIdQueryParams` - Query parameters of getFolderById method headers `GetFolderByIdHeaders` - Headers of getFolderById method ### Returns This function returns a value of type `FolderFull`. Returns a folder, including the first 100 entries in the folder. If you used query parameters like `sort`, `direction`, `offset`, or `limit` the *folder items list* will be affected accordingly. To fetch more items within the folder, use the [Get items in a folder](e://get-folders-id-items)) endpoint. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Update folder Updates a folder. This can be also be used to move the folder, create shared links, update collaborations, and more. This operation is performed by calling function `updateFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id/). ``` client.getFolders().updateFolderById(folderToUpdate.getId(), new UpdateFolderByIdRequestBody.Builder().name(updatedName).description("Updated description").build()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateFolderByIdRequestBody` - Request body of updateFolderById method queryParams `UpdateFolderByIdQueryParams` - Query parameters of updateFolderById method headers `UpdateFolderByIdHeaders` - Headers of updateFolderById method ### Returns This function returns a value of type `FolderFull`. Returns a folder object for the updated folder Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. If the user is moving folders with a large number of items in all of their descendants, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. ## Delete folder Deletes a folder, either permanently or by moving it to the trash. This operation is performed by calling function `deleteFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id/). ``` client.getFolders().deleteFolderById(newFolder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `DeleteFolderByIdQueryParams` - Query parameters of deleteFolderById method headers `DeleteFolderByIdHeaders` - Headers of deleteFolderById method ### Returns This function returns a value of type `void`. Returns an empty response when the folder is successfully deleted or moved to the trash. ## List items in folder Retrieves a page of items in a folder. These items can be files, folders, and web links. To request more information about the folder itself, like its size, use the [Get a folder](#get-folders-id) endpoint instead. This operation is performed by calling function `getFolderItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-items/). ``` client.getFolders().getFolderItems(folderOrigin.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetFolderItemsQueryParams` - Query parameters of getFolderItems method headers `GetFolderItemsHeaders` - Headers of getFolderItems method ### Returns This function returns a value of type `Items`. Returns a collection of files, folders, and web links contained in a folder. ## Create folder Creates a new empty folder within the specified parent folder. This operation is performed by calling function `createFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders/). ``` client.getFolders().createFolder(new CreateFolderRequestBody(newFolderName, new CreateFolderRequestBodyParentField("0"))) ``` ### Arguments requestBody `CreateFolderRequestBody` - Request body of createFolder method queryParams `CreateFolderQueryParams` - Query parameters of createFolder method headers `CreateFolderHeaders` - Headers of createFolder method ### Returns This function returns a value of type `FolderFull`. Returns a folder object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. ## Copy folder Creates a copy of a folder within a destination folder. The original folder will not be changed. This operation is performed by calling function `copyFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id-copy/). ``` client.getFolders().copyFolder(folderOrigin.getId(), new CopyFolderRequestBody.Builder(new CopyFolderRequestBodyParentField("0")).name(copiedFolderName).build()) ``` ### Arguments folderId `String` - The unique identifier of the folder to copy. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder with the ID `0` can not be copied. Example: "0" requestBody `CopyFolderRequestBody` - Request body of copyFolder method queryParams `CopyFolderQueryParams` - Query parameters of copyFolder method headers `CopyFolderHeaders` - Headers of copyFolder method ### Returns This function returns a value of type `FolderFull`. Returns a new folder object representing the copied folder. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields. --- ## Untitled *Type: page* FolderWatermarksManager Get watermark for folder Apply watermark to folder Remove watermark from folder Get watermark for folder Retrieve… # FolderWatermarksManager - [Get watermark for folder](#get-watermark-for-folder) - [Apply watermark to folder](#apply-watermark-to-folder) - [Remove watermark from folder](#remove-watermark-from-folder) ## Get watermark for folder Retrieve the watermark for a folder. This operation is performed by calling function `getFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-watermark/). ``` client.getFolderWatermarks().getFolderWatermark(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `GetFolderWatermarkHeaders` - Headers of getFolderWatermark method ### Returns This function returns a value of type `Watermark`. Returns an object containing information about the watermark associated for to this folder. ## Apply watermark to folder Applies or update a watermark on a folder. This operation is performed by calling function `updateFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id-watermark/). ``` client.getFolderWatermarks().updateFolderWatermark(folder.getId(), new UpdateFolderWatermarkRequestBody(new UpdateFolderWatermarkRequestBodyWatermarkField.Builder().imprint(UpdateFolderWatermarkRequestBodyWatermarkImprintField.DEFAULT).build())) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateFolderWatermarkRequestBody` - Request body of updateFolderWatermark method headers `UpdateFolderWatermarkHeaders` - Headers of updateFolderWatermark method ### Returns This function returns a value of type `Watermark`. Returns an updated watermark if a watermark already existed on this folder.Returns a new watermark if no watermark existed on this folder yet. ## Remove watermark from folder Removes the watermark from a folder. This operation is performed by calling function `deleteFolderWatermark`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-watermark/). ``` client.getFolderWatermarks().deleteFolderWatermark(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteFolderWatermarkHeaders` - Headers of deleteFolderWatermark method ### Returns This function returns a value of type `void`. An empty response will be returned when the watermark was successfully deleted. --- ## Untitled *Type: page* GroupsManager List groups for enterprise Create group Get group Update group Remove group List groups for enterprise Retrieves all of the… # GroupsManager - [List groups for enterprise](#list-groups-for-enterprise) - [Create group](#create-group) - [Get group](#get-group) - [Update group](#update-group) - [Remove group](#remove-group) ## List groups for enterprise Retrieves all of the groups for a given enterprise. The user must have admin permissions to inspect enterprise's groups. This operation is performed by calling function `getGroups`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups/). ``` client.getGroups().getGroups() ``` ### Arguments queryParams `GetGroupsQueryParams` - Query parameters of getGroups method headers `GetGroupsHeaders` - Headers of getGroups method ### Returns This function returns a value of type `Groups`. Returns a collection of group objects. If there are no groups, an empty collection will be returned. ## Create group Creates a new group of users in an enterprise. Only users with admin permissions can create new groups. This operation is performed by calling function `createGroup`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups/). ``` client.getGroups().createGroup(new CreateGroupRequestBody.Builder(groupName).description(groupDescription).build()) ``` ### Arguments requestBody `CreateGroupRequestBody` - Request body of createGroup method queryParams `CreateGroupQueryParams` - Query parameters of createGroup method headers `CreateGroupHeaders` - Headers of createGroup method ### Returns This function returns a value of type `GroupFull`. Returns the new group object. ## Get group Retrieves information about a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id/). ``` client.getGroups().getGroupById(group.getId(), new GetGroupByIdQueryParams.Builder().fields(Arrays.asList("id", "name", "description", "group_type")).build()) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" queryParams `GetGroupByIdQueryParams` - Query parameters of getGroupById method headers `GetGroupByIdHeaders` - Headers of getGroupById method ### Returns This function returns a value of type `GroupFull`. Returns the group object. ## Update group Updates a specific group. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `updateGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-groups-id/). ``` client.getGroups().updateGroupById(group.getId(), new UpdateGroupByIdRequestBody.Builder().name(updatedGroupName).build()) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" requestBody `UpdateGroupByIdRequestBody` - Request body of updateGroupById method queryParams `UpdateGroupByIdQueryParams` - Query parameters of updateGroupById method headers `UpdateGroupByIdHeaders` - Headers of updateGroupById method ### Returns This function returns a value of type `GroupFull`. Returns the updated group object. ## Remove group Permanently deletes a group. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `deleteGroupById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-groups-id/). ``` client.getGroups().deleteGroupById(group.getId()) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" headers `DeleteGroupByIdHeaders` - Headers of deleteGroupById method ### Returns This function returns a value of type `void`. A blank response is returned if the group was successfully deleted. --- ## Untitled *Type: page* HubItemsManager Get hub items Manage hub items Get hub items Retrieves all items associated with a Hub. This operation is performed by… # HubItemsManager - [Get hub items](#get-hub-items) - [Manage hub items](#manage-hub-items) ## Get hub items Retrieves all items associated with a Hub. This operation is performed by calling function `getHubItemsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-items/). ``` client.getHubItems().getHubItemsV2025R0(new GetHubItemsV2025R0QueryParams(createdHub.getId())) ``` ### Arguments queryParams `GetHubItemsV2025R0QueryParams` - Query parameters of getHubItemsV2025R0 method headers `GetHubItemsV2025R0Headers` - Headers of getHubItemsV2025R0 method ### Returns This function returns a value of type `HubItemsV2025R0`. Retrieves the items associated with the specified Hub. ## Manage hub items Adds and/or removes Hub items from a Hub. This operation is performed by calling function `manageHubItemsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-manage-items/). ``` client.getHubItems().manageHubItemsV2025R0(createdHub.getId(), new HubItemsManageRequestV2025R0.Builder().operations(Arrays.asList(new HubItemOperationV2025R0(HubItemOperationV2025R0ActionField.ADD, new FolderReferenceV2025R0(folder.getId())))).build()) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubItemsManageRequestV2025R0` - Request body of manageHubItemsV2025R0 method headers `ManageHubItemsV2025R0Headers` - Headers of manageHubItemsV2025R0 method ### Returns This function returns a value of type `HubItemsManageResponseV2025R0`. --- ## Untitled *Type: page* HubCollaborationsManager Get hub collaborations Create hub collaboration Get hub collaboration by collaboration ID Update hub collaboration… # HubCollaborationsManager - [Get hub collaborations](#get-hub-collaborations) - [Create hub collaboration](#create-hub-collaboration) - [Get hub collaboration by collaboration ID](#get-hub-collaboration-by-collaboration-id) - [Update hub collaboration](#update-hub-collaboration) - [Remove hub collaboration](#remove-hub-collaboration) ## Get hub collaborations Retrieves all collaborations for a hub. This operation is performed by calling function `getHubCollaborationsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations/). ``` client.getHubCollaborations().getHubCollaborationsV2025R0(new GetHubCollaborationsV2025R0QueryParams(hub.getId())) ``` ### Arguments queryParams `GetHubCollaborationsV2025R0QueryParams` - Query parameters of getHubCollaborationsV2025R0 method headers `GetHubCollaborationsV2025R0Headers` - Headers of getHubCollaborationsV2025R0 method ### Returns This function returns a value of type `HubCollaborationsV2025R0`. Retrieves the collaborations associated with the specified hub. ## Create hub collaboration Adds a collaboration for a single user or a single group to a hub. Collaborations can be created using email address, user IDs, or group IDs. This operation is performed by calling function `createHubCollaborationV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hub-collaborations/). ``` client.getHubCollaborations().createHubCollaborationV2025R0(new HubCollaborationCreateRequestV2025R0(new HubCollaborationCreateRequestV2025R0HubField(hub.getId()), new HubCollaborationCreateRequestV2025R0AccessibleByField.Builder("user").id(user.getId()).build(), "viewer")) ``` ### Arguments requestBody `HubCollaborationCreateRequestV2025R0` - Request body of createHubCollaborationV2025R0 method headers `CreateHubCollaborationV2025R0Headers` - Headers of createHubCollaborationV2025R0 method ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a new hub collaboration object. ## Get hub collaboration by collaboration ID Retrieves details for a hub collaboration by collaboration ID. This operation is performed by calling function `getHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hub-collaborations-id/). ``` client.getHubCollaborations().getHubCollaborationByIdV2025R0(createdCollaboration.getId()) ``` ### Arguments hubCollaborationId `String` - The ID of the hub collaboration. Example: "1234" headers `GetHubCollaborationByIdV2025R0Headers` - Headers of getHubCollaborationByIdV2025R0 method ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns a hub collaboration object. ## Update hub collaboration Updates a hub collaboration. Can be used to change the hub role. This operation is performed by calling function `updateHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hub-collaborations-id/). ``` client.getHubCollaborations().updateHubCollaborationByIdV2025R0(createdCollaboration.getId(), new HubCollaborationUpdateRequestV2025R0.Builder().role("editor").build()) ``` ### Arguments hubCollaborationId `String` - The ID of the hub collaboration. Example: "1234" requestBody `HubCollaborationUpdateRequestV2025R0` - Request body of updateHubCollaborationByIdV2025R0 method headers `UpdateHubCollaborationByIdV2025R0Headers` - Headers of updateHubCollaborationByIdV2025R0 method ### Returns This function returns a value of type `HubCollaborationV2025R0`. Returns an updated hub collaboration object. ## Remove hub collaboration Deletes a single hub collaboration. This operation is performed by calling function `deleteHubCollaborationByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hub-collaborations-id/). ``` client.getHubCollaborations().deleteHubCollaborationByIdV2025R0(createdCollaboration.getId()) ``` ### Arguments hubCollaborationId `String` - The ID of the hub collaboration. Example: "1234" headers `DeleteHubCollaborationByIdV2025R0Headers` - Headers of deleteHubCollaborationByIdV2025R0 method ### Returns This function returns a value of type `void`. A blank response is returned if the hub collaboration was successfully deleted. --- ## Untitled *Type: page* HubsManager List all hubs Create hub List all hubs for requesting enterprise Get hub information by ID Update hub information by ID Delete… # HubsManager - [List all hubs](#list-all-hubs) - [Create hub](#create-hub) - [List all hubs for requesting enterprise](#list-all-hubs-for-requesting-enterprise) - [Get hub information by ID](#get-hub-information-by-id) - [Update hub information by ID](#update-hub-information-by-id) - [Delete hub](#delete-hub) - [Copy hub](#copy-hub) ## List all hubs Retrieves all hubs for requesting user. This operation is performed by calling function `getHubsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs/). ``` client.getHubs().getHubsV2025R0(new GetHubsV2025R0QueryParams.Builder().scope("all").sort("name").direction(GetHubsV2025R0QueryParamsDirectionField.ASC).build()) ``` ### Arguments queryParams `GetHubsV2025R0QueryParams` - Query parameters of getHubsV2025R0 method headers `GetHubsV2025R0Headers` - Headers of getHubsV2025R0 method ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Create hub Creates a new Hub. This operation is performed by calling function `createHubV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs/). ``` client.getHubs().createHubV2025R0(new HubCreateRequestV2025R0.Builder(hubTitle).description(hubDescription).build()) ``` ### Arguments requestBody `HubCreateRequestV2025R0` - Request body of createHubV2025R0 method headers `CreateHubV2025R0Headers` - Headers of createHubV2025R0 method ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. ## List all hubs for requesting enterprise Retrieves all hubs for a given enterprise. Admins or Hub Co-admins of an enterprise with GCM scope can make this call. This operation is performed by calling function `getEnterpriseHubsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-enterprise-hubs/). ``` client.getHubs().getEnterpriseHubsV2025R0(new GetEnterpriseHubsV2025R0QueryParams.Builder().sort("name").direction(GetEnterpriseHubsV2025R0QueryParamsDirectionField.ASC).build()) ``` ### Arguments queryParams `GetEnterpriseHubsV2025R0QueryParams` - Query parameters of getEnterpriseHubsV2025R0 method headers `GetEnterpriseHubsV2025R0Headers` - Headers of getEnterpriseHubsV2025R0 method ### Returns This function returns a value of type `HubsV2025R0`. Returns all hubs for the given user or enterprise. ## Get hub information by ID Retrieves details for a hub by its ID. This operation is performed by calling function `getHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-hubs-id/). ``` client.getHubs().getHubByIdV2025R0(hubId) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" headers `GetHubByIdV2025R0Headers` - Headers of getHubByIdV2025R0 method ### Returns This function returns a value of type `HubV2025R0`. Returns a hub object. ## Update hub information by ID Updates a Hub. Can be used to change title, description, or Hub settings. This operation is performed by calling function `updateHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-hubs-id/). ``` client.getHubs().updateHubByIdV2025R0(hubId, new HubUpdateRequestV2025R0.Builder().title(newHubTitle).description(newHubDescription).build()) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubUpdateRequestV2025R0` - Request body of updateHubByIdV2025R0 method headers `UpdateHubByIdV2025R0Headers` - Headers of updateHubByIdV2025R0 method ### Returns This function returns a value of type `HubV2025R0`. Returns a Hub object. ## Delete hub Deletes a single hub. This operation is performed by calling function `deleteHubByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-hubs-id/). ``` client.getHubs().deleteHubByIdV2025R0(hubId) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" headers `DeleteHubByIdV2025R0Headers` - Headers of deleteHubByIdV2025R0 method ### Returns This function returns a value of type `void`. A blank response is returned if the hub was successfully deleted. ## Copy hub Creates a copy of a Hub. The original Hub will not be modified. This operation is performed by calling function `copyHubV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-hubs-id-copy/). ``` client.getHubs().copyHubV2025R0(createdHub.getId(), new HubCopyRequestV2025R0.Builder().title(copiedHubTitle).description(copiedHubDescription).build()) ``` ### Arguments hubId `String` - The unique identifier that represent a hub. The ID for any hub can be determined by visiting this hub in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/hubs/123` the `hub_id` is `123`. Example: "12345" requestBody `HubCopyRequestV2025R0` - Request body of copyHubV2025R0 method headers `CopyHubV2025R0Headers` - Headers of copyHubV2025R0 method ### Returns This function returns a value of type `HubV2025R0`. Returns a new Hub object. --- ## Untitled *Type: page* IntegrationMappingsManager List Slack integration mappings Create Slack integration mapping Update Slack integration mapping Delete Slack… # IntegrationMappingsManager - [List Slack integration mappings](#list-slack-integration-mappings) - [Create Slack integration mapping](#create-slack-integration-mapping) - [Update Slack integration mapping](#update-slack-integration-mapping) - [Delete Slack integration mapping](#delete-slack-integration-mapping) - [List Teams integration mappings](#list-teams-integration-mappings) - [Create Teams integration mapping](#create-teams-integration-mapping) - [Update Teams integration mapping](#update-teams-integration-mapping) - [Delete Teams integration mapping](#delete-teams-integration-mapping) ## List Slack integration mappings Lists [Slack integration mappings](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `getSlackIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-slack/). ``` userClient.getIntegrationMappings().getSlackIntegrationMapping() ``` ### Arguments queryParams `GetSlackIntegrationMappingQueryParams` - Query parameters of getSlackIntegrationMapping method headers `GetSlackIntegrationMappingHeaders` - Headers of getSlackIntegrationMapping method ### Returns This function returns a value of type `IntegrationMappings`. Returns a collection of integration mappings. ## Create Slack integration mapping Creates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack) by mapping a Slack channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `createSlackIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-slack/). ``` userClient.getIntegrationMappings().createSlackIntegrationMapping(new IntegrationMappingSlackCreateRequest(new IntegrationMappingPartnerItemSlack.Builder(slackPartnerItemId).slackOrgId(slackOrgId).build(), new IntegrationMappingBoxItemSlack(folder.getId()))) ``` ### Arguments requestBody `IntegrationMappingSlackCreateRequest` - Request body of createSlackIntegrationMapping method headers `CreateSlackIntegrationMappingHeaders` - Headers of createSlackIntegrationMapping method ### Returns This function returns a value of type `IntegrationMapping`. Returns the created integration mapping. ## Update Slack integration mapping Updates a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `updateSlackIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-slack-id/). ``` userClient.getIntegrationMappings().updateSlackIntegrationMappingById(slackIntegrationMapping.getId(), new UpdateSlackIntegrationMappingByIdRequestBody.Builder().boxItem(new IntegrationMappingBoxItemSlack(folder.getId())).build()) ``` ### Arguments integrationMappingId `String` - An ID of an integration mapping. Example: "11235432" requestBody `UpdateSlackIntegrationMappingByIdRequestBody` - Request body of updateSlackIntegrationMappingById method headers `UpdateSlackIntegrationMappingByIdHeaders` - Headers of updateSlackIntegrationMappingById method ### Returns This function returns a value of type `IntegrationMapping`. Returns the updated integration mapping object. ## Delete Slack integration mapping Deletes a [Slack integration mapping](https://support.box.com/hc/en-us/articles/4415585987859-Box-as-the-Content-Layer-for-Slack). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `deleteSlackIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-slack-id/). ``` userClient.getIntegrationMappings().deleteSlackIntegrationMappingById(slackIntegrationMapping.getId()) ``` ### Arguments integrationMappingId `String` - An ID of an integration mapping. Example: "11235432" headers `DeleteSlackIntegrationMappingByIdHeaders` - Headers of deleteSlackIntegrationMappingById method ### Returns This function returns a value of type `void`. Empty body in response. ## List Teams integration mappings Lists [Teams integration mappings](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) in a users' enterprise. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `getTeamsIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-integration-mappings-teams/). ``` userClient.getIntegrationMappings().getTeamsIntegrationMapping() ``` ### Arguments queryParams `GetTeamsIntegrationMappingQueryParams` - Query parameters of getTeamsIntegrationMapping method headers `GetTeamsIntegrationMappingHeaders` - Headers of getTeamsIntegrationMapping method ### Returns This function returns a value of type `IntegrationMappingsTeams`. Returns a collection of integration mappings. ## Create Teams integration mapping Creates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams) by mapping a Teams channel to a Box item. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `createTeamsIntegrationMapping`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-integration-mappings-teams/). ``` userClient.getIntegrationMappings().createTeamsIntegrationMapping(new IntegrationMappingTeamsCreateRequest(new IntegrationMappingPartnerItemTeamsCreateRequest(IntegrationMappingPartnerItemTeamsCreateRequestTypeField.CHANNEL, partnerItemId, tenantId, teamId), new FolderReference(folder.getId()))) ``` ### Arguments requestBody `IntegrationMappingTeamsCreateRequest` - Request body of createTeamsIntegrationMapping method headers `CreateTeamsIntegrationMappingHeaders` - Headers of createTeamsIntegrationMapping method ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the created integration mapping. ## Update Teams integration mapping Updates a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). Supports updating the Box folder ID and options. You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `updateTeamsIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-integration-mappings-teams-id/). ``` userClient.getIntegrationMappings().updateTeamsIntegrationMappingById(integrationMappingId, new UpdateTeamsIntegrationMappingByIdRequestBody.Builder().boxItem(new FolderReference("1234567")).build()) ``` ### Arguments integrationMappingId `String` - An ID of an integration mapping. Example: "11235432" requestBody `UpdateTeamsIntegrationMappingByIdRequestBody` - Request body of updateTeamsIntegrationMappingById method headers `UpdateTeamsIntegrationMappingByIdHeaders` - Headers of updateTeamsIntegrationMappingById method ### Returns This function returns a value of type `IntegrationMappingTeams`. Returns the updated integration mapping object. ## Delete Teams integration mapping Deletes a [Teams integration mapping](https://support.box.com/hc/en-us/articles/360044681474-Using-Box-for-Teams). You need Admin or Co-Admin role to use this endpoint. This operation is performed by calling function `deleteTeamsIntegrationMappingById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-integration-mappings-teams-id/). ``` userClient.getIntegrationMappings().deleteTeamsIntegrationMappingById(integrationMappingId) ``` ### Arguments integrationMappingId `String` - An ID of an integration mapping. Example: "11235432" headers `DeleteTeamsIntegrationMappingByIdHeaders` - Headers of deleteTeamsIntegrationMappingById method ### Returns This function returns a value of type `void`. Empty body in response. --- ## Untitled *Type: page* InvitesManager Create user invite Get user invite status Create user invite Invites an existing external user to join an enterprise. The… # InvitesManager - [Create user invite](#create-user-invite) - [Get user invite status](#get-user-invite-status) ## Create user invite Invites an existing external user to join an enterprise. The existing user can not be part of another enterprise and must already have a Box account. Once invited, the user will receive an email and are prompted to accept the invitation within the Box web application. This method requires the "Manage An Enterprise" scope enabled for the application, which can be enabled within the developer console. This operation is performed by calling function `createInvite`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-invites/). ``` client.getInvites().createInvite(new CreateInviteRequestBody(new CreateInviteRequestBodyEnterpriseField(currentUser.getEnterprise().getId()), new CreateInviteRequestBodyActionableByField.Builder().login(email).build())) ``` ### Arguments requestBody `CreateInviteRequestBody` - Request body of createInvite method queryParams `CreateInviteQueryParams` - Query parameters of createInvite method headers `CreateInviteHeaders` - Headers of createInvite method ### Returns This function returns a value of type `Invite`. Returns a new invite object. ## Get user invite status Returns the status of a user invite. This operation is performed by calling function `getInviteById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-invites-id/). ``` client.getInvites().getInviteById(invitation.getId()) ``` ### Arguments inviteId `String` - The ID of an invite. Example: "213723" queryParams `GetInviteByIdQueryParams` - Query parameters of getInviteById method headers `GetInviteByIdHeaders` - Headers of getInviteById method ### Returns This function returns a value of type `Invite`. Returns an invite object. --- ## Untitled *Type: page* LegalHoldPoliciesManager List all legal hold policies Create legal hold policy Get legal hold policy Update legal hold policy Remove legal… # LegalHoldPoliciesManager - [List all legal hold policies](#list-all-legal-hold-policies) - [Create legal hold policy](#create-legal-hold-policy) - [Get legal hold policy](#get-legal-hold-policy) - [Update legal hold policy](#update-legal-hold-policy) - [Remove legal hold policy](#remove-legal-hold-policy) ## List all legal hold policies Retrieves a list of legal hold policies that belong to an enterprise. This operation is performed by calling function `getLegalHoldPolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies/). ``` client.getLegalHoldPolicies().getLegalHoldPolicies() ``` ### Arguments queryParams `GetLegalHoldPoliciesQueryParams` - Query parameters of getLegalHoldPolicies method headers `GetLegalHoldPoliciesHeaders` - Headers of getLegalHoldPolicies method ### Returns This function returns a value of type `LegalHoldPolicies`. Returns a list of legal hold policies. ## Create legal hold policy Create a new legal hold policy. This operation is performed by calling function `createLegalHoldPolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policies/). ``` client.getLegalHoldPolicies().createLegalHoldPolicy(new CreateLegalHoldPolicyRequestBody.Builder(legalHoldPolicyName).description(legalHoldDescription).filterStartedAt(filterStartedAt).filterEndedAt(filterEndedAt).isOngoing(false).build()) ``` ### Arguments requestBody `CreateLegalHoldPolicyRequestBody` - Request body of createLegalHoldPolicy method headers `CreateLegalHoldPolicyHeaders` - Headers of createLegalHoldPolicy method ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Get legal hold policy Retrieve a legal hold policy. This operation is performed by calling function `getLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policies-id/). ``` client.getLegalHoldPolicies().getLegalHoldPolicyById(legalHoldPolicyId) ``` ### Arguments legalHoldPolicyId `String` - The ID of the legal hold policy. Example: "324432" headers `GetLegalHoldPolicyByIdHeaders` - Headers of getLegalHoldPolicyById method ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a legal hold policy object. ## Update legal hold policy Update legal hold policy. This operation is performed by calling function `updateLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-legal-hold-policies-id/). ``` client.getLegalHoldPolicies().updateLegalHoldPolicyById(legalHoldPolicyId, new UpdateLegalHoldPolicyByIdRequestBody.Builder().policyName(updatedLegalHoldPolicyName).build()) ``` ### Arguments legalHoldPolicyId `String` - The ID of the legal hold policy. Example: "324432" requestBody `UpdateLegalHoldPolicyByIdRequestBody` - Request body of updateLegalHoldPolicyById method headers `UpdateLegalHoldPolicyByIdHeaders` - Headers of updateLegalHoldPolicyById method ### Returns This function returns a value of type `LegalHoldPolicy`. Returns a new legal hold policy object. ## Remove legal hold policy Delete an existing legal hold policy. This is an asynchronous process. The policy will not be fully deleted yet when the response returns. This operation is performed by calling function `deleteLegalHoldPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policies-id/). ``` client.getLegalHoldPolicies().deleteLegalHoldPolicyById(legalHoldPolicy.getId()) ``` ### Arguments legalHoldPolicyId `String` - The ID of the legal hold policy. Example: "324432" headers `DeleteLegalHoldPolicyByIdHeaders` - Headers of deleteLegalHoldPolicyById method ### Returns This function returns a value of type `void`. A blank response is returned if the policy was successfully deleted. --- ## Untitled *Type: page* ListCollaborationsManager List file collaborations List folder collaborations List pending collaborations List group collaborations List… # ListCollaborationsManager - [List file collaborations](#list-file-collaborations) - [List folder collaborations](#list-folder-collaborations) - [List pending collaborations](#list-pending-collaborations) - [List group collaborations](#list-group-collaborations) ## List file collaborations Retrieves a list of pending and active collaborations for a file. This returns all the users that have access to the file or have been invited to the file. This operation is performed by calling function `getFileCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-collaborations/). ``` client.getListCollaborations().getFileCollaborations(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetFileCollaborationsQueryParams` - Query parameters of getFileCollaborations method headers `GetFileCollaborationsHeaders` - Headers of getFileCollaborations method ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this file an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List folder collaborations Retrieves a list of pending and active collaborations for a folder. This returns all the users that have access to the folder or have been invited to the folder. This operation is performed by calling function `getFolderCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-collaborations/). ``` client.getListCollaborations().getFolderCollaborations(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. Example: "12345" queryParams `GetFolderCollaborationsQueryParams` - Query parameters of getFolderCollaborations method headers `GetFolderCollaborationsHeaders` - Headers of getFolderCollaborations method ### Returns This function returns a value of type `Collaborations`. Returns a collection of collaboration objects. If there are no collaborations on this folder an empty collection will be returned. This list includes pending collaborations, for which the `status` is set to `pending`, indicating invitations that have been sent but not yet accepted. ## List pending collaborations Retrieves all pending collaboration invites for this user. This operation is performed by calling function `getCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations/). ``` client.getListCollaborations().getCollaborations(new GetCollaborationsQueryParams(GetCollaborationsQueryParamsStatusField.PENDING)) ``` ### Arguments queryParams `GetCollaborationsQueryParams` - Query parameters of getCollaborations method headers `GetCollaborationsHeaders` - Headers of getCollaborations method ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of pending collaboration objects. If the user has no pending collaborations, the collection will be empty. ## List group collaborations Retrieves all the collaborations for a group. The user must have admin permissions to inspect enterprise's groups. Each collaboration object has details on which files or folders the group has access to and with what role. This operation is performed by calling function `getGroupCollaborations`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-collaborations/). ``` client.getListCollaborations().getGroupCollaborations(group.getId()) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" queryParams `GetGroupCollaborationsQueryParams` - Query parameters of getGroupCollaborations method headers `GetGroupCollaborationsHeaders` - Headers of getGroupCollaborations method ### Returns This function returns a value of type `CollaborationsOffsetPaginated`. Returns a collection of collaboration objects. If there are no collaborations, an empty collection will be returned. --- ## Untitled *Type: page* MembershipsManager List user's groups List members of group Add user to group Get group membership Update group membership Remove user from… # MembershipsManager - [List user's groups](#list-users-groups) - [List members of group](#list-members-of-group) - [Add user to group](#add-user-to-group) - [Get group membership](#get-group-membership) - [Update group membership](#update-group-membership) - [Remove user from group](#remove-user-from-group) ## List user's groups Retrieves all the groups for a user. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getUserMemberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id-memberships/). ``` client.getMemberships().getUserMemberships(user.getId()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" queryParams `GetUserMembershipsQueryParams` - Query parameters of getUserMemberships method headers `GetUserMembershipsHeaders` - Headers of getUserMemberships method ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## List members of group Retrieves all the members for a group. Only members of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupMemberships`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-groups-id-memberships/). ``` client.getMemberships().getGroupMemberships(group.getId()) ``` ### Arguments groupId `String` - The ID of the group. Example: "57645" queryParams `GetGroupMembershipsQueryParams` - Query parameters of getGroupMemberships method headers `GetGroupMembershipsHeaders` - Headers of getGroupMemberships method ### Returns This function returns a value of type `GroupMemberships`. Returns a collection of membership objects. If there are no memberships, an empty collection will be returned. ## Add user to group Creates a group membership. Only users with admin-level permissions will be able to use this API. This operation is performed by calling function `createGroupMembership`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-group-memberships/). ``` client.getMemberships().createGroupMembership(new CreateGroupMembershipRequestBody(new CreateGroupMembershipRequestBodyUserField(user.getId()), new CreateGroupMembershipRequestBodyGroupField(group.getId()))) ``` ### Arguments requestBody `CreateGroupMembershipRequestBody` - Request body of createGroupMembership method queryParams `CreateGroupMembershipQueryParams` - Query parameters of createGroupMembership method headers `CreateGroupMembershipHeaders` - Headers of createGroupMembership method ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Get group membership Retrieves a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `getGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-group-memberships-id/). ``` client.getMemberships().getGroupMembershipById(groupMembership.getId()) ``` ### Arguments groupMembershipId `String` - The ID of the group membership. Example: "434534" queryParams `GetGroupMembershipByIdQueryParams` - Query parameters of getGroupMembershipById method headers `GetGroupMembershipByIdHeaders` - Headers of getGroupMembershipById method ### Returns This function returns a value of type `GroupMembership`. Returns the group membership object. ## Update group membership Updates a user's group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `updateGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-group-memberships-id/). ``` client.getMemberships().updateGroupMembershipById(groupMembership.getId(), new UpdateGroupMembershipByIdRequestBody.Builder().role(UpdateGroupMembershipByIdRequestBodyRoleField.ADMIN).build()) ``` ### Arguments groupMembershipId `String` - The ID of the group membership. Example: "434534" requestBody `UpdateGroupMembershipByIdRequestBody` - Request body of updateGroupMembershipById method queryParams `UpdateGroupMembershipByIdQueryParams` - Query parameters of updateGroupMembershipById method headers `UpdateGroupMembershipByIdHeaders` - Headers of updateGroupMembershipById method ### Returns This function returns a value of type `GroupMembership`. Returns a new group membership object. ## Remove user from group Deletes a specific group membership. Only admins of this group or users with admin-level permissions will be able to use this API. This operation is performed by calling function `deleteGroupMembershipById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-group-memberships-id/). ``` client.getMemberships().deleteGroupMembershipById(groupMembership.getId()) ``` ### Arguments groupMembershipId `String` - The ID of the group membership. Example: "434534" headers `DeleteGroupMembershipByIdHeaders` - Headers of deleteGroupMembershipById method ### Returns This function returns a value of type `void`. A blank response is returned if the membership was successfully deleted. --- ## Untitled *Type: page* MetadataTemplatesManager Find metadata template by instance ID Get metadata template by name Update metadata template Remove metadata… # MetadataTemplatesManager - [Find metadata template by instance ID](#find-metadata-template-by-instance-id) - [Get metadata template by name](#get-metadata-template-by-name) - [Update metadata template](#update-metadata-template) - [Remove metadata template](#remove-metadata-template) - [Get metadata template by ID](#get-metadata-template-by-id) - [List all global metadata templates](#list-all-global-metadata-templates) - [List all metadata templates for enterprise](#list-all-metadata-templates-for-enterprise) - [Create metadata template](#create-metadata-template) ## Find metadata template by instance ID Finds a metadata template by searching for the ID of an instance of the template. This operation is performed by calling function `getMetadataTemplatesByInstanceId`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates/). ``` client.getMetadataTemplates().getMetadataTemplatesByInstanceId(new GetMetadataTemplatesByInstanceIdQueryParams(createdMetadataInstance.getId())) ``` ### Arguments queryParams `GetMetadataTemplatesByInstanceIdQueryParams` - Query parameters of getMetadataTemplatesByInstanceId method headers `GetMetadataTemplatesByInstanceIdHeaders` - Headers of getMetadataTemplatesByInstanceId method ### Returns This function returns a value of type `MetadataTemplates`. Returns a list containing the 1 metadata template that matches the instance ID. ## Get metadata template by name Retrieves a metadata template by its `scope` and `templateKey` values. To find the `scope` and `templateKey` for a template, list all templates for an enterprise or globally, or list all templates applied to a file or folder. This operation is performed by calling function `getMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id-id-schema/). ``` client.getMetadataTemplates().getMetadataTemplate(GetMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()) ``` ### Arguments scope `GetMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `GetMetadataTemplateHeaders` - Headers of getMetadataTemplate method ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template matching the `scope` and `template` name. ## Update metadata template Updates a metadata template. The metadata template can only be updated if the template already exists. The update is applied atomically. If any errors occur during the application of the operations, the metadata template will not be changed. This operation is performed by calling function `updateMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-metadata-templates-id-id-schema/). ``` client.getMetadataTemplates().updateMetadataTemplate(UpdateMetadataTemplateScope.ENTERPRISE, templateKey, Arrays.asList(new UpdateMetadataTemplateRequestBody.Builder(UpdateMetadataTemplateRequestBodyOpField.ADDFIELD).data(mapOf(entryOf("type", "string"), entryOf("displayName", "newFieldName"))).fieldKey("newfieldname").build())) ``` ### Arguments scope `UpdateMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" requestBody `List<UpdateMetadataTemplateRequestBody>` - Request body of updateMetadataTemplate method headers `UpdateMetadataTemplateHeaders` - Headers of updateMetadataTemplate method ### Returns This function returns a value of type `MetadataTemplate`. Returns the updated metadata template, with the custom template data included. ## Remove metadata template Delete a metadata template and its instances. This deletion is permanent and can not be reversed. This operation is performed by calling function `deleteMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-templates-id-id-schema/). ``` client.getMetadataTemplates().deleteMetadataTemplate(DeleteMetadataTemplateScope.ENTERPRISE, template.getTemplateKey()) ``` ### Arguments scope `DeleteMetadataTemplateScope` - The scope of the metadata template. Example: "global" templateKey `String` - The name of the metadata template. Example: "properties" headers `DeleteMetadataTemplateHeaders` - Headers of deleteMetadataTemplate method ### Returns This function returns a value of type `void`. Returns an empty response when the metadata template is successfully deleted. ## Get metadata template by ID Retrieves a metadata template by its ID. This operation is performed by calling function `getMetadataTemplateById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-id/). ``` client.getMetadataTemplates().getMetadataTemplateById(template.getId()) ``` ### Arguments templateId `String` - The ID of the template. Example: "f7a9891f" headers `GetMetadataTemplateByIdHeaders` - Headers of getMetadataTemplateById method ### Returns This function returns a value of type `MetadataTemplate`. Returns the metadata template that matches the ID. ## List all global metadata templates Used to retrieve all generic, global metadata templates available to all enterprises using Box. This operation is performed by calling function `getGlobalMetadataTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-global/). ``` client.getMetadataTemplates().getGlobalMetadataTemplates() ``` ### Arguments queryParams `GetGlobalMetadataTemplatesQueryParams` - Query parameters of getGlobalMetadataTemplates method headers `GetGlobalMetadataTemplatesHeaders` - Headers of getGlobalMetadataTemplates method ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates available to all enterprises and their corresponding schema. ## List all metadata templates for enterprise Used to retrieve all metadata templates created to be used specifically within the user's enterprise. This operation is performed by calling function `getEnterpriseMetadataTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-templates-enterprise/). ``` client.getMetadataTemplates().getEnterpriseMetadataTemplates() ``` ### Arguments queryParams `GetEnterpriseMetadataTemplatesQueryParams` - Query parameters of getEnterpriseMetadataTemplates method headers `GetEnterpriseMetadataTemplatesHeaders` - Headers of getEnterpriseMetadataTemplates method ### Returns This function returns a value of type `MetadataTemplates`. Returns all of the metadata templates within an enterprise and their corresponding schema. ## Create metadata template Creates a new metadata template that can be applied to files and folders. This operation is performed by calling function `createMetadataTemplate`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-templates-schema/). ``` client.getMetadataTemplates().createMetadataTemplate(new CreateMetadataTemplateRequestBody.Builder("enterprise", templateKey).templateKey(templateKey).fields(Arrays.asList(new CreateMetadataTemplateRequestBodyFieldsField(CreateMetadataTemplateRequestBodyFieldsTypeField.STRING, "testName", "testName"), new CreateMetadataTemplateRequestBodyFieldsField(CreateMetadataTemplateRequestBodyFieldsTypeField.FLOAT, "age", "age"), new CreateMetadataTemplateRequestBodyFieldsField(CreateMetadataTemplateRequestBodyFieldsTypeField.DATE, "birthDate", "birthDate"), new CreateMetadataTemplateRequestBodyFieldsField.Builder(CreateMetadataTemplateRequestBodyFieldsTypeField.ENUM, "countryCode", "countryCode").options(Arrays.asList(new CreateMetadataTemplateRequestBodyFieldsOptionsField("US"), new CreateMetadataTemplateRequestBodyFieldsOptionsField("CA"))).build(), new CreateMetadataTemplateRequestBodyFieldsField.Builder(CreateMetadataTemplateRequestBodyFieldsTypeField.MULTISELECT, "sports", "sports").options(Arrays.asList(new CreateMetadataTemplateRequestBodyFieldsOptionsField("basketball"), new CreateMetadataTemplateRequestBodyFieldsOptionsField("football"), new CreateMetadataTemplateRequestBodyFieldsOptionsField("tennis"))).build())).build()) ``` ### Arguments requestBody `CreateMetadataTemplateRequestBody` - Request body of createMetadataTemplate method headers `CreateMetadataTemplateHeaders` - Headers of createMetadataTemplate method ### Returns This function returns a value of type `MetadataTemplate`. The schema representing the metadata template created. --- ## Untitled *Type: page* MetadataCascadePoliciesManager List metadata cascade policies Create metadata cascade policy Get metadata cascade policy Remove metadata… # MetadataCascadePoliciesManager - [List metadata cascade policies](#list-metadata-cascade-policies) - [Create metadata cascade policy](#create-metadata-cascade-policy) - [Get metadata cascade policy](#get-metadata-cascade-policy) - [Remove metadata cascade policy](#remove-metadata-cascade-policy) - [Force-apply metadata cascade policy to folder](#force-apply-metadata-cascade-policy-to-folder) ## List metadata cascade policies Retrieves a list of all the metadata cascade policies that are applied to a given folder. This can not be used on the root folder with ID `0`. This operation is performed by calling function `getMetadataCascadePolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies/). ``` client.getMetadataCascadePolicies().getMetadataCascadePolicies(new GetMetadataCascadePoliciesQueryParams(folder.getId())) ``` ### Arguments queryParams `GetMetadataCascadePoliciesQueryParams` - Query parameters of getMetadataCascadePolicies method headers `GetMetadataCascadePoliciesHeaders` - Headers of getMetadataCascadePolicies method ### Returns This function returns a value of type `MetadataCascadePolicies`. Returns a list of metadata cascade policies. ## Create metadata cascade policy Creates a new metadata cascade policy that applies a given metadata template to a given folder and automatically cascades it down to any files within that folder. In order for the policy to be applied a metadata instance must first be applied to the folder the policy is to be applied to. This operation is performed by calling function `createMetadataCascadePolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies/). ``` client.getMetadataCascadePolicies().createMetadataCascadePolicy(new CreateMetadataCascadePolicyRequestBody(folder.getId(), CreateMetadataCascadePolicyRequestBodyScopeField.ENTERPRISE, templateKey)) ``` ### Arguments requestBody `CreateMetadataCascadePolicyRequestBody` - Request body of createMetadataCascadePolicy method headers `CreateMetadataCascadePolicyHeaders` - Headers of createMetadataCascadePolicy method ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a new of metadata cascade policy. ## Get metadata cascade policy Retrieve a specific metadata cascade policy assigned to a folder. This operation is performed by calling function `getMetadataCascadePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-metadata-cascade-policies-id/). ``` client.getMetadataCascadePolicies().getMetadataCascadePolicyById(cascadePolicyId) ``` ### Arguments metadataCascadePolicyId `String` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" headers `GetMetadataCascadePolicyByIdHeaders` - Headers of getMetadataCascadePolicyById method ### Returns This function returns a value of type `MetadataCascadePolicy`. Returns a metadata cascade policy. ## Remove metadata cascade policy Deletes a metadata cascade policy. This operation is performed by calling function `deleteMetadataCascadePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-metadata-cascade-policies-id/). ``` client.getMetadataCascadePolicies().deleteMetadataCascadePolicyById(cascadePolicyId) ``` ### Arguments metadataCascadePolicyId `String` - The ID of the metadata cascade policy. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" headers `DeleteMetadataCascadePolicyByIdHeaders` - Headers of deleteMetadataCascadePolicyById method ### Returns This function returns a value of type `void`. Returns an empty response when the policy is successfully deleted. ## Force-apply metadata cascade policy to folder Force the metadata on a folder with a metadata cascade policy to be applied to all of its children. This can be used after creating a new cascade policy to enforce the metadata to be cascaded down to all existing files within that folder. This operation is performed by calling function `applyMetadataCascadePolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-cascade-policies-id-apply/). ``` client.getMetadataCascadePolicies().applyMetadataCascadePolicy(cascadePolicyId, new ApplyMetadataCascadePolicyRequestBody(ApplyMetadataCascadePolicyRequestBodyConflictResolutionField.OVERWRITE)) ``` ### Arguments metadataCascadePolicyId `String` - The ID of the cascade policy to force-apply. Example: "6fd4ff89-8fc1-42cf-8b29-1890dedd26d7" requestBody `ApplyMetadataCascadePolicyRequestBody` - Request body of applyMetadataCascadePolicy method headers `ApplyMetadataCascadePolicyHeaders` - Headers of applyMetadataCascadePolicy method ### Returns This function returns a value of type `void`. Returns an empty response when the API call was successful. The metadata cascade operation will be performed asynchronously. The API call will return directly, before the cascade operation is complete. There is currently no API to check for the status of this operation. --- ## Untitled *Type: page* RecentItemsManager List recently accessed items List recently accessed items Returns information about the recent items accessed by a user… # RecentItemsManager - [List recently accessed items](#list-recently-accessed-items) ## List recently accessed items Returns information about the recent items accessed by a user, either in the last 90 days or up to the last 1000 items accessed. This operation is performed by calling function `getRecentItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-recent-items/). ``` client.getRecentItems().getRecentItems() ``` ### Arguments queryParams `GetRecentItemsQueryParams` - Query parameters of getRecentItems method headers `GetRecentItemsHeaders` - Headers of getRecentItems method ### Returns This function returns a value of type `RecentItems`. Returns a list recent items access by a user. --- ## Untitled *Type: page* LegalHoldPolicyAssignmentsManager List legal hold policy assignments Assign legal hold policy Get legal hold policy assignment Unassign… # LegalHoldPolicyAssignmentsManager - [List legal hold policy assignments](#list-legal-hold-policy-assignments) - [Assign legal hold policy](#assign-legal-hold-policy) - [Get legal hold policy assignment](#get-legal-hold-policy-assignment) - [Unassign legal hold policy](#unassign-legal-hold-policy) - [List files with current file versions for legal hold policy assignment](#list-files-with-current-file-versions-for-legal-hold-policy-assignment) ## List legal hold policy assignments Retrieves a list of items a legal hold policy has been assigned to. This operation is performed by calling function `getLegalHoldPolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments/). ``` client.getLegalHoldPolicyAssignments().getLegalHoldPolicyAssignments(new GetLegalHoldPolicyAssignmentsQueryParams(legalHoldPolicyId)) ``` ### Arguments queryParams `GetLegalHoldPolicyAssignmentsQueryParams` - Query parameters of getLegalHoldPolicyAssignments method headers `GetLegalHoldPolicyAssignmentsHeaders` - Headers of getLegalHoldPolicyAssignments method ### Returns This function returns a value of type `LegalHoldPolicyAssignments`. Returns a list of legal hold policy assignments. ## Assign legal hold policy Assign a legal hold to a file, file version, folder, or user. This operation is performed by calling function `createLegalHoldPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-legal-hold-policy-assignments/). ``` client.getLegalHoldPolicyAssignments().createLegalHoldPolicyAssignment(new CreateLegalHoldPolicyAssignmentRequestBody(legalHoldPolicyId, new CreateLegalHoldPolicyAssignmentRequestBodyAssignToField(CreateLegalHoldPolicyAssignmentRequestBodyAssignToTypeField.FILE, fileId))) ``` ### Arguments requestBody `CreateLegalHoldPolicyAssignmentRequestBody` - Request body of createLegalHoldPolicyAssignment method headers `CreateLegalHoldPolicyAssignmentHeaders` - Headers of createLegalHoldPolicyAssignment method ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a new legal hold policy assignment. ## Get legal hold policy assignment Retrieve a legal hold policy assignment. This operation is performed by calling function `getLegalHoldPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id/). ``` client.getLegalHoldPolicyAssignments().getLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId) ``` ### Arguments legalHoldPolicyAssignmentId `String` - The ID of the legal hold policy assignment. Example: "753465" headers `GetLegalHoldPolicyAssignmentByIdHeaders` - Headers of getLegalHoldPolicyAssignmentById method ### Returns This function returns a value of type `LegalHoldPolicyAssignment`. Returns a legal hold policy object. ## Unassign legal hold policy Remove a legal hold from an item. This is an asynchronous process. The policy will not be fully removed yet when the response returns. This operation is performed by calling function `deleteLegalHoldPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-legal-hold-policy-assignments-id/). ``` client.getLegalHoldPolicyAssignments().deleteLegalHoldPolicyAssignmentById(legalHoldPolicyAssignmentId) ``` ### Arguments legalHoldPolicyAssignmentId `String` - The ID of the legal hold policy assignment. Example: "753465" headers `DeleteLegalHoldPolicyAssignmentByIdHeaders` - Headers of deleteLegalHoldPolicyAssignmentById method ### Returns This function returns a value of type `void`. A blank response is returned if the assignment was successfully deleted. ## List files with current file versions for legal hold policy assignment Get a list of files with current file versions for a legal hold assignment. In some cases you may want to get previous file versions instead. In these cases, use the `GET /legal_hold_policy_assignments/:id/file_versions_on_hold` API instead to return any previous versions of a file for this legal hold policy assignment. Due to ongoing re-architecture efforts this API might not return all file versions held for this policy ID. Instead, this API will only return the latest file version held in the newly developed architecture. The `GET /file_version_legal_holds` API can be used to fetch current and past versions of files held within the legacy architecture. This endpoint does not support returning any content that is on hold due to a Custodian collaborating on a Hub. The `GET /legal_hold_policy_assignments?policy_id={id}` API can be used to find a list of policy assignments for a given policy ID. This operation is performed by calling function `getLegalHoldPolicyAssignmentFileOnHold`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-legal-hold-policy-assignments-id-files-on-hold/). ``` client.getLegalHoldPolicyAssignments().getLegalHoldPolicyAssignmentFileOnHold(legalHoldPolicyAssignmentId) ``` ### Arguments legalHoldPolicyAssignmentId `String` - The ID of the legal hold policy assignment. Example: "753465" queryParams `GetLegalHoldPolicyAssignmentFileOnHoldQueryParams` - Query parameters of getLegalHoldPolicyAssignmentFileOnHold method headers `GetLegalHoldPolicyAssignmentFileOnHoldHeaders` - Headers of getLegalHoldPolicyAssignmentFileOnHold method ### Returns This function returns a value of type `FilesOnHold`. Returns the list of current file versions held under legal hold for a specific legal hold policy assignment. --- ## Untitled *Type: page* RetentionPoliciesManager List retention policies Create retention policy Get retention policy Update retention policy Delete retention… # RetentionPoliciesManager - [List retention policies](#list-retention-policies) - [Create retention policy](#create-retention-policy) - [Get retention policy](#get-retention-policy) - [Update retention policy](#update-retention-policy) - [Delete retention policy](#delete-retention-policy) ## List retention policies Retrieves all of the retention policies for an enterprise. This operation is performed by calling function `getRetentionPolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies/). ``` client.getRetentionPolicies().getRetentionPolicies() ``` ### Arguments queryParams `GetRetentionPoliciesQueryParams` - Query parameters of getRetentionPolicies method headers `GetRetentionPoliciesHeaders` - Headers of getRetentionPolicies method ### Returns This function returns a value of type `RetentionPolicies`. Returns a list retention policies in the enterprise. ## Create retention policy Creates a retention policy. This operation is performed by calling function `createRetentionPolicy`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policies/). ``` client.getRetentionPolicies().createRetentionPolicy(new CreateRetentionPolicyRequestBody.Builder(retentionPolicyName, CreateRetentionPolicyRequestBodyPolicyTypeField.FINITE, CreateRetentionPolicyRequestBodyDispositionActionField.REMOVE_RETENTION).description(retentionDescription).retentionLength("1").retentionType(CreateRetentionPolicyRequestBodyRetentionTypeField.MODIFIABLE).canOwnerExtendRetention(true).areOwnersNotified(true).build()) ``` ### Arguments requestBody `CreateRetentionPolicyRequestBody` - Request body of createRetentionPolicy method headers `CreateRetentionPolicyHeaders` - Headers of createRetentionPolicy method ### Returns This function returns a value of type `RetentionPolicy`. Returns a new retention policy object. ## Get retention policy Retrieves a retention policy. This operation is performed by calling function `getRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id/). ``` client.getRetentionPolicies().getRetentionPolicyById(retentionPolicy.getId()) ``` ### Arguments retentionPolicyId `String` - The ID of the retention policy. Example: "982312" queryParams `GetRetentionPolicyByIdQueryParams` - Query parameters of getRetentionPolicyById method headers `GetRetentionPolicyByIdHeaders` - Headers of getRetentionPolicyById method ### Returns This function returns a value of type `RetentionPolicy`. Returns the retention policy object. ## Update retention policy Updates a retention policy. This operation is performed by calling function `updateRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-retention-policies-id/). ``` client.getRetentionPolicies().updateRetentionPolicyById(retentionPolicy.getId(), new UpdateRetentionPolicyByIdRequestBody.Builder().policyName(updatedRetentionPolicyName).build()) ``` ### Arguments retentionPolicyId `String` - The ID of the retention policy. Example: "982312" requestBody `UpdateRetentionPolicyByIdRequestBody` - Request body of updateRetentionPolicyById method headers `UpdateRetentionPolicyByIdHeaders` - Headers of updateRetentionPolicyById method ### Returns This function returns a value of type `RetentionPolicy`. Returns the updated retention policy object. ## Delete retention policy Permanently deletes a retention policy. This operation is performed by calling function `deleteRetentionPolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policies-id/). ``` client.getRetentionPolicies().deleteRetentionPolicyById(retentionPolicy.getId()) ``` ### Arguments retentionPolicyId `String` - The ID of the retention policy. Example: "982312" headers `DeleteRetentionPolicyByIdHeaders` - Headers of deleteRetentionPolicyById method ### Returns This function returns a value of type `void`. Returns an empty response when the policy has been deleted. --- ## Untitled *Type: page* RetentionPolicyAssignmentsManager List retention policy assignments Assign retention policy Get retention policy assignment Remove retention… # RetentionPolicyAssignmentsManager - [List retention policy assignments](#list-retention-policy-assignments) - [Assign retention policy](#assign-retention-policy) - [Get retention policy assignment](#get-retention-policy-assignment) - [Remove retention policy assignment](#remove-retention-policy-assignment) - [Get files under retention](#get-files-under-retention) ## List retention policy assignments Returns a list of all retention policy assignments associated with a specified retention policy. This operation is performed by calling function `getRetentionPolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policies-id-assignments/). ``` client.getRetentionPolicyAssignments().getRetentionPolicyAssignments(retentionPolicy.getId()) ``` ### Arguments retentionPolicyId `String` - The ID of the retention policy. Example: "982312" queryParams `GetRetentionPolicyAssignmentsQueryParams` - Query parameters of getRetentionPolicyAssignments method headers `GetRetentionPolicyAssignmentsHeaders` - Headers of getRetentionPolicyAssignments method ### Returns This function returns a value of type `RetentionPolicyAssignments`. Returns a list of the retention policy assignments associated with the specified retention policy. ## Assign retention policy Assigns a retention policy to an item. This operation is performed by calling function `createRetentionPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-retention-policy-assignments/). ``` client.getRetentionPolicyAssignments().createRetentionPolicyAssignment(new CreateRetentionPolicyAssignmentRequestBody(retentionPolicy.getId(), new CreateRetentionPolicyAssignmentRequestBodyAssignToField.Builder(CreateRetentionPolicyAssignmentRequestBodyAssignToTypeField.FOLDER).id(folder.getId()).build())) ``` ### Arguments requestBody `CreateRetentionPolicyAssignmentRequestBody` - Request body of createRetentionPolicyAssignment method headers `CreateRetentionPolicyAssignmentHeaders` - Headers of createRetentionPolicyAssignment method ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns a new retention policy assignment object. ## Get retention policy assignment Retrieves a retention policy assignment. This operation is performed by calling function `getRetentionPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id/). ``` client.getRetentionPolicyAssignments().getRetentionPolicyAssignmentById(retentionPolicyAssignment.getId()) ``` ### Arguments retentionPolicyAssignmentId `String` - The ID of the retention policy assignment. Example: "1233123" queryParams `GetRetentionPolicyAssignmentByIdQueryParams` - Query parameters of getRetentionPolicyAssignmentById method headers `GetRetentionPolicyAssignmentByIdHeaders` - Headers of getRetentionPolicyAssignmentById method ### Returns This function returns a value of type `RetentionPolicyAssignment`. Returns the retention policy assignment object. ## Remove retention policy assignment Removes a retention policy assignment applied to content. This operation is performed by calling function `deleteRetentionPolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-retention-policy-assignments-id/). ``` client.getRetentionPolicyAssignments().deleteRetentionPolicyAssignmentById(retentionPolicyAssignment.getId()) ``` ### Arguments retentionPolicyAssignmentId `String` - The ID of the retention policy assignment. Example: "1233123" headers `DeleteRetentionPolicyAssignmentByIdHeaders` - Headers of deleteRetentionPolicyAssignmentById method ### Returns This function returns a value of type `void`. Returns an empty response when the policy assignment is successfully deleted. ## Get files under retention Returns a list of files under retention for a retention policy assignment. This operation is performed by calling function `getFilesUnderRetentionPolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-retention-policy-assignments-id-files-under-retention/). ``` client.getRetentionPolicyAssignments().getFilesUnderRetentionPolicyAssignment(retentionPolicyAssignment.getId()) ``` ### Arguments retentionPolicyAssignmentId `String` - The ID of the retention policy assignment. Example: "1233123" queryParams `GetFilesUnderRetentionPolicyAssignmentQueryParams` - Query parameters of getFilesUnderRetentionPolicyAssignment method headers `GetFilesUnderRetentionPolicyAssignmentHeaders` - Headers of getFilesUnderRetentionPolicyAssignment method ### Returns This function returns a value of type `FilesUnderRetention`. Returns a list of files under retention that are associated with the specified retention policy assignment. --- ## Untitled *Type: page* SessionTerminationManager Create jobs to terminate users session Create jobs to terminate user group session Create jobs to terminate users… # SessionTerminationManager - [Create jobs to terminate users session](#create-jobs-to-terminate-users-session) - [Create jobs to terminate user group session](#create-jobs-to-terminate-user-group-session) ## Create jobs to terminate users session Validates the roles and permissions of the user, and creates asynchronous jobs to terminate the user's sessions. Returns the status for the POST request. This operation is performed by calling function `terminateUsersSessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users-terminate-sessions/). ``` client.getSessionTermination().terminateUsersSessions(new TerminateUsersSessionsRequestBody(Arrays.asList(getEnvVar("USER_ID")), Arrays.asList(user.getLogin()))) ``` ### Arguments requestBody `TerminateUsersSessionsRequestBody` - Request body of terminateUsersSessions method headers `TerminateUsersSessionsHeaders` - Headers of terminateUsersSessions method ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. ## Create jobs to terminate user group session Validates the roles and permissions of the group, and creates asynchronous jobs to terminate the group's sessions. Returns the status for the POST request. This operation is performed by calling function `terminateGroupsSessions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-groups-terminate-sessions/). ``` client.getSessionTermination().terminateGroupsSessions(new TerminateGroupsSessionsRequestBody(Arrays.asList(group.getId()))) ``` ### Arguments requestBody `TerminateGroupsSessionsRequestBody` - Request body of terminateGroupsSessions method headers `TerminateGroupsSessionsHeaders` - Headers of terminateGroupsSessions method ### Returns This function returns a value of type `SessionTerminationMessage`. Returns a message about the request status. --- ## Untitled *Type: page* SharedLinksAppItemsManager Find app item for shared link Find app item for shared link Returns the app item represented by a shared link… # SharedLinksAppItemsManager - [Find app item for shared link](#find-app-item-for-shared-link) ## Find app item for shared link Returns the app item represented by a shared link. The link can originate from the current enterprise or another. This operation is performed by calling function `findAppItemForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--app-items/). ``` client.getSharedLinksAppItems().findAppItemForSharedLink(new FindAppItemForSharedLinkHeaders(String.join("", "shared_link=", appItemSharedLink))) ``` ### Arguments headers `FindAppItemForSharedLinkHeaders` - Headers of findAppItemForSharedLink method ### Returns This function returns a value of type `AppItem`. Returns a full app item resource if the shared link is valid and the user has access to it. --- ## Untitled *Type: page* SearchManager Query files/folders by metadata Search for content Query files/folders by metadata Create a search using SQL-like syntax to… # SearchManager - [Query files/folders by metadata](#query-files-folders-by-metadata) - [Search for content](#search-for-content) ## Query files/folders by metadata Create a search using SQL-like syntax to return items that match specific metadata. By default, this endpoint returns only the most basic info about the items for which the query matches. To get additional fields for each item, including any of the metadata, use the `fields` attribute in the query. This operation is performed by calling function `searchByMetadataQuery`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-metadata-queries-execute-read/). ``` client.getSearch().searchByMetadataQuery(new MetadataQuery.Builder(searchFrom, "0").query("name = :name AND age < :age AND birthDate >= :birthDate AND countryCode = :countryCode AND sports = :sports").queryParams(mapOf(entryOf("name", "John"), entryOf("age", 50), entryOf("birthDate", "2001-01-01T02:20:10.120Z"), entryOf("countryCode", "US"), entryOf("sports", Arrays.asList("basketball", "tennis")))).build()) ``` ### Arguments requestBody `MetadataQuery` - Request body of searchByMetadataQuery method headers `SearchByMetadataQueryHeaders` - Headers of searchByMetadataQuery method ### Returns This function returns a value of type `MetadataQueryResults`. Returns a list of files and folders that match this metadata query. ## Search for content Searches for files, folders, web links, and shared files across the users content or across the entire enterprise. This operation is performed by calling function `searchForContent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-search/). ``` client.getSearch().searchForContent(new SearchForContentQueryParams.Builder().ancestorFolderIds(Arrays.asList("0")).mdfilters(Arrays.asList(new MetadataFilter.Builder().scope(MetadataFilterScopeField.ENTERPRISE).templateKey(templateKey).filters(searchFilters).build())).build()) ``` ### Arguments queryParams `SearchForContentQueryParams` - Query parameters of searchForContent method headers `SearchForContentHeaders` - Headers of searchForContent method ### Returns This function returns a value of type `SearchResultsOrSearchResultsWithSharedLinks`. Returns a collection of search results. If there are no matching search results, the `entries` array will be empty. --- ## Untitled *Type: page* SharedLinksFilesManager Find file for shared link Get shared link for file Add shared link to file Update shared link on file Remove shared… # SharedLinksFilesManager - [Find file for shared link](#find-file-for-shared-link) - [Get shared link for file](#get-shared-link-for-file) - [Add shared link to file](#add-shared-link-to-file) - [Update shared link on file](#update-shared-link-on-file) - [Remove shared link from file](#remove-shared-link-from-file) ## Find file for shared link Returns the file represented by a shared link. A shared file can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared file when only given a shared link. The `shared_link_permission_options` array field can be returned by requesting it in the `fields` query parameter. This operation is performed by calling function `findFileForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items/). ``` userClient.getSharedLinksFiles().findFileForSharedLink(new FindFileForSharedLinkQueryParams(), new FindFileForSharedLinkHeaders(String.join("", "shared_link=", fileFromApi.getSharedLink().getUrl(), "&shared_link_password=Secret123@"))) ``` ### Arguments queryParams `FindFileForSharedLinkQueryParams` - Query parameters of findFileForSharedLink method headers `FindFileForSharedLinkHeaders` - Headers of findFileForSharedLink method ### Returns This function returns a value of type `FileFull`. Returns a full file resource if the shared link is valid and the user has access to it. ## Get shared link for file Gets the information for a shared link on a file. This operation is performed by calling function `getSharedLinkForFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id--get-shared-link/). ``` client.getSharedLinksFiles().getSharedLinkForFile(fileId, new GetSharedLinkForFileQueryParams("shared_link")) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetSharedLinkForFileQueryParams` - Query parameters of getSharedLinkForFile method headers `GetSharedLinkForFileHeaders` - Headers of getSharedLinkForFile method ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with the additional shared link information. ## Add shared link to file Adds a shared link to a file. This operation is performed by calling function `addShareLinkToFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--add-shared-link/). ``` client.getSharedLinksFiles().addShareLinkToFile(fileId, new AddShareLinkToFileRequestBody.Builder().sharedLink(new AddShareLinkToFileRequestBodySharedLinkField.Builder().access(AddShareLinkToFileRequestBodySharedLinkAccessField.OPEN).password("Secret123@").build()).build(), new AddShareLinkToFileQueryParams("shared_link")) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `AddShareLinkToFileRequestBody` - Request body of addShareLinkToFile method queryParams `AddShareLinkToFileQueryParams` - Query parameters of addShareLinkToFile method headers `AddShareLinkToFileHeaders` - Headers of addShareLinkToFile method ### Returns This function returns a value of type `FileFull`. Returns the base representation of a file with a new shared link attached. ## Update shared link on file Updates a shared link on a file. This operation is performed by calling function `updateSharedLinkOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--update-shared-link/). ``` client.getSharedLinksFiles().updateSharedLinkOnFile(fileId, new UpdateSharedLinkOnFileRequestBody.Builder().sharedLink(new UpdateSharedLinkOnFileRequestBodySharedLinkField.Builder().access(UpdateSharedLinkOnFileRequestBodySharedLinkAccessField.COLLABORATORS).build()).build(), new UpdateSharedLinkOnFileQueryParams("shared_link")) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UpdateSharedLinkOnFileRequestBody` - Request body of updateSharedLinkOnFile method queryParams `UpdateSharedLinkOnFileQueryParams` - Query parameters of updateSharedLinkOnFile method headers `UpdateSharedLinkOnFileHeaders` - Headers of updateSharedLinkOnFile method ### Returns This function returns a value of type `FileFull`. Returns a basic representation of the file, with the updated shared link attached. ## Remove shared link from file Removes a shared link from a file. This operation is performed by calling function `removeSharedLinkFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id--remove-shared-link/). ``` client.getSharedLinksFiles().removeSharedLinkFromFile(fileId, new RemoveSharedLinkFromFileRequestBody.Builder().sharedLink(null).build(), new RemoveSharedLinkFromFileQueryParams("shared_link")) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `RemoveSharedLinkFromFileRequestBody` - Request body of removeSharedLinkFromFile method queryParams `RemoveSharedLinkFromFileQueryParams` - Query parameters of removeSharedLinkFromFile method headers `RemoveSharedLinkFromFileHeaders` - Headers of removeSharedLinkFromFile method ### Returns This function returns a value of type `FileFull`. Returns a basic representation of a file, with the shared link removed. --- ## Untitled *Type: page* SharedLinksFoldersManager Find folder for shared link Get shared link for folder Add shared link to folder Update shared link on folder… # SharedLinksFoldersManager - [Find folder for shared link](#find-folder-for-shared-link) - [Get shared link for folder](#get-shared-link-for-folder) - [Add shared link to folder](#add-shared-link-to-folder) - [Update shared link on folder](#update-shared-link-on-folder) - [Remove shared link from folder](#remove-shared-link-from-folder) ## Find folder for shared link Return the folder represented by a shared link. A shared folder can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared folder when only given a shared link. This operation is performed by calling function `findFolderForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--folders/). ``` userClient.getSharedLinksFolders().findFolderForSharedLink(new FindFolderForSharedLinkQueryParams(), new FindFolderForSharedLinkHeaders(String.join("", "shared_link=", folderFromApi.getSharedLink().getUrl(), "&shared_link_password=Secret123@"))) ``` ### Arguments queryParams `FindFolderForSharedLinkQueryParams` - Query parameters of findFolderForSharedLink method headers `FindFolderForSharedLinkHeaders` - Headers of findFolderForSharedLink method ### Returns This function returns a value of type `FolderFull`. Returns a full folder resource if the shared link is valid and the user has access to it. ## Get shared link for folder Gets the information for a shared link on a folder. This operation is performed by calling function `getSharedLinkForFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id--get-shared-link/). ``` client.getSharedLinksFolders().getSharedLinkForFolder(folder.getId(), new GetSharedLinkForFolderQueryParams("shared_link")) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetSharedLinkForFolderQueryParams` - Query parameters of getSharedLinkForFolder method headers `GetSharedLinkForFolderHeaders` - Headers of getSharedLinkForFolder method ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with the additional shared link information. ## Add shared link to folder Adds a shared link to a folder. This operation is performed by calling function `addShareLinkToFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--add-shared-link/). ``` client.getSharedLinksFolders().addShareLinkToFolder(folder.getId(), new AddShareLinkToFolderRequestBody.Builder().sharedLink(new AddShareLinkToFolderRequestBodySharedLinkField.Builder().access(AddShareLinkToFolderRequestBodySharedLinkAccessField.OPEN).password("Secret123@").build()).build(), new AddShareLinkToFolderQueryParams("shared_link")) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `AddShareLinkToFolderRequestBody` - Request body of addShareLinkToFolder method queryParams `AddShareLinkToFolderQueryParams` - Query parameters of addShareLinkToFolder method headers `AddShareLinkToFolderHeaders` - Headers of addShareLinkToFolder method ### Returns This function returns a value of type `FolderFull`. Returns the base representation of a folder with a new shared link attached. ## Update shared link on folder Updates a shared link on a folder. This operation is performed by calling function `updateSharedLinkOnFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--update-shared-link/). ``` client.getSharedLinksFolders().updateSharedLinkOnFolder(folder.getId(), new UpdateSharedLinkOnFolderRequestBody.Builder().sharedLink(new UpdateSharedLinkOnFolderRequestBodySharedLinkField.Builder().access(UpdateSharedLinkOnFolderRequestBodySharedLinkAccessField.COLLABORATORS).build()).build(), new UpdateSharedLinkOnFolderQueryParams("shared_link")) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `UpdateSharedLinkOnFolderRequestBody` - Request body of updateSharedLinkOnFolder method queryParams `UpdateSharedLinkOnFolderQueryParams` - Query parameters of updateSharedLinkOnFolder method headers `UpdateSharedLinkOnFolderHeaders` - Headers of updateSharedLinkOnFolder method ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of the folder, with the updated shared link attached. ## Remove shared link from folder Removes a shared link from a folder. This operation is performed by calling function `removeSharedLinkFromFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-folders-id--remove-shared-link/). ``` client.getSharedLinksFolders().removeSharedLinkFromFolder(folder.getId(), new RemoveSharedLinkFromFolderRequestBody.Builder().sharedLink(null).build(), new RemoveSharedLinkFromFolderQueryParams("shared_link")) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `RemoveSharedLinkFromFolderRequestBody` - Request body of removeSharedLinkFromFolder method queryParams `RemoveSharedLinkFromFolderQueryParams` - Query parameters of removeSharedLinkFromFolder method headers `RemoveSharedLinkFromFolderHeaders` - Headers of removeSharedLinkFromFolder method ### Returns This function returns a value of type `FolderFull`. Returns a basic representation of a folder, with the shared link removed. --- ## Untitled *Type: page* ShieldInformationBarrierReportsManager List shield information barrier reports Create shield information barrier report Get shield… # ShieldInformationBarrierReportsManager - [List shield information barrier reports](#list-shield-information-barrier-reports) - [Create shield information barrier report](#create-shield-information-barrier-report) - [Get shield information barrier report by ID](#get-shield-information-barrier-report-by-id) ## List shield information barrier reports Lists shield information barrier reports. This operation is performed by calling function `getShieldInformationBarrierReports`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports/). ``` client.getShieldInformationBarrierReports().getShieldInformationBarrierReports(new GetShieldInformationBarrierReportsQueryParams(barrierId)) ``` ### Arguments queryParams `GetShieldInformationBarrierReportsQueryParams` - Query parameters of getShieldInformationBarrierReports method headers `GetShieldInformationBarrierReportsHeaders` - Headers of getShieldInformationBarrierReports method ### Returns This function returns a value of type `ShieldInformationBarrierReports`. Returns a paginated list of shield information barrier report objects. ## Create shield information barrier report Creates a shield information barrier report for a given barrier. This operation is performed by calling function `createShieldInformationBarrierReport`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-reports/). ``` client.getShieldInformationBarrierReports().createShieldInformationBarrierReport(new ShieldInformationBarrierReference.Builder().shieldInformationBarrier(new ShieldInformationBarrierBase.Builder().id(barrierId).type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER).build()).build()) ``` ### Arguments requestBody `ShieldInformationBarrierReference` - Request body of createShieldInformationBarrierReport method headers `CreateShieldInformationBarrierReportHeaders` - Headers of createShieldInformationBarrierReport method ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report information object. ## Get shield information barrier report by ID Retrieves a shield information barrier report by its ID. This operation is performed by calling function `getShieldInformationBarrierReportById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-reports-id/). ``` client.getShieldInformationBarrierReports().getShieldInformationBarrierReportById(createdReport.getId()) ``` ### Arguments shieldInformationBarrierReportId `String` - The ID of the shield information barrier Report. Example: "3423" headers `GetShieldInformationBarrierReportByIdHeaders` - Headers of getShieldInformationBarrierReportById method ### Returns This function returns a value of type `ShieldInformationBarrierReport`. Returns the shield information barrier report object. --- ## Untitled *Type: page* SharedLinksWebLinksManager Find web link for shared link Get shared link for web link Add shared link to web link Update shared link on web… # SharedLinksWebLinksManager - [Find web link for shared link](#find-web-link-for-shared-link) - [Get shared link for web link](#get-shared-link-for-web-link) - [Add shared link to web link](#add-shared-link-to-web-link) - [Update shared link on web link](#update-shared-link-on-web-link) - [Remove shared link from web link](#remove-shared-link-from-web-link) ## Find web link for shared link Returns the web link represented by a shared link. A shared web link can be represented by a shared link, which can originate within the current enterprise or within another. This endpoint allows an application to retrieve information about a shared web link when only given a shared link. This operation is performed by calling function `findWebLinkForSharedLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shared-items--web-links/). ``` userClient.getSharedLinksWebLinks().findWebLinkForSharedLink(new FindWebLinkForSharedLinkQueryParams(), new FindWebLinkForSharedLinkHeaders(String.join("", "shared_link=", webLinkFromApi.getSharedLink().getUrl(), "&shared_link_password=Secret123@"))) ``` ### Arguments queryParams `FindWebLinkForSharedLinkQueryParams` - Query parameters of findWebLinkForSharedLink method headers `FindWebLinkForSharedLinkHeaders` - Headers of findWebLinkForSharedLink method ### Returns This function returns a value of type `WebLink`. Returns a full web link resource if the shared link is valid and the user has access to it. ## Get shared link for web link Gets the information for a shared link on a web link. This operation is performed by calling function `getSharedLinkForWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id--get-shared-link/). ``` client.getSharedLinksWebLinks().getSharedLinkForWebLink(webLinkId, new GetSharedLinkForWebLinkQueryParams("shared_link")) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" queryParams `GetSharedLinkForWebLinkQueryParams` - Query parameters of getSharedLinkForWebLink method headers `GetSharedLinkForWebLinkHeaders` - Headers of getSharedLinkForWebLink method ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with the additional shared link information. ## Add shared link to web link Adds a shared link to a web link. This operation is performed by calling function `addShareLinkToWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--add-shared-link/). ``` client.getSharedLinksWebLinks().addShareLinkToWebLink(webLinkId, new AddShareLinkToWebLinkRequestBody.Builder().sharedLink(new AddShareLinkToWebLinkRequestBodySharedLinkField.Builder().access(AddShareLinkToWebLinkRequestBodySharedLinkAccessField.OPEN).password("Secret123@").build()).build(), new AddShareLinkToWebLinkQueryParams("shared_link")) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `AddShareLinkToWebLinkRequestBody` - Request body of addShareLinkToWebLink method queryParams `AddShareLinkToWebLinkQueryParams` - Query parameters of addShareLinkToWebLink method headers `AddShareLinkToWebLinkHeaders` - Headers of addShareLinkToWebLink method ### Returns This function returns a value of type `WebLink`. Returns the base representation of a web link with a new shared link attached. ## Update shared link on web link Updates a shared link on a web link. This operation is performed by calling function `updateSharedLinkOnWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--update-shared-link/). ``` client.getSharedLinksWebLinks().updateSharedLinkOnWebLink(webLinkId, new UpdateSharedLinkOnWebLinkRequestBody.Builder().sharedLink(new UpdateSharedLinkOnWebLinkRequestBodySharedLinkField.Builder().access(UpdateSharedLinkOnWebLinkRequestBodySharedLinkAccessField.COLLABORATORS).build()).build(), new UpdateSharedLinkOnWebLinkQueryParams("shared_link")) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `UpdateSharedLinkOnWebLinkRequestBody` - Request body of updateSharedLinkOnWebLink method queryParams `UpdateSharedLinkOnWebLinkQueryParams` - Query parameters of updateSharedLinkOnWebLink method headers `UpdateSharedLinkOnWebLinkHeaders` - Headers of updateSharedLinkOnWebLink method ### Returns This function returns a value of type `WebLink`. Returns a basic representation of the web link, with the updated shared link attached. ## Remove shared link from web link Removes a shared link from a web link. This operation is performed by calling function `removeSharedLinkFromWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id--remove-shared-link/). ``` client.getSharedLinksWebLinks().removeSharedLinkFromWebLink(webLinkId, new RemoveSharedLinkFromWebLinkRequestBody.Builder().sharedLink(null).build(), new RemoveSharedLinkFromWebLinkQueryParams("shared_link")) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `RemoveSharedLinkFromWebLinkRequestBody` - Request body of removeSharedLinkFromWebLink method queryParams `RemoveSharedLinkFromWebLinkQueryParams` - Query parameters of removeSharedLinkFromWebLink method headers `RemoveSharedLinkFromWebLinkHeaders` - Headers of removeSharedLinkFromWebLink method ### Returns This function returns a value of type `WebLink`. Returns a basic representation of a web link, with the shared link removed. --- ## Untitled *Type: page* ShieldInformationBarriersManager Get shield information barrier with specified ID Add changed status of shield information barrier with… # ShieldInformationBarriersManager - [Get shield information barrier with specified ID](#get-shield-information-barrier-with-specified-id) - [Add changed status of shield information barrier with specified ID](#add-changed-status-of-shield-information-barrier-with-specified-id) - [List shield information barriers](#list-shield-information-barriers) - [Create shield information barrier](#create-shield-information-barrier) ## Get shield information barrier with specified ID Get shield information barrier based on provided ID. This operation is performed by calling function `getShieldInformationBarrierById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers-id/). ``` client.getShieldInformationBarriers().getShieldInformationBarrierById(barrierId) ``` ### Arguments shieldInformationBarrierId `String` - The ID of the shield information barrier. Example: "1910967" headers `GetShieldInformationBarrierByIdHeaders` - Headers of getShieldInformationBarrierById method ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the shield information barrier object. ## Add changed status of shield information barrier with specified ID Change status of shield information barrier with the specified ID. This operation is performed by calling function `updateShieldInformationBarrierStatus`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers-change-status/). ``` client.getShieldInformationBarriers().updateShieldInformationBarrierStatus(new UpdateShieldInformationBarrierStatusRequestBody(barrierId, UpdateShieldInformationBarrierStatusRequestBodyStatusField.DISABLED)) ``` ### Arguments requestBody `UpdateShieldInformationBarrierStatusRequestBody` - Request body of updateShieldInformationBarrierStatus method headers `UpdateShieldInformationBarrierStatusHeaders` - Headers of updateShieldInformationBarrierStatus method ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns the updated shield information barrier object. ## List shield information barriers Retrieves a list of shield information barrier objects for the enterprise of JWT. This operation is performed by calling function `getShieldInformationBarriers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barriers/). ``` client.getShieldInformationBarriers().getShieldInformationBarriers() ``` ### Arguments queryParams `GetShieldInformationBarriersQueryParams` - Query parameters of getShieldInformationBarriers method headers `GetShieldInformationBarriersHeaders` - Headers of getShieldInformationBarriers method ### Returns This function returns a value of type `ShieldInformationBarriers`. Returns a paginated list of shield information barrier objects, empty list if currently no barrier. ## Create shield information barrier Creates a shield information barrier to separate individuals/groups within the same firm and prevents confidential information passing between them. This operation is performed by calling function `createShieldInformationBarrier`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barriers/). ``` client.getShieldInformationBarriers().createShieldInformationBarrier(new CreateShieldInformationBarrierRequestBody(new EnterpriseBase.Builder().id(enterpriseId).build())) ``` ### Arguments requestBody `CreateShieldInformationBarrierRequestBody` - Request body of createShieldInformationBarrier method headers `CreateShieldInformationBarrierHeaders` - Headers of createShieldInformationBarrier method ### Returns This function returns a value of type `ShieldInformationBarrier`. Returns a new shield information barrier object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentMembersManager Get shield information barrier segment member by ID Delete shield information barrier segment… # ShieldInformationBarrierSegmentMembersManager - [Get shield information barrier segment member by ID](#get-shield-information-barrier-segment-member-by-id) - [Delete shield information barrier segment member by ID](#delete-shield-information-barrier-segment-member-by-id) - [List shield information barrier segment members](#list-shield-information-barrier-segment-members) - [Create shield information barrier segment member](#create-shield-information-barrier-segment-member) ## Get shield information barrier segment member by ID Retrieves a shield information barrier segment member by its ID. This operation is performed by calling function `getShieldInformationBarrierSegmentMemberById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members-id/). ``` client.getShieldInformationBarrierSegmentMembers().getShieldInformationBarrierSegmentMemberById(segmentMember.getId()) ``` ### Arguments shieldInformationBarrierSegmentMemberId `String` - The ID of the shield information barrier segment Member. Example: "7815" headers `GetShieldInformationBarrierSegmentMemberByIdHeaders` - Headers of getShieldInformationBarrierSegmentMemberById method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns the shield information barrier segment member object. ## Delete shield information barrier segment member by ID Deletes a shield information barrier segment member based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentMemberById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-members-id/). ``` client.getShieldInformationBarrierSegmentMembers().deleteShieldInformationBarrierSegmentMemberById(segmentMember.getId()) ``` ### Arguments shieldInformationBarrierSegmentMemberId `String` - The ID of the shield information barrier segment Member. Example: "7815" headers `DeleteShieldInformationBarrierSegmentMemberByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentMemberById method ### Returns This function returns a value of type `void`. Returns an empty response if the segment member was deleted successfully. ## List shield information barrier segment members Lists shield information barrier segment members based on provided segment IDs. This operation is performed by calling function `getShieldInformationBarrierSegmentMembers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-members/). ``` client.getShieldInformationBarrierSegmentMembers().getShieldInformationBarrierSegmentMembers(new GetShieldInformationBarrierSegmentMembersQueryParams(segment.getId())) ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentMembersQueryParams` - Query parameters of getShieldInformationBarrierSegmentMembers method headers `GetShieldInformationBarrierSegmentMembersHeaders` - Headers of getShieldInformationBarrierSegmentMembers method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMembers`. Returns a paginated list of shield information barrier segment member objects. ## Create shield information barrier segment member Creates a new shield information barrier segment member. This operation is performed by calling function `createShieldInformationBarrierSegmentMember`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-members/). ``` client.getShieldInformationBarrierSegmentMembers().createShieldInformationBarrierSegmentMember(new CreateShieldInformationBarrierSegmentMemberRequestBody(new CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentField.Builder().id(segment.getId()).type(CreateShieldInformationBarrierSegmentMemberRequestBodyShieldInformationBarrierSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT).build(), new UserBase(getEnvVar("USER_ID")))) ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentMemberRequestBody` - Request body of createShieldInformationBarrierSegmentMember method headers `CreateShieldInformationBarrierSegmentMemberHeaders` - Headers of createShieldInformationBarrierSegmentMember method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentMember`. Returns a new shield information barrier segment member object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentRestrictionsManager Get shield information barrier segment restriction by ID Delete shield information… # ShieldInformationBarrierSegmentRestrictionsManager - [Get shield information barrier segment restriction by ID](#get-shield-information-barrier-segment-restriction-by-id) - [Delete shield information barrier segment restriction by ID](#delete-shield-information-barrier-segment-restriction-by-id) - [List shield information barrier segment restrictions](#list-shield-information-barrier-segment-restrictions) - [Create shield information barrier segment restriction](#create-shield-information-barrier-segment-restriction) ## Get shield information barrier segment restriction by ID Retrieves a shield information barrier segment restriction based on provided ID. This operation is performed by calling function `getShieldInformationBarrierSegmentRestrictionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions-id/). ``` client.getShieldInformationBarrierSegmentRestrictions().getShieldInformationBarrierSegmentRestrictionById(segmentRestrictionId) ``` ### Arguments shieldInformationBarrierSegmentRestrictionId `String` - The ID of the shield information barrier segment Restriction. Example: "4563" headers `GetShieldInformationBarrierSegmentRestrictionByIdHeaders` - Headers of getShieldInformationBarrierSegmentRestrictionById method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the shield information barrier segment restriction object. ## Delete shield information barrier segment restriction by ID Delete shield information barrier segment restriction based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentRestrictionById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segment-restrictions-id/). ``` client.getShieldInformationBarrierSegmentRestrictions().deleteShieldInformationBarrierSegmentRestrictionById(segmentRestrictionId) ``` ### Arguments shieldInformationBarrierSegmentRestrictionId `String` - The ID of the shield information barrier segment Restriction. Example: "4563" headers `DeleteShieldInformationBarrierSegmentRestrictionByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentRestrictionById method ### Returns This function returns a value of type `void`. Empty body in response. ## List shield information barrier segment restrictions Lists shield information barrier segment restrictions based on provided segment ID. This operation is performed by calling function `getShieldInformationBarrierSegmentRestrictions`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segment-restrictions/). ``` client.getShieldInformationBarrierSegmentRestrictions().getShieldInformationBarrierSegmentRestrictions(new GetShieldInformationBarrierSegmentRestrictionsQueryParams(segmentId)) ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentRestrictionsQueryParams` - Query parameters of getShieldInformationBarrierSegmentRestrictions method headers `GetShieldInformationBarrierSegmentRestrictionsHeaders` - Headers of getShieldInformationBarrierSegmentRestrictions method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestrictions`. Returns a paginated list of shield information barrier segment restriction objects. ## Create shield information barrier segment restriction Creates a shield information barrier segment restriction object. This operation is performed by calling function `createShieldInformationBarrierSegmentRestriction`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segment-restrictions/). ``` client.getShieldInformationBarrierSegmentRestrictions().createShieldInformationBarrierSegmentRestriction(new CreateShieldInformationBarrierSegmentRestrictionRequestBody.Builder(new CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentField.Builder().id(segmentId).type(CreateShieldInformationBarrierSegmentRestrictionRequestBodyShieldInformationBarrierSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT).build(), new CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentField.Builder().id(segmentToRestrictId).type(CreateShieldInformationBarrierSegmentRestrictionRequestBodyRestrictedSegmentTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT).build()).type(CreateShieldInformationBarrierSegmentRestrictionRequestBodyTypeField.SHIELD_INFORMATION_BARRIER_SEGMENT_RESTRICTION).build()) ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentRestrictionRequestBody` - Request body of createShieldInformationBarrierSegmentRestriction method headers `CreateShieldInformationBarrierSegmentRestrictionHeaders` - Headers of createShieldInformationBarrierSegmentRestriction method ### Returns This function returns a value of type `ShieldInformationBarrierSegmentRestriction`. Returns the newly created Shield Information Barrier Segment Restriction object. --- ## Untitled *Type: page* ShieldListsManager Get all shield lists in enterprise Create shield list Get single shield list by shield list id Delete single shield list… # ShieldListsManager - [Get all shield lists in enterprise](#get-all-shield-lists-in-enterprise) - [Create shield list](#create-shield-list) - [Get single shield list by shield list id](#get-single-shield-list-by-shield-list-id) - [Delete single shield list by shield list id](#delete-single-shield-list-by-shield-list-id) - [Update shield list](#update-shield-list) ## Get all shield lists in enterprise Retrieves all shield lists in the enterprise. This operation is performed by calling function `getShieldListsV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists/). ``` client.getShieldLists().getShieldListsV2025R0() ``` ### Arguments headers `GetShieldListsV2025R0Headers` - Headers of getShieldListsV2025R0 method ### Returns This function returns a value of type `ShieldListsV2025R0`. Returns the list of shield list objects. ## Create shield list Creates a shield list. This operation is performed by calling function `createShieldListV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/post-shield-lists/). ``` client.getShieldLists().createShieldListV2025R0(new ShieldListsCreateV2025R0.Builder(shieldListCountryName, new ShieldListContentCountryV2025R0.Builder(Arrays.asList("US", "PL")).type(ShieldListContentCountryV2025R0TypeField.COUNTRY).build()).description("A list of things that are shielded").build()) ``` ### Arguments requestBody `ShieldListsCreateV2025R0` - Request body of createShieldListV2025R0 method headers `CreateShieldListV2025R0Headers` - Headers of createShieldListV2025R0 method ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Get single shield list by shield list id Retrieves a single shield list by its ID. This operation is performed by calling function `getShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/get-shield-lists-id/). ``` client.getShieldLists().getShieldListByIdV2025R0(shieldListCountry.getId()) ``` ### Arguments shieldListId `String` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " headers `GetShieldListByIdV2025R0Headers` - Headers of getShieldListByIdV2025R0 method ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. ## Delete single shield list by shield list id Delete a single shield list by its ID. This operation is performed by calling function `deleteShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/delete-shield-lists-id/). ``` client.getShieldLists().deleteShieldListByIdV2025R0(shieldListCountry.getId()) ``` ### Arguments shieldListId `String` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " headers `DeleteShieldListByIdV2025R0Headers` - Headers of deleteShieldListByIdV2025R0 method ### Returns This function returns a value of type `void`. Shield List correctly removed. No content in response. ## Update shield list Updates a shield list. This operation is performed by calling function `updateShieldListByIdV2025R0`. See the endpoint docs at [API Reference](https://developer.box.com/reference/v2025.0/put-shield-lists-id/). ``` client.getShieldLists().updateShieldListByIdV2025R0(shieldListCountry.getId(), new ShieldListsUpdateV2025R0.Builder(shieldListCountryName, new ShieldListContentCountryV2025R0.Builder(Arrays.asList("US")).type(ShieldListContentCountryV2025R0TypeField.COUNTRY).build()).description("Updated description").build()) ``` ### Arguments shieldListId `String` - The unique identifier that represents a shield list. The ID for any Shield List can be determined by the response from the endpoint fetching all shield lists for the enterprise. Example: "90fb0e17-c332-40ed-b4f9-fa8908fbbb24 " requestBody `ShieldListsUpdateV2025R0` - Request body of updateShieldListByIdV2025R0 method headers `UpdateShieldListByIdV2025R0Headers` - Headers of updateShieldListByIdV2025R0 method ### Returns This function returns a value of type `ShieldListV2025R0`. Returns the shield list object. --- ## Untitled *Type: page* ShieldInformationBarrierSegmentsManager Get shield information barrier segment with specified ID Delete shield information barrier segment… # ShieldInformationBarrierSegmentsManager - [Get shield information barrier segment with specified ID](#get-shield-information-barrier-segment-with-specified-id) - [Delete shield information barrier segment](#delete-shield-information-barrier-segment) - [Update shield information barrier segment with specified ID](#update-shield-information-barrier-segment-with-specified-id) - [List shield information barrier segments](#list-shield-information-barrier-segments) - [Create shield information barrier segment](#create-shield-information-barrier-segment) ## Get shield information barrier segment with specified ID Retrieves shield information barrier segment based on provided ID.. This operation is performed by calling function `getShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments-id/). ``` client.getShieldInformationBarrierSegments().getShieldInformationBarrierSegmentById(segmentId) ``` ### Arguments shieldInformationBarrierSegmentId `String` - The ID of the shield information barrier segment. Example: "3423" headers `GetShieldInformationBarrierSegmentByIdHeaders` - Headers of getShieldInformationBarrierSegmentById method ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the shield information barrier segment object. ## Delete shield information barrier segment Deletes the shield information barrier segment based on provided ID. This operation is performed by calling function `deleteShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-shield-information-barrier-segments-id/). ``` client.getShieldInformationBarrierSegments().deleteShieldInformationBarrierSegmentById(segmentId) ``` ### Arguments shieldInformationBarrierSegmentId `String` - The ID of the shield information barrier segment. Example: "3423" headers `DeleteShieldInformationBarrierSegmentByIdHeaders` - Headers of deleteShieldInformationBarrierSegmentById method ### Returns This function returns a value of type `void`. Empty body in response. ## Update shield information barrier segment with specified ID Updates the shield information barrier segment based on provided ID.. This operation is performed by calling function `updateShieldInformationBarrierSegmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-shield-information-barrier-segments-id/). ``` client.getShieldInformationBarrierSegments().updateShieldInformationBarrierSegmentById(segmentId, new UpdateShieldInformationBarrierSegmentByIdRequestBody.Builder().description(updatedSegmentDescription).build()) ``` ### Arguments shieldInformationBarrierSegmentId `String` - The ID of the shield information barrier segment. Example: "3423" requestBody `UpdateShieldInformationBarrierSegmentByIdRequestBody` - Request body of updateShieldInformationBarrierSegmentById method headers `UpdateShieldInformationBarrierSegmentByIdHeaders` - Headers of updateShieldInformationBarrierSegmentById method ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns the updated shield information barrier segment object. ## List shield information barrier segments Retrieves a list of shield information barrier segment objects for the specified Information Barrier ID. This operation is performed by calling function `getShieldInformationBarrierSegments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-shield-information-barrier-segments/). ``` client.getShieldInformationBarrierSegments().getShieldInformationBarrierSegments(new GetShieldInformationBarrierSegmentsQueryParams(barrierId)) ``` ### Arguments queryParams `GetShieldInformationBarrierSegmentsQueryParams` - Query parameters of getShieldInformationBarrierSegments method headers `GetShieldInformationBarrierSegmentsHeaders` - Headers of getShieldInformationBarrierSegments method ### Returns This function returns a value of type `ShieldInformationBarrierSegments`. Returns a paginated list of shield information barrier segment objects. ## Create shield information barrier segment Creates a shield information barrier segment. This operation is performed by calling function `createShieldInformationBarrierSegment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-shield-information-barrier-segments/). ``` client.getShieldInformationBarrierSegments().createShieldInformationBarrierSegment(new CreateShieldInformationBarrierSegmentRequestBody.Builder(new ShieldInformationBarrierBase.Builder().id(barrierId).type(ShieldInformationBarrierBaseTypeField.SHIELD_INFORMATION_BARRIER).build(), segmentName).description(segmentDescription).build()) ``` ### Arguments requestBody `CreateShieldInformationBarrierSegmentRequestBody` - Request body of createShieldInformationBarrierSegment method headers `CreateShieldInformationBarrierSegmentHeaders` - Headers of createShieldInformationBarrierSegment method ### Returns This function returns a value of type `ShieldInformationBarrierSegment`. Returns a new shield information barrier segment object. --- ## Untitled *Type: page* SignRequestsManager Cancel Box Sign request Resend Box Sign request Get Box Sign request by ID List Box Sign requests Create Box Sign… # SignRequestsManager - [Cancel Box Sign request](#cancel-box-sign-request) - [Resend Box Sign request](#resend-box-sign-request) - [Get Box Sign request by ID](#get-box-sign-request-by-id) - [List Box Sign requests](#list-box-sign-requests) - [Create Box Sign request](#create-box-sign-request) ## Cancel Box Sign request Cancels a sign request. This operation is performed by calling function `cancelSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-cancel/). ``` client.getSignRequests().cancelSignRequest(createdSignRequest.getId()) ``` ### Arguments signRequestId `String` - The ID of the signature request. Example: "33243242" headers `CancelSignRequestHeaders` - Headers of cancelSignRequest method ### Returns This function returns a value of type `SignRequest`. Returns a Sign Request object. ## Resend Box Sign request Resends a signature request email to all outstanding signers. This operation is performed by calling function `resendSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests-id-resend/). *Currently we don't have an example for calling `resendSignRequest` in integration tests* ### Arguments signRequestId `String` - The ID of the signature request. Example: "33243242" headers `ResendSignRequestHeaders` - Headers of resendSignRequest method ### Returns This function returns a value of type `void`. Returns an empty response when the API call was successful. The email notifications will be sent asynchronously. ## Get Box Sign request by ID Gets a sign request by ID. This operation is performed by calling function `getSignRequestById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests-id/). ``` client.getSignRequests().getSignRequestById(createdSignRequest.getId()) ``` ### Arguments signRequestId `String` - The ID of the signature request. Example: "33243242" headers `GetSignRequestByIdHeaders` - Headers of getSignRequestById method ### Returns This function returns a value of type `SignRequest`. Returns a signature request. ## List Box Sign requests Gets signature requests created by a user. If the `sign_files` and/or `parent_folder` are deleted, the signature request will not return in the list. This operation is performed by calling function `getSignRequests`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-requests/). ``` client.getSignRequests().getSignRequests() ``` ### Arguments queryParams `GetSignRequestsQueryParams` - Query parameters of getSignRequests method headers `GetSignRequestsHeaders` - Headers of getSignRequests method ### Returns This function returns a value of type `SignRequests`. Returns a collection of sign requests. ## Create Box Sign request Creates a signature request. This involves preparing a document for signing and sending the signature request to signers. This operation is performed by calling function `createSignRequest`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-sign-requests/). ``` client.getSignRequests().createSignRequest(new SignRequestCreateRequest.Builder(Arrays.asList(new SignRequestCreateSigner.Builder().email(signerEmail).role(SignRequestCreateSignerRoleField.SIGNER).isInPerson(false).embedUrlExternalUserId("123").declinedRedirectUrl("https://www.box.com").loginRequired(false).password("password").suppressNotifications(true).build())).sourceFiles(Arrays.asList(new FileBase(fileToSign.getId()))).parentFolder(new FolderMini(destinationFolder.getId())).isDocumentPreparationNeeded(false).redirectUrl("https://www.box.com").declinedRedirectUrl("https://www.box.com").areTextSignaturesEnabled(true).emailSubject("Sign this document").emailMessage("Please sign this document").areRemindersEnabled(true).name("Sign Request").prefillTags(Arrays.asList(new SignRequestPrefillTag.Builder().documentTagId("0").dateValue(dateFromString("2035-01-01")).build())).daysValid(30L).externalId("123").externalSystemName("BoxSignIntegration").build()) ``` ### Arguments requestBody `SignRequestCreateRequest` - Request body of createSignRequest method headers `CreateSignRequestHeaders` - Headers of createSignRequest method ### Returns This function returns a value of type `SignRequest`. Returns a Box Sign request object. --- ## Untitled *Type: page* SignTemplatesManager List Box Sign templates Get Box Sign template by ID List Box Sign templates Gets Box Sign templates created by a user… # SignTemplatesManager - [List Box Sign templates](#list-box-sign-templates) - [Get Box Sign template by ID](#get-box-sign-template-by-id) ## List Box Sign templates Gets Box Sign templates created by a user. This operation is performed by calling function `getSignTemplates`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates/). ``` client.getSignTemplates().getSignTemplates(new GetSignTemplatesQueryParams.Builder().limit(2L).build()) ``` ### Arguments queryParams `GetSignTemplatesQueryParams` - Query parameters of getSignTemplates method headers `GetSignTemplatesHeaders` - Headers of getSignTemplates method ### Returns This function returns a value of type `SignTemplates`. Returns a collection of templates. ## Get Box Sign template by ID Fetches details of a specific Box Sign template. This operation is performed by calling function `getSignTemplateById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-sign-templates-id/). ``` client.getSignTemplates().getSignTemplateById(signTemplates.getEntries().get(0).getId()) ``` ### Arguments templateId `String` - The ID of a Box Sign template. Example: "123075213-7d117509-8f05-42e4-a5ef-5190a319d41d" headers `GetSignTemplateByIdHeaders` - Headers of getSignTemplateById method ### Returns This function returns a value of type `SignTemplate`. Returns details of a template. --- ## Untitled *Type: page* StoragePoliciesManager List storage policies Get storage policy List storage policies Fetches all the storage policies in the enterprise… # StoragePoliciesManager - [List storage policies](#list-storage-policies) - [Get storage policy](#get-storage-policy) ## List storage policies Fetches all the storage policies in the enterprise. This operation is performed by calling function `getStoragePolicies`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies/). ``` client.getStoragePolicies().getStoragePolicies() ``` ### Arguments queryParams `GetStoragePoliciesQueryParams` - Query parameters of getStoragePolicies method headers `GetStoragePoliciesHeaders` - Headers of getStoragePolicies method ### Returns This function returns a value of type `StoragePolicies`. Returns a collection of storage policies. ## Get storage policy Fetches a specific storage policy. This operation is performed by calling function `getStoragePolicyById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policies-id/). ``` client.getStoragePolicies().getStoragePolicyById(storagePolicy.getId()) ``` ### Arguments storagePolicyId `String` - The ID of the storage policy. Example: "34342" headers `GetStoragePolicyByIdHeaders` - Headers of getStoragePolicyById method ### Returns This function returns a value of type `StoragePolicy`. Returns a storage policy object. --- ## Untitled *Type: page* SkillsManager List Box Skill cards on file Create Box Skill cards on file Update Box Skill cards on file Remove Box Skill cards from file… # SkillsManager - [List Box Skill cards on file](#list-box-skill-cards-on-file) - [Create Box Skill cards on file](#create-box-skill-cards-on-file) - [Update Box Skill cards on file](#update-box-skill-cards-on-file) - [Remove Box Skill cards from file](#remove-box-skill-cards-from-file) - [Update all Box Skill cards on file](#update-all-box-skill-cards-on-file) ## List Box Skill cards on file List the Box Skills metadata cards that are attached to a file. This operation is performed by calling function `getBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-metadata-global-boxSkillsCards/). ``` client.getSkills().getBoxSkillCardsOnFile(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetBoxSkillCardsOnFileHeaders` - Headers of getBoxSkillCardsOnFile method ### Returns This function returns a value of type `SkillCardsMetadata`. Returns all the metadata associated with a file. This API does not support pagination and will therefore always return all of the metadata associated to the file. ## Create Box Skill cards on file Applies one or more Box Skills metadata cards to a file. This operation is performed by calling function `createBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-metadata-global-boxSkillsCards/). ``` client.getSkills().createBoxSkillCardsOnFile(file.getId(), new CreateBoxSkillCardsOnFileRequestBody(cardsToCreate)) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `CreateBoxSkillCardsOnFileRequestBody` - Request body of createBoxSkillCardsOnFile method headers `CreateBoxSkillCardsOnFileHeaders` - Headers of createBoxSkillCardsOnFile method ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the instance of the template that was applied to the file, including the data that was applied to the template. ## Update Box Skill cards on file Updates one or more Box Skills metadata cards to a file. This operation is performed by calling function `updateBoxSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-files-id-metadata-global-boxSkillsCards/). ``` client.getSkills().updateBoxSkillCardsOnFile(file.getId(), Arrays.asList(new UpdateBoxSkillCardsOnFileRequestBody.Builder().op(UpdateBoxSkillCardsOnFileRequestBodyOpField.REPLACE).path("/cards/0").value(cardToUpdate).build())) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `List<UpdateBoxSkillCardsOnFileRequestBody>` - Request body of updateBoxSkillCardsOnFile method headers `UpdateBoxSkillCardsOnFileHeaders` - Headers of updateBoxSkillCardsOnFile method ### Returns This function returns a value of type `SkillCardsMetadata`. Returns the updated metadata template, with the custom template data included. ## Remove Box Skill cards from file Removes any Box Skills cards metadata from a file. This operation is performed by calling function `deleteBoxSkillCardsFromFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-metadata-global-boxSkillsCards/). ``` client.getSkills().deleteBoxSkillCardsFromFile(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteBoxSkillCardsFromFileHeaders` - Headers of deleteBoxSkillCardsFromFile method ### Returns This function returns a value of type `void`. Returns an empty response when the cards are successfully deleted. ## Update all Box Skill cards on file An alternative method that can be used to overwrite and update all Box Skill metadata cards on a file. This operation is performed by calling function `updateAllSkillCardsOnFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-skill-invocations-id/). *Currently we don't have an example for calling `updateAllSkillCardsOnFile` in integration tests* ### Arguments skillId `String` - The ID of the skill to apply this metadata for. Example: "33243242" requestBody `UpdateAllSkillCardsOnFileRequestBody` - Request body of updateAllSkillCardsOnFile method headers `UpdateAllSkillCardsOnFileHeaders` - Headers of updateAllSkillCardsOnFile method ### Returns This function returns a value of type `void`. Returns an empty response when the card has been successfully updated. --- ## Untitled *Type: page* StoragePolicyAssignmentsManager List storage policy assignments Assign storage policy Get storage policy assignment Update storage policy… # StoragePolicyAssignmentsManager - [List storage policy assignments](#list-storage-policy-assignments) - [Assign storage policy](#assign-storage-policy) - [Get storage policy assignment](#get-storage-policy-assignment) - [Update storage policy assignment](#update-storage-policy-assignment) - [Unassign storage policy](#unassign-storage-policy) ## List storage policy assignments Fetches all the storage policy assignment for an enterprise or user. This operation is performed by calling function `getStoragePolicyAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments/). ``` client.getStoragePolicyAssignments().getStoragePolicyAssignments(new GetStoragePolicyAssignmentsQueryParams(GetStoragePolicyAssignmentsQueryParamsResolvedForTypeField.USER, userId)) ``` ### Arguments queryParams `GetStoragePolicyAssignmentsQueryParams` - Query parameters of getStoragePolicyAssignments method headers `GetStoragePolicyAssignmentsHeaders` - Headers of getStoragePolicyAssignments method ### Returns This function returns a value of type `StoragePolicyAssignments`. Returns a collection of storage policies for the enterprise or user. ## Assign storage policy Creates a storage policy assignment for an enterprise or user. This operation is performed by calling function `createStoragePolicyAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-storage-policy-assignments/). ``` client.getStoragePolicyAssignments().createStoragePolicyAssignment(new CreateStoragePolicyAssignmentRequestBody(new CreateStoragePolicyAssignmentRequestBodyStoragePolicyField(policyId), new CreateStoragePolicyAssignmentRequestBodyAssignedToField(CreateStoragePolicyAssignmentRequestBodyAssignedToTypeField.USER, userId))) ``` ### Arguments requestBody `CreateStoragePolicyAssignmentRequestBody` - Request body of createStoragePolicyAssignment method headers `CreateStoragePolicyAssignmentHeaders` - Headers of createStoragePolicyAssignment method ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns the new storage policy assignment created. ## Get storage policy assignment Fetches a specific storage policy assignment. This operation is performed by calling function `getStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-storage-policy-assignments-id/). ``` client.getStoragePolicyAssignments().getStoragePolicyAssignmentById(storagePolicyAssignment.getId()) ``` ### Arguments storagePolicyAssignmentId `String` - The ID of the storage policy assignment. Example: "932483" headers `GetStoragePolicyAssignmentByIdHeaders` - Headers of getStoragePolicyAssignmentById method ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns a storage policy assignment object. ## Update storage policy assignment Updates a specific storage policy assignment. This operation is performed by calling function `updateStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-storage-policy-assignments-id/). ``` client.getStoragePolicyAssignments().updateStoragePolicyAssignmentById(storagePolicyAssignment.getId(), new UpdateStoragePolicyAssignmentByIdRequestBody(new UpdateStoragePolicyAssignmentByIdRequestBodyStoragePolicyField(storagePolicy2.getId()))) ``` ### Arguments storagePolicyAssignmentId `String` - The ID of the storage policy assignment. Example: "932483" requestBody `UpdateStoragePolicyAssignmentByIdRequestBody` - Request body of updateStoragePolicyAssignmentById method headers `UpdateStoragePolicyAssignmentByIdHeaders` - Headers of updateStoragePolicyAssignmentById method ### Returns This function returns a value of type `StoragePolicyAssignment`. Returns an updated storage policy assignment object. ## Unassign storage policy Delete a storage policy assignment. Deleting a storage policy assignment on a user will have the user inherit the enterprise's default storage policy. There is a rate limit for calling this endpoint of only twice per user in a 24 hour time frame. This operation is performed by calling function `deleteStoragePolicyAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-storage-policy-assignments-id/). ``` client.getStoragePolicyAssignments().deleteStoragePolicyAssignmentById(storagePolicyAssignment.getId()) ``` ### Arguments storagePolicyAssignmentId `String` - The ID of the storage policy assignment. Example: "932483" headers `DeleteStoragePolicyAssignmentByIdHeaders` - Headers of deleteStoragePolicyAssignmentById method ### Returns This function returns a value of type `void`. Returns an empty response when the storage policy assignment is successfully deleted. --- ## Untitled *Type: page* TasksManager List tasks on file Create task Get task Update task Remove task List tasks on file Retrieves a list of all the tasks for a file… # TasksManager - [List tasks on file](#list-tasks-on-file) - [Create task](#create-task) - [Get task](#get-task) - [Update task](#update-task) - [Remove task](#remove-task) ## List tasks on file Retrieves a list of all the tasks for a file. This endpoint does not support pagination. This operation is performed by calling function `getFileTasks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-tasks/). ``` client.getTasks().getFileTasks(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `GetFileTasksHeaders` - Headers of getFileTasks method ### Returns This function returns a value of type `Tasks`. Returns a list of tasks on a file. If there are no tasks on this file an empty collection is returned instead. ## Create task Creates a single task on a file. This task is not assigned to any user and will need to be assigned separately. This operation is performed by calling function `createTask`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-tasks/). ``` client.getTasks().createTask(new CreateTaskRequestBody.Builder(new CreateTaskRequestBodyItemField.Builder().id(file.getId()).type(CreateTaskRequestBodyItemTypeField.FILE).build()).action(CreateTaskRequestBodyActionField.REVIEW).message("test message").dueAt(dateTime).completionRule(CreateTaskRequestBodyCompletionRuleField.ALL_ASSIGNEES).build()) ``` ### Arguments requestBody `CreateTaskRequestBody` - Request body of createTask method headers `CreateTaskHeaders` - Headers of createTask method ### Returns This function returns a value of type `Task`. Returns the newly created task. ## Get task Retrieves information about a specific task. This operation is performed by calling function `getTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id/). ``` client.getTasks().getTaskById(task.getId()) ``` ### Arguments taskId `String` - The ID of the task. Example: "12345" headers `GetTaskByIdHeaders` - Headers of getTaskById method ### Returns This function returns a value of type `Task`. Returns a task object. ## Update task Updates a task. This can be used to update a task's configuration, or to update its completion state. This operation is performed by calling function `updateTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-tasks-id/). ``` client.getTasks().updateTaskById(task.getId(), new UpdateTaskByIdRequestBody.Builder().message("updated message").build()) ``` ### Arguments taskId `String` - The ID of the task. Example: "12345" requestBody `UpdateTaskByIdRequestBody` - Request body of updateTaskById method headers `UpdateTaskByIdHeaders` - Headers of updateTaskById method ### Returns This function returns a value of type `Task`. Returns the updated task object. ## Remove task Removes a task from a file. This operation is performed by calling function `deleteTaskById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-tasks-id/). ``` client.getTasks().deleteTaskById(task.getId()) ``` ### Arguments taskId `String` - The ID of the task. Example: "12345" headers `DeleteTaskByIdHeaders` - Headers of deleteTaskById method ### Returns This function returns a value of type `void`. Returns an empty response when the task was successfully deleted. --- ## Untitled *Type: page* TaskAssignmentsManager List task assignments Assign task Get task assignment Update task assignment Unassign task List task assignments… # TaskAssignmentsManager - [List task assignments](#list-task-assignments) - [Assign task](#assign-task) - [Get task assignment](#get-task-assignment) - [Update task assignment](#update-task-assignment) - [Unassign task](#unassign-task) ## List task assignments Lists all of the assignments for a given task. This operation is performed by calling function `getTaskAssignments`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-tasks-id-assignments/). ``` client.getTaskAssignments().getTaskAssignments(task.getId()) ``` ### Arguments taskId `String` - The ID of the task. Example: "12345" headers `GetTaskAssignmentsHeaders` - Headers of getTaskAssignments method ### Returns This function returns a value of type `TaskAssignments`. Returns a collection of task assignment defining what task on a file has been assigned to which users and by who. ## Assign task Assigns a task to a user. A task can be assigned to more than one user by creating multiple assignments. This operation is performed by calling function `createTaskAssignment`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-task-assignments/). ``` client.getTaskAssignments().createTaskAssignment(new CreateTaskAssignmentRequestBody(new CreateTaskAssignmentRequestBodyTaskField.Builder(task.getId()).type(CreateTaskAssignmentRequestBodyTaskTypeField.TASK).build(), new CreateTaskAssignmentRequestBodyAssignToField.Builder().id(currentUser.getId()).build())) ``` ### Arguments requestBody `CreateTaskAssignmentRequestBody` - Request body of createTaskAssignment method headers `CreateTaskAssignmentHeaders` - Headers of createTaskAssignment method ### Returns This function returns a value of type `TaskAssignment`. Returns a new task assignment object. ## Get task assignment Retrieves information about a task assignment. This operation is performed by calling function `getTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-task-assignments-id/). ``` client.getTaskAssignments().getTaskAssignmentById(taskAssignment.getId()) ``` ### Arguments taskAssignmentId `String` - The ID of the task assignment. Example: "12345" headers `GetTaskAssignmentByIdHeaders` - Headers of getTaskAssignmentById method ### Returns This function returns a value of type `TaskAssignment`. Returns a task assignment, specifying who the task has been assigned to and by whom. ## Update task assignment Updates a task assignment. This endpoint can be used to update the state of a task assigned to a user. This operation is performed by calling function `updateTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-task-assignments-id/). ``` client.getTaskAssignments().updateTaskAssignmentById(taskAssignment.getId(), new UpdateTaskAssignmentByIdRequestBody.Builder().message("updated message").resolutionState(UpdateTaskAssignmentByIdRequestBodyResolutionStateField.APPROVED).build()) ``` ### Arguments taskAssignmentId `String` - The ID of the task assignment. Example: "12345" requestBody `UpdateTaskAssignmentByIdRequestBody` - Request body of updateTaskAssignmentById method headers `UpdateTaskAssignmentByIdHeaders` - Headers of updateTaskAssignmentById method ### Returns This function returns a value of type `TaskAssignment`. Returns the updated task assignment object. ## Unassign task Deletes a specific task assignment. This operation is performed by calling function `deleteTaskAssignmentById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-task-assignments-id/). ``` client.getTaskAssignments().deleteTaskAssignmentById(taskAssignment.getId()) ``` ### Arguments taskAssignmentId `String` - The ID of the task assignment. Example: "12345" headers `DeleteTaskAssignmentByIdHeaders` - Headers of deleteTaskAssignmentById method ### Returns This function returns a value of type `void`. Returns an empty response when the task assignment was successfully deleted. --- ## Untitled *Type: page* TermsOfServicesManager List terms of services Create terms of service Get terms of service Update terms of service List terms of services… # TermsOfServicesManager - [List terms of services](#list-terms-of-services) - [Create terms of service](#create-terms-of-service) - [Get terms of service](#get-terms-of-service) - [Update terms of service](#update-terms-of-service) ## List terms of services Returns the current terms of service text and settings for the enterprise. This operation is performed by calling function `getTermsOfService`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services/). ``` client.getTermsOfServices().getTermsOfService() ``` ### Arguments queryParams `GetTermsOfServiceQueryParams` - Query parameters of getTermsOfService method headers `GetTermsOfServiceHeaders` - Headers of getTermsOfService method ### Returns This function returns a value of type `TermsOfServices`. Returns a collection of terms of service text and settings for the enterprise. ## Create terms of service Creates a terms of service for a given enterprise and type of user. This operation is performed by calling function `createTermsOfService`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-services/). ``` client.getTermsOfServices().createTermsOfService(new CreateTermsOfServiceRequestBody.Builder(CreateTermsOfServiceRequestBodyStatusField.DISABLED, "Test TOS").tosType(CreateTermsOfServiceRequestBodyTosTypeField.MANAGED).build()) ``` ### Arguments requestBody `CreateTermsOfServiceRequestBody` - Request body of createTermsOfService method headers `CreateTermsOfServiceHeaders` - Headers of createTermsOfService method ### Returns This function returns a value of type `TermsOfService`. Returns a new task object. ## Get terms of service Fetches a specific terms of service. This operation is performed by calling function `getTermsOfServiceById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-services-id/). *Currently we don't have an example for calling `getTermsOfServiceById` in integration tests* ### Arguments termsOfServiceId `String` - The ID of the terms of service. Example: "324234" headers `GetTermsOfServiceByIdHeaders` - Headers of getTermsOfServiceById method ### Returns This function returns a value of type `TermsOfService`. Returns a terms of service object. ## Update terms of service Updates a specific terms of service. This operation is performed by calling function `updateTermsOfServiceById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-services-id/). ``` client.getTermsOfServices().updateTermsOfServiceById(tos.getId(), new UpdateTermsOfServiceByIdRequestBody(UpdateTermsOfServiceByIdRequestBodyStatusField.DISABLED, "TOS")) ``` ### Arguments termsOfServiceId `String` - The ID of the terms of service. Example: "324234" requestBody `UpdateTermsOfServiceByIdRequestBody` - Request body of updateTermsOfServiceById method headers `UpdateTermsOfServiceByIdHeaders` - Headers of updateTermsOfServiceById method ### Returns This function returns a value of type `TermsOfService`. Returns an updated terms of service object. --- ## Untitled *Type: page* TransferManager Transfer owned folders Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into… # TransferManager - [Transfer owned folders](#transfer-owned-folders) ## Transfer owned folders Move all of the items (files, folders and workflows) owned by a user into another user's account Only the root folder (`0`) can be transferred. Folders can only be moved across users by users with administrative permissions. All existing shared links and folder-level collaborations are transferred during the operation. Please note that while collaborations at the individual file-level are transferred during the operation, the collaborations are deleted when the original user is deleted. If the user has a large number of items across all folders, the call will be run asynchronously. If the operation is not completed within 10 minutes, the user will receive a 200 OK response, and the operation will continue running. If the destination path has a metadata cascade policy attached to any of the parent folders, a metadata cascade operation will be kicked off asynchronously. There is currently no way to check for when this operation is finished. The destination folder's name will be in the format `{User}'s Files and Folders`, where `{User}` is the display name of the user. To make this API call your application will need to have the "Read and write all files and folders stored in Box" scope enabled. Please make sure the destination user has access to `Relay` or `Relay Lite`, and has access to the files and folders involved in the workflows being transferred. Admins will receive an email when the operation is completed. This operation is performed by calling function `transferOwnedFolder`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id-folders-0/). ``` client.getTransfer().transferOwnedFolder(sourceUser.getId(), new TransferOwnedFolderRequestBody(new TransferOwnedFolderRequestBodyOwnedByField(targetUser.getId())), new TransferOwnedFolderQueryParams.Builder().notify(false).build()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" requestBody `TransferOwnedFolderRequestBody` - Request body of transferOwnedFolder method queryParams `TransferOwnedFolderQueryParams` - Query parameters of transferOwnedFolder method headers `TransferOwnedFolderHeaders` - Headers of transferOwnedFolder method ### Returns This function returns a value of type `FolderFull`. Returns the information for the newly created destination folder. --- ## Untitled *Type: page* TermsOfServiceUserStatusesManager List terms of service user statuses Create terms of service status for new user Update terms of service… # TermsOfServiceUserStatusesManager - [List terms of service user statuses](#list-terms-of-service-user-statuses) - [Create terms of service status for new user](#create-terms-of-service-status-for-new-user) - [Update terms of service status for existing user](#update-terms-of-service-status-for-existing-user) ## List terms of service user statuses Retrieves an overview of users and their status for a terms of service, including Whether they have accepted the terms and when. This operation is performed by calling function `getTermsOfServiceUserStatuses`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-terms-of-service-user-statuses/). ``` client.getTermsOfServiceUserStatuses().getTermsOfServiceUserStatuses(new GetTermsOfServiceUserStatusesQueryParams.Builder(tos.getId()).userId(user.getId()).build()) ``` ### Arguments queryParams `GetTermsOfServiceUserStatusesQueryParams` - Query parameters of getTermsOfServiceUserStatuses method headers `GetTermsOfServiceUserStatusesHeaders` - Headers of getTermsOfServiceUserStatuses method ### Returns This function returns a value of type `TermsOfServiceUserStatuses`. Returns a list of terms of service statuses. ## Create terms of service status for new user Sets the status for a terms of service for a user. This operation is performed by calling function `createTermsOfServiceStatusForUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-terms-of-service-user-statuses/). ``` client.getTermsOfServiceUserStatuses().createTermsOfServiceStatusForUser(new CreateTermsOfServiceStatusForUserRequestBody(new CreateTermsOfServiceStatusForUserRequestBodyTosField(tos.getId()), new CreateTermsOfServiceStatusForUserRequestBodyUserField(user.getId()), false)) ``` ### Arguments requestBody `CreateTermsOfServiceStatusForUserRequestBody` - Request body of createTermsOfServiceStatusForUser method headers `CreateTermsOfServiceStatusForUserHeaders` - Headers of createTermsOfServiceStatusForUser method ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns a terms of service status object. ## Update terms of service status for existing user Updates the status for a terms of service for a user. This operation is performed by calling function `updateTermsOfServiceStatusForUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-terms-of-service-user-statuses-id/). ``` client.getTermsOfServiceUserStatuses().updateTermsOfServiceStatusForUserById(createdTosUserStatus.getId(), new UpdateTermsOfServiceStatusForUserByIdRequestBody(true)) ``` ### Arguments termsOfServiceUserStatusId `String` - The ID of the terms of service status. Example: "324234" requestBody `UpdateTermsOfServiceStatusForUserByIdRequestBody` - Request body of updateTermsOfServiceStatusForUserById method headers `UpdateTermsOfServiceStatusForUserByIdHeaders` - Headers of updateTermsOfServiceStatusForUserById method ### Returns This function returns a value of type `TermsOfServiceUserStatus`. Returns the updated terms of service status object. --- ## Untitled *Type: page* TrashedFilesManager Restore file Get trashed file Permanently remove file Restore file Restores a file that has been moved to the trash. An… # TrashedFilesManager - [Restore file](#restore-file) - [Get trashed file](#get-trashed-file) - [Permanently remove file](#permanently-remove-file) ## Restore file Restores a file that has been moved to the trash. An optional new parent ID can be provided to restore the file to in case the original folder has been deleted. This operation is performed by calling function `restoreFileFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id/). ``` client.getTrashedFiles().restoreFileFromTrash(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `RestoreFileFromTrashRequestBody` - Request body of restoreFileFromTrash method queryParams `RestoreFileFromTrashQueryParams` - Query parameters of restoreFileFromTrash method headers `RestoreFileFromTrashHeaders` - Headers of restoreFileFromTrash method ### Returns This function returns a value of type `TrashFileRestored`. Returns a file object when the file has been restored. ## Get trashed file Retrieves a file that has been moved to the trash. Please note that only if the file itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `getTrashedFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-files-id-trash/). ``` client.getTrashedFiles().getTrashedFileById(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" queryParams `GetTrashedFileByIdQueryParams` - Query parameters of getTrashedFileById method headers `GetTrashedFileByIdHeaders` - Headers of getTrashedFileById method ### Returns This function returns a value of type `TrashFile`. Returns the file that was trashed, including information about when the it was moved to the trash. ## Permanently remove file Permanently deletes a file that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedFileById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-files-id-trash/). ``` client.getTrashedFiles().deleteTrashedFileById(file.getId()) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" headers `DeleteTrashedFileByIdHeaders` - Headers of deleteTrashedFileById method ### Returns This function returns a value of type `void`. Returns an empty response when the file was permanently deleted. --- ## Untitled *Type: page* TrashedItemsManager List trashed items List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute… # TrashedItemsManager - [List trashed items](#list-trashed-items) ## List trashed items Retrieves the files and folders that have been moved to the trash. Any attribute in the full files or folders objects can be passed in with the `fields` parameter to retrieve those specific attributes that are not returned by default. This endpoint defaults to use offset-based pagination, yet also supports marker-based pagination using the `marker` parameter. This operation is performed by calling function `getTrashedItems`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-trash-items/). ``` client.getTrashedItems().getTrashedItems() ``` ### Arguments queryParams `GetTrashedItemsQueryParams` - Query parameters of getTrashedItems method headers `GetTrashedItemsHeaders` - Headers of getTrashedItems method ### Returns This function returns a value of type `Items`. Returns a list of items that have been deleted. --- ## Untitled *Type: page* TrashedWebLinksManager Restore web link Get trashed web link Permanently remove web link Restore web link Restores a web link that has been… # TrashedWebLinksManager - [Restore web link](#restore-web-link) - [Get trashed web link](#get-trashed-web-link) - [Permanently remove web link](#permanently-remove-web-link) ## Restore web link Restores a web link that has been moved to the trash. An optional new parent ID can be provided to restore the web link to in case the original folder has been deleted. This operation is performed by calling function `restoreWeblinkFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links-id/). ``` client.getTrashedWebLinks().restoreWeblinkFromTrash(weblink.getId()) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `RestoreWeblinkFromTrashRequestBody` - Request body of restoreWeblinkFromTrash method queryParams `RestoreWeblinkFromTrashQueryParams` - Query parameters of restoreWeblinkFromTrash method headers `RestoreWeblinkFromTrashHeaders` - Headers of restoreWeblinkFromTrash method ### Returns This function returns a value of type `TrashWebLinkRestored`. Returns a web link object when it has been restored. ## Get trashed web link Retrieves a web link that has been moved to the trash. This operation is performed by calling function `getTrashedWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id-trash/). ``` client.getTrashedWebLinks().getTrashedWebLinkById(weblink.getId()) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" queryParams `GetTrashedWebLinkByIdQueryParams` - Query parameters of getTrashedWebLinkById method headers `GetTrashedWebLinkByIdHeaders` - Headers of getTrashedWebLinkById method ### Returns This function returns a value of type `TrashWebLink`. Returns the web link that was trashed, including information about when the it was moved to the trash. ## Permanently remove web link Permanently deletes a web link that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id-trash/). ``` client.getTrashedWebLinks().deleteTrashedWebLinkById(weblink.getId()) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" headers `DeleteTrashedWebLinkByIdHeaders` - Headers of deleteTrashedWebLinkById method ### Returns This function returns a value of type `void`. Returns an empty response when the web link was permanently deleted. --- ## Untitled *Type: page* TrashedFoldersManager Restore folder Get trashed folder Permanently remove folder Restore folder Restores a folder that has been moved to… # TrashedFoldersManager - [Restore folder](#restore-folder) - [Get trashed folder](#get-trashed-folder) - [Permanently remove folder](#permanently-remove-folder) ## Restore folder Restores a folder that has been moved to the trash. An optional new parent ID can be provided to restore the folder to in case the original folder has been deleted. During this operation, part of the file tree will be locked, mainly the source folder and all of its descendants, as well as the destination folder. For the duration of the operation, no other move, copy, delete, or restore operation can performed on any of the locked folders. This operation is performed by calling function `restoreFolderFromTrash`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-folders-id/). ``` client.getTrashedFolders().restoreFolderFromTrash(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" requestBody `RestoreFolderFromTrashRequestBody` - Request body of restoreFolderFromTrash method queryParams `RestoreFolderFromTrashQueryParams` - Query parameters of restoreFolderFromTrash method headers `RestoreFolderFromTrashHeaders` - Headers of restoreFolderFromTrash method ### Returns This function returns a value of type `TrashFolderRestored`. Returns a folder object when the folder has been restored. ## Get trashed folder Retrieves a folder that has been moved to the trash. Please note that only if the folder itself has been moved to the trash can it be retrieved with this API call. If instead one of its parent folders was moved to the trash, only that folder can be inspected using the [`GET /folders/:id/trash`](e://get_folders_id_trash) API. To list all items that have been moved to the trash, please use the [`GET /folders/trash/items`](e://get-folders-trash-items/) API. This operation is performed by calling function `getTrashedFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-folders-id-trash/). ``` client.getTrashedFolders().getTrashedFolderById(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" queryParams `GetTrashedFolderByIdQueryParams` - Query parameters of getTrashedFolderById method headers `GetTrashedFolderByIdHeaders` - Headers of getTrashedFolderById method ### Returns This function returns a value of type `TrashFolder`. Returns the folder that was trashed, including information about when the it was moved to the trash. ## Permanently remove folder Permanently deletes a folder that is in the trash. This action cannot be undone. This operation is performed by calling function `deleteTrashedFolderById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-folders-id-trash/). ``` client.getTrashedFolders().deleteTrashedFolderById(folder.getId()) ``` ### Arguments folderId `String` - The unique identifier that represent a folder. The ID for any folder can be determined by visiting this folder in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/folder/123` the `folder_id` is `123`. The root folder of a Box account is always represented by the ID `0`. Example: "12345" headers `DeleteTrashedFolderByIdHeaders` - Headers of deleteTrashedFolderById method ### Returns This function returns a value of type `void`. Returns an empty response when the folder was permanently deleted. --- ## Untitled *Type: page* UploadsManager Upload file version Preflight check before upload Upload file Upload a file with a preflight check Upload file version Update… # UploadsManager - [Upload file version](#upload-file-version) - [Preflight check before upload](#preflight-check-before-upload) - [Upload file](#upload-file) - [Upload a file with a preflight check](#upload-a-file-with-a-preflight-check) ## Upload file version Update a file's content. For file sizes over 50MB we recommend using the Chunk Upload APIs. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. This operation is performed by calling function `uploadFileVersion`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-id-content/). ``` client.getUploads().uploadFileVersion(uploadedFile.getId(), new UploadFileVersionRequestBody(new UploadFileVersionRequestBodyAttributesField(newFileVersionName), newFileContentStream)) ``` ### Arguments fileId `String` - The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345" requestBody `UploadFileVersionRequestBody` - Request body of uploadFileVersion method queryParams `UploadFileVersionQueryParams` - Query parameters of uploadFileVersion method headers `UploadFileVersionHeaders` - Headers of uploadFileVersion method ### Returns This function returns a value of type `Files`. Returns the new file object in a list. ## Preflight check before upload Performs a check to verify that a file will be accepted by Box before you upload the entire file. This operation is performed by calling function `preflightFileUploadCheck`. See the endpoint docs at [API Reference](https://developer.box.com/reference/options-files-content/). ``` client.getUploads().preflightFileUploadCheck(new PreflightFileUploadCheckRequestBody.Builder().name(newFileName).size(1024 * 1024).parent(new PreflightFileUploadCheckRequestBodyParentField.Builder().id("0").build()).build()) ``` ### Arguments requestBody `PreflightFileUploadCheckRequestBody` - Request body of preflightFileUploadCheck method headers `PreflightFileUploadCheckHeaders` - Headers of preflightFileUploadCheck method ### Returns This function returns a value of type `UploadUrl`. If the check passed, the response will include a session URL that can be used to upload the file to. ## Upload file Uploads a small file to Box. For file sizes over 50MB we recommend using the Chunk Upload APIs. The `attributes` part of the body must come **before** the `file` part. Requests that do not follow this format when uploading the file will receive a HTTP `400` error with a `metadata_after_file_contents` error code. This operation is performed by calling function `uploadFile`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-files-content/). ``` client.getUploads().uploadFile(new UploadFileRequestBody(new UploadFileRequestBodyAttributesField(newFileName, new UploadFileRequestBodyAttributesParentField("0")), fileContentStream)) ``` ### Arguments requestBody `UploadFileRequestBody` - Request body of uploadFile method queryParams `UploadFileQueryParams` - Query parameters of uploadFile method headers `UploadFileHeaders` - Headers of uploadFile method ### Returns This function returns a value of type `Files`. Returns the new file object in a list. ## Upload a file with a preflight check Upload a file with a preflight check This operation is performed by calling function `uploadWithPreflightCheck`. ``` client.getUploads().uploadWithPreflightCheck(new UploadWithPreflightCheckRequestBody(new UploadWithPreflightCheckRequestBodyAttributesField(newFileName, new UploadWithPreflightCheckRequestBodyAttributesParentField("0"), -1), fileContentStream)) ``` ### Arguments requestBody `UploadWithPreflightCheckRequestBody` queryParams `UploadWithPreflightCheckQueryParams` - Query parameters of uploadFile method headers `UploadWithPreflightCheckHeaders` - Headers of uploadFile method ### Returns This function returns a value of type `Files`. --- ## Untitled *Type: page* UserCollaborationsManager Get collaboration Update collaboration Remove collaboration Create collaboration Get collaboration Retrieves a… # UserCollaborationsManager - [Get collaboration](#get-collaboration) - [Update collaboration](#update-collaboration) - [Remove collaboration](#remove-collaboration) - [Create collaboration](#create-collaboration) ## Get collaboration Retrieves a single collaboration. This operation is performed by calling function `getCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-collaborations-id/). ``` client.getUserCollaborations().getCollaborationById(collaborationId) ``` ### Arguments collaborationId `String` - The ID of the collaboration. Example: "1234" queryParams `GetCollaborationByIdQueryParams` - Query parameters of getCollaborationById method headers `GetCollaborationByIdHeaders` - Headers of getCollaborationById method ### Returns This function returns a value of type `Collaboration`. Returns a collaboration object. ## Update collaboration Updates a collaboration. Can be used to change the owner of an item, or to accept collaboration invites. This operation is performed by calling function `updateCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-collaborations-id/). ``` client.getUserCollaborations().updateCollaborationById(collaborationId, new UpdateCollaborationByIdRequestBody(UpdateCollaborationByIdRequestBodyRoleField.VIEWER)) ``` ### Arguments collaborationId `String` - The ID of the collaboration. Example: "1234" requestBody `UpdateCollaborationByIdRequestBody` - Request body of updateCollaborationById method headers `UpdateCollaborationByIdHeaders` - Headers of updateCollaborationById method ### Returns This function returns a value of type `Collaboration`. Returns an updated collaboration object unless the owner has changed.If the role is changed to `owner`, the collaboration is deleted and a new collaboration is created. The previous `owner` of the old collaboration will be a `co-owner` on the new collaboration. ## Remove collaboration Deletes a single collaboration. This operation is performed by calling function `deleteCollaborationById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-collaborations-id/). ``` client.getUserCollaborations().deleteCollaborationById(collaborationId) ``` ### Arguments collaborationId `String` - The ID of the collaboration. Example: "1234" headers `DeleteCollaborationByIdHeaders` - Headers of deleteCollaborationById method ### Returns This function returns a value of type `void`. A blank response is returned if the collaboration was successfully deleted. ## Create collaboration Adds a collaboration for a single user or a single group to a file or folder. Collaborations can be created using email address, user IDs, or a group IDs. If a collaboration is being created with a group, access to this endpoint is dependent on the group's ability to be invited. If collaboration is in `pending` status, the following fields are redacted: - `login` and `name` are hidden if a collaboration was created using `user_id`, - `name` is hidden if a collaboration was created using `login`. This operation is performed by calling function `createCollaboration`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-collaborations/). ``` client.getUserCollaborations().createCollaboration(new CreateCollaborationRequestBody(new CreateCollaborationRequestBodyItemField.Builder().type(CreateCollaborationRequestBodyItemTypeField.FOLDER).id(folder.getId()).build(), new CreateCollaborationRequestBodyAccessibleByField.Builder(CreateCollaborationRequestBodyAccessibleByTypeField.USER).id(user.getId()).build(), CreateCollaborationRequestBodyRoleField.EDITOR)) ``` ### Arguments requestBody `CreateCollaborationRequestBody` - Request body of createCollaboration method queryParams `CreateCollaborationQueryParams` - Query parameters of createCollaboration method headers `CreateCollaborationHeaders` - Headers of createCollaboration method ### Returns This function returns a value of type `Collaboration`. Returns a new collaboration object. --- ## Untitled *Type: page* UsersManager List enterprise users Create user Get current user Get user Update user Delete user List enterprise users Returns a list of all… # UsersManager - [List enterprise users](#list-enterprise-users) - [Create user](#create-user) - [Get current user](#get-current-user) - [Get user](#get-user) - [Update user](#update-user) - [Delete user](#delete-user) ## List enterprise users Returns a list of all users for the Enterprise along with their `user_id`, `public_name`, and `login`. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This operation is performed by calling function `getUsers`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users/). ``` client.getUsers().getUsers() ``` ### Arguments queryParams `GetUsersQueryParams` - Query parameters of getUsers method headers `GetUsersHeaders` - Headers of getUsers method ### Returns This function returns a value of type `Users`. Returns all of the users in the enterprise. ## Create user Creates a new managed user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `createUser`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-users/). ``` client.getUsers().createUser(new CreateUserRequestBody.Builder(userName).login(userLogin).isPlatformAccessOnly(true).build()) ``` ### Arguments requestBody `CreateUserRequestBody` - Request body of createUser method queryParams `CreateUserQueryParams` - Query parameters of createUser method headers `CreateUserHeaders` - Headers of createUser method ### Returns This function returns a value of type `UserFull`. Returns a user object for the newly created user. ## Get current user Retrieves information about the user who is currently authenticated. In the case of a client-side authenticated OAuth 2.0 application this will be the user who authorized the app. In the case of a JWT, server-side authenticated application this will be the service account that belongs to the application by default. Use the `As-User` header to change who this API call is made on behalf of. This operation is performed by calling function `getUserMe`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-me/). ``` client.getUsers().getUserMe() ``` ### Arguments queryParams `GetUserMeQueryParams` - Query parameters of getUserMe method headers `GetUserMeHeaders` - Headers of getUserMe method ### Returns This function returns a value of type `UserFull`. Returns a single user object. ## Get user Retrieves information about a user in the enterprise. The application and the authenticated user need to have the permission to look up users in the entire enterprise. This endpoint also returns a limited set of information for external users who are collaborated on content owned by the enterprise for authenticated users with the right scopes. In this case, disallowed fields will return null instead. This operation is performed by calling function `getUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-users-id/). ``` client.getUsers().getUserById(user.getId()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" queryParams `GetUserByIdQueryParams` - Query parameters of getUserById method headers `GetUserByIdHeaders` - Headers of getUserById method ### Returns This function returns a value of type `UserFull`. Returns a single user object. Not all available fields are returned by default. Use the [fields](#param-fields) query parameter to explicitly request any specific fields using the [fields](#get-users-id--request--fields) parameter. ## Update user Updates a managed or app user in an enterprise. This endpoint is only available to users and applications with the right admin permissions. This operation is performed by calling function `updateUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-users-id/). ``` client.getUsers().updateUserById(user.getId(), new UpdateUserByIdRequestBody.Builder().name(updatedUserName).build()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" requestBody `UpdateUserByIdRequestBody` - Request body of updateUserById method queryParams `UpdateUserByIdQueryParams` - Query parameters of updateUserById method headers `UpdateUserByIdHeaders` - Headers of updateUserById method ### Returns This function returns a value of type `UserFull`. Returns the updated user object. ## Delete user Deletes a user. By default this will fail if the user still owns any content. Move their owned content first before proceeding, or use the `force` field to delete the user and their files. This operation is performed by calling function `deleteUserById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-users-id/). ``` client.getUsers().deleteUserById(user.getId()) ``` ### Arguments userId `String` - The ID of the user. Example: "12345" queryParams `DeleteUserByIdQueryParams` - Query parameters of deleteUserById method headers `DeleteUserByIdHeaders` - Headers of deleteUserById method ### Returns This function returns a value of type `void`. Removes the user and returns an empty response. --- ## Untitled *Type: page* WebhooksManager List all webhooks Create webhook Get webhook Update webhook Remove webhook Validate a webhook message List all webhooks… # WebhooksManager - [List all webhooks](#list-all-webhooks) - [Create webhook](#create-webhook) - [Get webhook](#get-webhook) - [Update webhook](#update-webhook) - [Remove webhook](#remove-webhook) - [Validate a webhook message](#validate-a-webhook-message) ## List all webhooks Returns all defined webhooks for the requesting application. This API only returns webhooks that are applied to files or folders that are owned by the authenticated user. This means that an admin can not see webhooks created by a service account unless the admin has access to those folders, and vice versa. This operation is performed by calling function `getWebhooks`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks/). ``` client.getWebhooks().getWebhooks() ``` ### Arguments queryParams `GetWebhooksQueryParams` - Query parameters of getWebhooks method headers `GetWebhooksHeaders` - Headers of getWebhooks method ### Returns This function returns a value of type `Webhooks`. Returns a list of webhooks. ## Create webhook Creates a webhook. This operation is performed by calling function `createWebhook`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-webhooks/). ``` client.getWebhooks().createWebhook(new CreateWebhookRequestBody(new CreateWebhookRequestBodyTargetField.Builder().id(folder.getId()).type(CreateWebhookRequestBodyTargetTypeField.FOLDER).build(), "https://example.com/new-webhook", Arrays.asList(CreateWebhookRequestBodyTriggersField.FILE_UPLOADED))) ``` ### Arguments requestBody `CreateWebhookRequestBody` - Request body of createWebhook method headers `CreateWebhookHeaders` - Headers of createWebhook method ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Get webhook Retrieves a specific webhook. This operation is performed by calling function `getWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-webhooks-id/). ``` client.getWebhooks().getWebhookById(webhook.getId()) ``` ### Arguments webhookId `String` - The ID of the webhook. Example: "3321123" headers `GetWebhookByIdHeaders` - Headers of getWebhookById method ### Returns This function returns a value of type `Webhook`. Returns a webhook object. ## Update webhook Updates a webhook. This operation is performed by calling function `updateWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-webhooks-id/). ``` client.getWebhooks().updateWebhookById(webhook.getId(), new UpdateWebhookByIdRequestBody.Builder().address("https://example.com/updated-webhook").build()) ``` ### Arguments webhookId `String` - The ID of the webhook. Example: "3321123" requestBody `UpdateWebhookByIdRequestBody` - Request body of updateWebhookById method headers `UpdateWebhookByIdHeaders` - Headers of updateWebhookById method ### Returns This function returns a value of type `Webhook`. Returns the new webhook object. ## Remove webhook Deletes a webhook. This operation is performed by calling function `deleteWebhookById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-webhooks-id/). ``` client.getWebhooks().deleteWebhookById(webhook.getId()) ``` ### Arguments webhookId `String` - The ID of the webhook. Example: "3321123" headers `DeleteWebhookByIdHeaders` - Headers of deleteWebhookById method ### Returns This function returns a value of type `void`. An empty response will be returned when the webhook was successfully deleted. ## Validate a webhook message Validate a webhook message by verifying the signature and the delivery timestamp This operation is performed by calling function `validateMessage`. ``` WebhooksManager.validateMessage(body, headersWithCorrectDatetime, primaryKey, secondaryKey) ``` ### Arguments body `String` - The request body of the webhook message headers `Map<String, String>` - The headers of the webhook message primaryKey `String` - The primary signature to verify the message with secondaryKey `String` - The secondary signature to verify the message with maxAge `Integer` - The maximum age of the message in seconds, defaults to 10 minutes ### Returns This function returns a value of type `boolean`. --- ## Untitled *Type: page* WebLinksManager Create web link Get web link Update web link Remove web link Create web link Creates a web link object within a folder. This… # WebLinksManager - [Create web link](#create-web-link) - [Get web link](#get-web-link) - [Update web link](#update-web-link) - [Remove web link](#remove-web-link) ## Create web link Creates a web link object within a folder. This operation is performed by calling function `createWebLink`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-web-links/). ``` client.getWebLinks().createWebLink(new CreateWebLinkRequestBody.Builder(url, new CreateWebLinkRequestBodyParentField(parent.getId())).name(name).description(description).build()) ``` ### Arguments requestBody `CreateWebLinkRequestBody` - Request body of createWebLink method headers `CreateWebLinkHeaders` - Headers of createWebLink method ### Returns This function returns a value of type `WebLink`. Returns the newly created web link object. ## Get web link Retrieve information about a web link. This operation is performed by calling function `getWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-web-links-id/). ``` client.getWebLinks().getWebLinkById(weblink.getId()) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" headers `GetWebLinkByIdHeaders` - Headers of getWebLinkById method ### Returns This function returns a value of type `WebLink`. Returns the web link object. ## Update web link Updates a web link object. This operation is performed by calling function `updateWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/put-web-links-id/). ``` client.getWebLinks().updateWebLinkById(weblink.getId(), new UpdateWebLinkByIdRequestBody.Builder().name(updatedName).sharedLink(new UpdateWebLinkByIdRequestBodySharedLinkField.Builder().access(UpdateWebLinkByIdRequestBodySharedLinkAccessField.OPEN).password(password).build()).build()) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" requestBody `UpdateWebLinkByIdRequestBody` - Request body of updateWebLinkById method headers `UpdateWebLinkByIdHeaders` - Headers of updateWebLinkById method ### Returns This function returns a value of type `WebLink`. Returns the updated web link object. ## Remove web link Deletes a web link. This operation is performed by calling function `deleteWebLinkById`. See the endpoint docs at [API Reference](https://developer.box.com/reference/delete-web-links-id/). ``` client.getWebLinks().deleteWebLinkById(weblink.getId()) ``` ### Arguments webLinkId `String` - The ID of the web link. Example: "12345" headers `DeleteWebLinkByIdHeaders` - Headers of deleteWebLinkById method ### Returns This function returns a value of type `void`. An empty response will be returned when the web link was successfully deleted. --- ## Untitled *Type: page* WorkflowsManager List workflows Starts workflow based on request body List workflows Returns list of workflows that act on a given folder ID… # WorkflowsManager - [List workflows](#list-workflows) - [Starts workflow based on request body](#starts-workflow-based-on-request-body) ## List workflows Returns list of workflows that act on a given `folder ID`, and have a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console in to use this endpoint. This operation is performed by calling function `getWorkflows`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-workflows/). ``` adminClient.getWorkflows().getWorkflows(new GetWorkflowsQueryParams(workflowFolderId)) ``` ### Arguments queryParams `GetWorkflowsQueryParams` - Query parameters of getWorkflows method headers `GetWorkflowsHeaders` - Headers of getWorkflows method ### Returns This function returns a value of type `Workflows`. Returns the workflow. ## Starts workflow based on request body Initiates a flow with a trigger type of `WORKFLOW_MANUAL_START`. You application must be authorized to use the `Manage Box Relay` application scope within the developer console. This operation is performed by calling function `startWorkflow`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-workflows-id-start/). ``` adminClient.getWorkflows().startWorkflow(workflowToRun.getId(), new StartWorkflowRequestBody.Builder(new StartWorkflowRequestBodyFlowField.Builder().type("flow").id(workflowToRun.getFlows().get(0).getId()).build(), Arrays.asList(new StartWorkflowRequestBodyFilesField.Builder().type(StartWorkflowRequestBodyFilesTypeField.FILE).id(workflowFileId).build()), new StartWorkflowRequestBodyFolderField.Builder().type(StartWorkflowRequestBodyFolderTypeField.FOLDER).id(workflowFolderId).build()).type(StartWorkflowRequestBodyTypeField.WORKFLOW_PARAMETERS).build()) ``` ### Arguments workflowId `String` - The ID of the workflow. Example: "12345" requestBody `StartWorkflowRequestBody` - Request body of startWorkflow method headers `StartWorkflowHeaders` - Headers of startWorkflow method ### Returns This function returns a value of type `void`. Starts the workflow. --- ## Untitled *Type: page* ZipDownloadsManager Create zip download Download zip archive Get zip download status Download ZIP Create zip download Creates a request to… # ZipDownloadsManager - [Create zip download](#create-zip-download) - [Download zip archive](#download-zip-archive) - [Get zip download status](#get-zip-download-status) - [Download ZIP](#download-zip) ## Create zip download Creates a request to download multiple files and folders as a single `zip` archive file. This API does not return the archive but instead performs all the checks to ensure that the user has access to all the items, and then returns a `download_url` and a `status_url` that can be used to download the archive. The limit for an archive is either the Account's upload limit or 10,000 files, whichever is met first. **Note**: Downloading a large file can be affected by various factors such as distance, network latency, bandwidth, and congestion, as well as packet loss ratio and current server load. For these reasons we recommend that a maximum ZIP archive total size does not exceed 25GB. This operation is performed by calling function `createZipDownload`. See the endpoint docs at [API Reference](https://developer.box.com/reference/post-zip-downloads/). ``` client.getZipDownloads().createZipDownload(new ZipDownloadRequest.Builder(Arrays.asList(new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FILE, file1.getId()), new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FILE, file2.getId()), new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FOLDER, folder1.getId()))).downloadFileName("zip").build()) ``` ### Arguments requestBody `ZipDownloadRequest` - Request body of createZipDownload method headers `CreateZipDownloadHeaders` - Headers of createZipDownload method ### Returns This function returns a value of type `ZipDownload`. If the `zip` archive is ready to be downloaded, the API will return a response that will include a `download_url`, a `status_url`, as well as any conflicts that might have occurred when creating the request. ## Download zip archive Returns the contents of a `zip` archive in binary format. This URL does not require any form of authentication and could be used in a user's browser to download the archive to a user's device. By default, this URL is only valid for a few seconds from the creation of the request for this archive. Once a download has started it can not be stopped and resumed, instead a new request for a zip archive would need to be created. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `download_url` field in the response to this endpoint. This operation is performed by calling function `getZipDownloadContent`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-content/). ``` client.getZipDownloads().getZipDownloadContent(zipDownload.getDownloadUrl()) ``` ### Arguments downloadUrl `String` - The URL that can be used to download created `zip` archive. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/content` headers `GetZipDownloadContentHeaders` - Headers of getZipDownloadContent method ### Returns This function returns a value of type `InputStream`. Returns the content of the items requested for this download, formatted as a stream of files and folders in a `zip` archive. ## Get zip download status Returns the download status of a `zip` archive, allowing an application to inspect the progress of the download as well as the number of items that might have been skipped. This endpoint can only be accessed once the download has started. Subsequently this endpoint is valid for 12 hours from the start of the download. The URL of this endpoint should not be considered as fixed. Instead, use the [Create zip download](e://post_zip_downloads) API to request to create a `zip` archive, and then follow the `status_url` field in the response to this endpoint. This operation is performed by calling function `getZipDownloadStatus`. See the endpoint docs at [API Reference](https://developer.box.com/reference/get-zip-downloads-id-status/). ``` client.getZipDownloads().getZipDownloadStatus(zipDownload.getStatusUrl()) ``` ### Arguments statusUrl `String` - The URL that can be used to get the status of the `zip` archive being downloaded. Example: `https://dl.boxcloud.com/2.0/zip_downloads/29l00nfxDyHOt7RphI9zT_w==nDnZEDjY2S8iEWWCHEEiptFxwoWojjlibZjJ6geuE5xnXENDTPxzgbks_yY=/status` headers `GetZipDownloadStatusHeaders` - Headers of getZipDownloadStatus method ### Returns This function returns a value of type `ZipDownloadStatus`. Returns the status of the `zip` archive that is being downloaded. ## Download ZIP Creates a zip and downloads its content This operation is performed by calling function `downloadZip`. ``` client.getZipDownloads().downloadZip(new ZipDownloadRequest.Builder(Arrays.asList(new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FILE, file1.getId()), new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FILE, file2.getId()), new ZipDownloadRequestItemsField(ZipDownloadRequestItemsTypeField.FOLDER, folder1.getId()))).downloadFileName("zip").build()) ``` ### Arguments requestBody `ZipDownloadRequest` - Zip download request body headers `DownloadZipHeaders` - Headers of zip download method ### Returns This function returns a value of type `InputStream`. --- ## Untitled *Type: page* Changelog All notable changes to this project will be documented in this file. See standard-version for commit guidelines. 0.8.0 (2025-08-0… # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## 0.8.0 (2025-08-05) ### Bug Fixes - Fix `mergeMaps` function (box/box-codegen[#734](https://github.com/box/box-java-sdk-gen/issues/734)) ([#324](https://github.com/box/box-java-sdk-gen/issues/324)) ([37e5536](https://github.com/box/box-java-sdk-gen/commit/37e553661f2573306710922984ff47d94fa6abc6)) - Fix downscope token to use `retrieveToken` method for token retrieval (box/box-codegen[#731](https://github.com/box/box-java-sdk-gen/issues/731)) ([#320](https://github.com/box/box-java-sdk-gen/issues/320)) ([55711f7](https://github.com/box/box-java-sdk-gen/commit/55711f79b38ab2ee4cc36a1df5c01cac8a9fbf8a)) - Fix Locale Comparison for upperCase and lowerCase (box/box-codegen[#746](https://github.com/box/box-java-sdk-gen/issues/746)) ([#345](https://github.com/box/box-java-sdk-gen/issues/345)) ([d8480ee](https://github.com/box/box-java-sdk-gen/commit/d8480ee6c8793f7d1595690007bb3c0dcedc2bc5)) - Specify events `next_stream_position` property type as `long` (box/box-openapi[#535](https://github.com/box/box-java-sdk-gen/issues/535)) ([#364](https://github.com/box/box-java-sdk-gen/issues/364)) ([715ac24](https://github.com/box/box-java-sdk-gen/commit/715ac2415b18b6128fa628728ace0cf3c632f47d)) ### New Features and Enhancements - Add AI spreadsheet processor (box/box-openapi[#533](https://github.com/box/box-java-sdk-gen/issues/533)) ([#349](https://github.com/box/box-java-sdk-gen/issues/349)) ([b53b17c](https://github.com/box/box-java-sdk-gen/commit/b53b17cba1189c38b9d8dba2ad9d97ed7c9fb59b)) - Add Archive Public API (box/box-openapi[#540](https://github.com/box/box-java-sdk-gen/issues/540)) ([#372](https://github.com/box/box-java-sdk-gen/issues/372)) ([32c566d](https://github.com/box/box-java-sdk-gen/commit/32c566d3fef6c3377975ee1e0ffb83cfa858dd47)) - add hubs API beta endpoints (box/box-openapi[#531](https://github.com/box/box-java-sdk-gen/issues/531)) ([#341](https://github.com/box/box-java-sdk-gen/issues/341)) ([d895e58](https://github.com/box/box-java-sdk-gen/commit/d895e58e61c5fe31ceb9d98697f98f13fba89148)) - Add new Hubs APIs and Hubs items API (box/box-openapi[#538](https://github.com/box/box-java-sdk-gen/issues/538)) ([#365](https://github.com/box/box-java-sdk-gen/issues/365)) ([73c70b3](https://github.com/box/box-java-sdk-gen/commit/73c70b35aafc8f5212010fa9566cb49f28f41d95)) - Add new property for network exception retry strategy (box/box-codegen[#763](https://github.com/box/box-java-sdk-gen/issues/763)) ([#371](https://github.com/box/box-java-sdk-gen/issues/371)) ([57927e0](https://github.com/box/box-java-sdk-gen/commit/57927e0b39c14ca208de7bc96ef942b8ca51f4d2)) - Add new schema for `Metadata Error` (box/box-openapi[#539](https://github.com/box/box-java-sdk-gen/issues/539)) ([#366](https://github.com/box/box-java-sdk-gen/issues/366)) ([08fcb0f](https://github.com/box/box-java-sdk-gen/commit/08fcb0faeadb2981648ad46db7505a1503d029eb)) - add Shield Lists APIs (box/box-openapi[#528](https://github.com/box/box-java-sdk-gen/issues/528)) ([#323](https://github.com/box/box-java-sdk-gen/issues/323)) ([79a2b87](https://github.com/box/box-java-sdk-gen/commit/79a2b87a6aaa2c33b9c9de7b3265ea31c3f09d58)) - Add webhook validation(box/box-codegen[#745](https://github.com/box/box-java-sdk-gen/issues/745)) ([#347](https://github.com/box/box-java-sdk-gen/issues/347)) ([ca61a56](https://github.com/box/box-java-sdk-gen/commit/ca61a56c48a3be2042c2d2b1670d1023d37e5979)) - Allow injecting private key `decryptor` for JWT (box/box-codegen[#754](https://github.com/box/box-java-sdk-gen/issues/754)) ([#355](https://github.com/box/box-java-sdk-gen/issues/355)) ([31f3a2a](https://github.com/box/box-java-sdk-gen/commit/31f3a2a6bcb2311b0db026220af58372914def41)) - Shorten builder names in Java (box/box-codegen[#742](https://github.com/box/box-java-sdk-gen/issues/742)) ([#334](https://github.com/box/box-java-sdk-gen/issues/334)) ([cf87520](https://github.com/box/box-java-sdk-gen/commit/cf87520c948022432a8905628d232d8d9424cd62)) - Support common union fields and implicit union conversion (box/box-codegen[#758](https://github.com/box/box-java-sdk-gen/issues/758)) ([#361](https://github.com/box/box-java-sdk-gen/issues/361)) ([eb98236](https://github.com/box/box-java-sdk-gen/commit/eb982364db2915305421838a47112bdf24f3dba2)) - Support DateTime in Java (box/box-codegen[#726](https://github.com/box/box-java-sdk-gen/issues/726)) ([#314](https://github.com/box/box-java-sdk-gen/issues/314)) ([90389ec](https://github.com/box/box-java-sdk-gen/commit/90389ecd8023125f82cb5a538c00a1a153b5488e)) - Support new tools in AI Studio (box/box-openapi[#534](https://github.com/box/box-java-sdk-gen/issues/534)) ([#352](https://github.com/box/box-java-sdk-gen/issues/352)) ([b7374ec](https://github.com/box/box-java-sdk-gen/commit/b7374ec91396d79719f75d6fccf8ef15ed503278)) - Support sending `nullable` fields in Java (box/box-codegen[#748](https://github.com/box/box-java-sdk-gen/issues/748)) ([#346](https://github.com/box/box-java-sdk-gen/issues/346)) ([e4e31bb](https://github.com/box/box-java-sdk-gen/commit/e4e31bbb85ddf95f1d480b19ae03c639b0a6509e)) - Update legal holds and AI models (box/box-openapi[#526](https://github.com/box/box-java-sdk-gen/issues/526)) ([#321](https://github.com/box/box-java-sdk-gen/issues/321)) ([28f2ec7](https://github.com/box/box-java-sdk-gen/commit/28f2ec7f871221527d1d5b0b9b6fd9b47e295b48)) ## 0.7.0 (2025-05-09) ### Bug Fixes - Fix conversion of `mdfilters` into query parameters (box/box-codegen[#721](https://github.com/box/box-java-sdk-gen/issues/721)) ([#301](https://github.com/box/box-java-sdk-gen/issues/301)) ([8c2e1c6](https://github.com/box/box-java-sdk-gen/commit/8c2e1c6801502e3952dfbbe20e2e36d4ef42810f)) ### New Features and Enhancements - add support of IBM models to AI API (box/box-openapi[#522](https://github.com/box/box-java-sdk-gen/issues/522)) ([#298](https://github.com/box/box-java-sdk-gen/issues/298)) ([1444afc](https://github.com/box/box-java-sdk-gen/commit/1444afc629d0f99814842c5c881fb1a9b28c30fe)) ### 0.6.2 (2025-05-02) ### Bug Fixes - Fix possible `NullPointerException` if data sanitizer is null ([#284](https://github.com/box/box-java-sdk-gen/issues/284)) ([e238f83](https://github.com/box/box-java-sdk-gen/commit/e238f8366aa9189b14f9748082829ea6b221d8dc)) - handle `double` and `any` `Metadata` values properly (box/box-codegen[#716](https://github.com/box/box-java-sdk-gen/issues/716)) ([#291](https://github.com/box/box-java-sdk-gen/issues/291)) ([2acac62](https://github.com/box/box-java-sdk-gen/commit/2acac62e231fe3e3f2706833cb0acbfdc5e30d70)) ### New Features and Enhancements - add AI agents warnings and allow for more types of metadata value (box/box-openapi[#520](https://github.com/box/box-java-sdk-gen/issues/520)) ([#295](https://github.com/box/box-java-sdk-gen/issues/295)) ([b945f1b](https://github.com/box/box-java-sdk-gen/commit/b945f1b7ef181f84bc20cba5638a9760ad6e52dc)) - Add security settings properties on sign template schema (box/box-openapi[#518](https://github.com/box/box-java-sdk-gen/issues/518)) ([#281](https://github.com/box/box-java-sdk-gen/issues/281)) ([075a1bc](https://github.com/box/box-java-sdk-gen/commit/075a1bc6494a6b5ab23df91a8d5735532e8fcbbf)) - Support additional properties for metadata endpoints (box/box-codegen[#719](https://github.com/box/box-java-sdk-gen/issues/719)) ([#293](https://github.com/box/box-java-sdk-gen/issues/293)) ([a3fd033](https://github.com/box/box-java-sdk-gen/commit/a3fd033288e684e6b30450d6f01f2e6e6e4500e1)) ### 0.6.1 (2025-04-10) ### Bug Fixes - Fix sanitizing headers in Java (box/box-codegen[#698](https://github.com/box/box-java-sdk-gen/issues/698)) ([#271](https://github.com/box/box-java-sdk-gen/issues/271)) ([0cf84d2](https://github.com/box/box-java-sdk-gen/commit/0cf84d266fd72c59ce275e78c33bcb3778d9b3f6)) ## 0.6.0 (2025-04-08) ### Bug Fixes - Fix handling responses with invalid `json` (box/box-codegen[#693](https://github.com/box/box-java-sdk-gen/issues/693)) ([#264](https://github.com/box/box-java-sdk-gen/issues/264)) ([c93ae3b](https://github.com/box/box-java-sdk-gen/commit/c93ae3b21a6f69f2134fb44e9489aece90d59ca9)) ### New Features and Enhancements - Support sensitive data sanitization in errors (box/box-codegen[#695](https://github.com/box/box-java-sdk-gen/issues/695)) ([#267](https://github.com/box/box-java-sdk-gen/issues/267)) ([2dd715f](https://github.com/box/box-java-sdk-gen/commit/2dd715f5c06ef3af6c82780686b332ae1360279c)) ### 0.5.2 (2025-03-25) ### Bug Fixes - Add missing fields to `AuthManager` during initialization (box/box-codegen[#688](https://github.com/box/box-java-sdk-gen/issues/688)) ([#257](https://github.com/box/box-java-sdk-gen/issues/257)) ([d352820](https://github.com/box/box-java-sdk-gen/commit/d3528207feac09477abdecd7bceb627580329ab6)) ### 0.5.1 (2025-03-18) ### Bug Fixes - add `verification_phone_number` property to create sign request (box/box-openapi[#515](https://github.com/box/box-java-sdk-gen/issues/515)) ([#242](https://github.com/box/box-java-sdk-gen/issues/242)) ([d81c700](https://github.com/box/box-java-sdk-gen/commit/d81c70052f3eb9198645090169fde85ee7991d10)) ### New Features and Enhancements - add find app item for shared link endpoint (box/box-openapi[#514](https://github.com/box/box-java-sdk-gen/issues/514)) ([#241](https://github.com/box/box-java-sdk-gen/issues/241)) ([751e35f](https://github.com/box/box-java-sdk-gen/commit/751e35fdf7f4b2a1fc8ac0153496eb5fe730549b)) - add Integration Mappings Teams API (box/box-openapi[#517](https://github.com/box/box-java-sdk-gen/issues/517)) ([#244](https://github.com/box/box-java-sdk-gen/issues/244)) ([ba45671](https://github.com/box/box-java-sdk-gen/commit/ba45671f4de0d933969256f394a85560726112c4)) - Expose token storage for authentication classes (box/box-codegen[#682](https://github.com/box/box-java-sdk-gen/issues/682)) ([#250](https://github.com/box/box-java-sdk-gen/issues/250)) ([6ad373d](https://github.com/box/box-java-sdk-gen/commit/6ad373df9ccd6fdd2d4cf465b04d765be9738cd1)) - Support AI Studio API (box/box-codegen[#626](https://github.com/box/box-java-sdk-gen/issues/626)) ([#223](https://github.com/box/box-java-sdk-gen/issues/223)) ([f991efd](https://github.com/box/box-java-sdk-gen/commit/f991efda62faa6feb4b4f4aa80247c5f4f6b399d)) - Support upload with preflight check (box/box-codegen[#676](https://github.com/box/box-java-sdk-gen/issues/676)) ([#249](https://github.com/box/box-java-sdk-gen/issues/249)) ([3199e25](https://github.com/box/box-java-sdk-gen/commit/3199e25f57b893dc504a64c40add7501152bb27f)) ## 0.5.0 (2025-02-10) ### Bug Fixes - Fix type of `Items` entries field (box/box-codegen[#660](https://github.com/box/box-java-sdk-gen/issues/660)) ([#213](https://github.com/box/box-java-sdk-gen/issues/213)) ([7e1b743](https://github.com/box/box-java-sdk-gen/commit/7e1b74386b0ab7bff92d855a8b50a42645854839)) ### New Features and Enhancements - Add hubs support to `/ai/ask` (box/box-openapi[#506](https://github.com/box/box-java-sdk-gen/issues/506)) ([#202](https://github.com/box/box-java-sdk-gen/issues/202)) ([888ee7b](https://github.com/box/box-java-sdk-gen/commit/888ee7bf5df8f7425371a7c55d1289d70137e675)) ## 0.4.0 (2025-02-03) ### Bug Fixes - Add missing token scope (box/box-openapi[#490](https://github.com/box/box-java-sdk-gen/issues/490)) ([#122](https://github.com/box/box-java-sdk-gen/issues/122)) ([83073a7](https://github.com/box/box-java-sdk-gen/commit/83073a7061744b97d685faa809cf6a96a6aa61a4)) - Correct types of `paged` and `thumb` properties in File representation (box/box-openapi[#503](https://github.com/box/box-java-sdk-gen/issues/503)) ([#161](https://github.com/box/box-java-sdk-gen/issues/161)) ([b603242](https://github.com/box/box-java-sdk-gen/commit/b60324274f9d74454ea93bb4ac418b2eea3a61e4)) - Fix handling list of enums and nested list of enums (box/box-codegen[#649](https://github.com/box/box-java-sdk-gen/issues/649)) ([#165](https://github.com/box/box-java-sdk-gen/issues/165)) ([45021c2](https://github.com/box/box-java-sdk-gen/commit/45021c26610c1427e86bbc8e277ac8f315a06837)) - Fix invalid variant config for Integration mapping Slack (box/box-openapi[#492](https://github.com/box/box-java-sdk-gen/issues/492)) ([#127](https://github.com/box/box-java-sdk-gen/issues/127)) ([c86142b](https://github.com/box/box-java-sdk-gen/commit/c86142b8c141e418f7b4fc1b64dd46adfb862f4e)) - Fix Java `NPE` in case of null body (box/box-codegen[#645](https://github.com/box/box-java-sdk-gen/issues/645)) ([#149](https://github.com/box/box-java-sdk-gen/issues/149)) ([25dee92](https://github.com/box/box-java-sdk-gen/commit/25dee9268ce16c8ef8909aefcdbf90a3f11d7ea2)) - order of fields in the `IntegrationMapping` schema (box/box-openapi[#497](https://github.com/box/box-java-sdk-gen/issues/497)) ([#145](https://github.com/box/box-java-sdk-gen/issues/145)) ([d3ce60c](https://github.com/box/box-java-sdk-gen/commit/d3ce60c7afa621e8dec5f7087497f0a4c60ba898)) - Remove auth when cross origin redirect (box/box-codegen[#648](https://github.com/box/box-java-sdk-gen/issues/648)) ([#158](https://github.com/box/box-java-sdk-gen/issues/158)) ([6136dac](https://github.com/box/box-java-sdk-gen/commit/6136dac05ba7215d2d7d6b68eac12910f1a4c06b)) ### New Features and Enhancements - Add Box Sign shared requests (box/box-openapi[#504](https://github.com/box/box-java-sdk-gen/issues/504)) ([#163](https://github.com/box/box-java-sdk-gen/issues/163)) ([b32f336](https://github.com/box/box-java-sdk-gen/commit/b32f33605b383f0bad987df6c5168e12acde90f6)) - Support Box Doc Gen API (box/box-codegen[#644](https://github.com/box/box-java-sdk-gen/issues/644)) ([#156](https://github.com/box/box-java-sdk-gen/issues/156)) ([81cb583](https://github.com/box/box-java-sdk-gen/commit/81cb583ea52e741a3c4597316d010521c30ae138)) - Support chunked upload in Java (box/box-codegen[#640](https://github.com/box/box-java-sdk-gen/issues/640)) ([#137](https://github.com/box/box-java-sdk-gen/issues/137)) ([012aaa0](https://github.com/box/box-java-sdk-gen/commit/012aaa0adf575865051156b7746ed4d50cb63a93)) - Update `/ai/extract_structured` response schema (box/box-codegen[#641](https://github.com/box/box-java-sdk-gen/issues/641)) ([#196](https://github.com/box/box-java-sdk-gen/issues/196)) ([d42892a](https://github.com/box/box-java-sdk-gen/commit/d42892a5b2e40b8192e0630b8dea56509248bf3f)) ## 0.3.0 (2024-12-30) ### Bug Fixes - Remove unused parameter from `SignRequest` (box/box-openapi[#489](https://github.com/box/box-java-sdk-gen/issues/489)) ([#107](https://github.com/box/box-java-sdk-gen/issues/107)) ([77bf54d](https://github.com/box/box-java-sdk-gen/commit/77bf54d27f48dc2752b95d43a4f65488de2c4d21)) ### New Features and Enhancements - Add `aiAgent` info to `AiResponse` (box/box-openapi[#485](https://github.com/box/box-java-sdk-gen/issues/485)) ([#93](https://github.com/box/box-java-sdk-gen/issues/93)) ([a7fe95f](https://github.com/box/box-java-sdk-gen/commit/a7fe95f6f264ec834f28b16c57ccb7ac11b98554)) - Add support for replacing the network client implementation (box/box-codegen[#629](https://github.com/box/box-java-sdk-gen/issues/629)) ([#115](https://github.com/box/box-java-sdk-gen/issues/115)) ([1bfa6ef](https://github.com/box/box-java-sdk-gen/commit/1bfa6efdff2da6af670f5841fefc7f9e51a3b804)) - Allow for customizing retry strategy (box/box-codegen[#635](https://github.com/box/box-java-sdk-gen/issues/635)) ([#120](https://github.com/box/box-java-sdk-gen/issues/120)) ([78946c0](https://github.com/box/box-java-sdk-gen/commit/78946c08c37834462a2fb700dd587a353b26052d)) - Support get download URL in Java (box/box-codegen[#634](https://github.com/box/box-java-sdk-gen/issues/634)) ([#119](https://github.com/box/box-java-sdk-gen/issues/119)) ([d62645e](https://github.com/box/box-java-sdk-gen/commit/d62645eaf7d4a5b4c1ab92fc602bd8bbcb4b253a)) - Support optional `userId` parameter for updating files, folders and web links ([#106](https://github.com/box/box-java-sdk-gen/issues/106)) ([50f7521](https://github.com/box/box-java-sdk-gen/commit/50f7521427f6019e588286eb9e9be20a8e28c3c1)) ## 0.2.0 (2024-12-03) ### Bug Fixes - add Dict import to the derived type when used in base type (box/box-codegen[#584](https://github.com/box/box-java-sdk-gen/issues/584)) ([#32](https://github.com/box/box-java-sdk-gen/issues/32)) ([d6212c8](https://github.com/box/box-java-sdk-gen/commit/d6212c80dcaf5f02040ad0a6f0e5a8622c69d463)) - fix additionalProperties (box/box-openapi[#477](https://github.com/box/box-java-sdk-gen/issues/477)) ([#31](https://github.com/box/box-java-sdk-gen/issues/31)) ([996944c](https://github.com/box/box-java-sdk-gen/commit/996944cf39e4925c6f346755d20c60a1a6665234)) - Support status codes with no content (box/box-codegen[#604](https://github.com/box/box-java-sdk-gen/issues/604)) ([#58](https://github.com/box/box-java-sdk-gen/issues/58)) ([cfc66b9](https://github.com/box/box-java-sdk-gen/commit/cfc66b9802f220865d3d403a6d0c51adae0d30d2)) - update client error schema to support schema errors (box/box-openapi[#467](https://github.com/box/box-java-sdk-gen/issues/467)) ([#23](https://github.com/box/box-java-sdk-gen/issues/23)) ([b5c018d](https://github.com/box/box-java-sdk-gen/commit/b5c018d94d52f9f47156b2a3e8a16c899ce5052c)) - use raw docstrings when comments contain backslash (box/box-codegen[#571](https://github.com/box/box-java-sdk-gen/issues/571)) ([8bedc09](https://github.com/box/box-java-sdk-gen/commit/8bedc096815817c2f83594956fa9fe5b663d3ab9)) ### New Features and Enhancements - Add optional URL parameter to `FetchResponse` (box/box-codegen[#617](https://github.com/box/box-java-sdk-gen/issues/617)) ([#89](https://github.com/box/box-java-sdk-gen/issues/89)) ([e50745c](https://github.com/box/box-java-sdk-gen/commit/e50745cfcec658157defb0925537d1d59210425a)) - Expose method for making custom HTTP requests (box/box-codegen[#610](https://github.com/box/box-java-sdk-gen/issues/610)) ([#84](https://github.com/box/box-java-sdk-gen/issues/84)) ([7476b1b](https://github.com/box/box-java-sdk-gen/commit/7476b1b67aafdbec83a068be526a50a56535db5e)) - Generate initial SDK (box/box-codegen[#570](https://github.com/box/box-java-sdk-gen/issues/570)) ([#3](https://github.com/box/box-java-sdk-gen/issues/3)) ([8750f1c](https://github.com/box/box-java-sdk-gen/commit/8750f1ce0742d77ebe57678478f52bd2c52c228b)) - include `rawData` in serialisable objects (box/box-codegen[#608](https://github.com/box/box-java-sdk-gen/issues/608)) ([#73](https://github.com/box/box-java-sdk-gen/issues/73)) ([56f8efd](https://github.com/box/box-java-sdk-gen/commit/56f8efdca04a0bb1dbd03ab5f7e06a7990275154)) - Introduce enum `Valuable` interface (box/box-codegen[#594](https://github.com/box/box-java-sdk-gen/issues/594)) ([#47](https://github.com/box/box-java-sdk-gen/issues/47)) ([3d7b227](https://github.com/box/box-java-sdk-gen/commit/3d7b2278b29fe490eda26463ceb843b0cbc37c7d)) - Modify schema for teams for integration mapping api (box/box-openapi[#463](https://github.com/box/box-java-sdk-gen/issues/463)) ([#21](https://github.com/box/box-java-sdk-gen/issues/21)) ([e5cb636](https://github.com/box/box-java-sdk-gen/commit/e5cb63695b7544fa14ee3da5a2f6a3a3d9ff50a0)) - Support `CCGAuth` and `OAuth` (box/box-openapi[#478](https://github.com/box/box-java-sdk-gen/issues/478)) ([#33](https://github.com/box/box-java-sdk-gen/issues/33)) ([d592498](https://github.com/box/box-java-sdk-gen/commit/d59249837578ba2eff78a503a0d4a0d5d29ff460)) - Support get collection by ID endpoint ([#46](https://github.com/box/box-java-sdk-gen/issues/46)) ([372cc5f](https://github.com/box/box-java-sdk-gen/commit/372cc5f7f97b308c33bbffc0aad26c01b6be6b2b)) - Support interceptors (box/box-codegen[#621](https://github.com/box/box-java-sdk-gen/issues/621)) ([#87](https://github.com/box/box-java-sdk-gen/issues/87)) ([8c1bbc3](https://github.com/box/box-java-sdk-gen/commit/8c1bbc3288e5742cd62df894553f24fc7a3ebd75)) - Support JWT Auth in Java (box/box-codegen[#590](https://github.com/box/box-java-sdk-gen/issues/590)) ([#36](https://github.com/box/box-java-sdk-gen/issues/36)) ([09a62d7](https://github.com/box/box-java-sdk-gen/commit/09a62d7ccf04017b9b8d2c4f940dde8bcd8c7e03)) - Support tests in Java (box/box-codegen[#580](https://github.com/box/box-java-sdk-gen/issues/580)) ([#30](https://github.com/box/box-java-sdk-gen/issues/30)) ([9c867c8](https://github.com/box/box-java-sdk-gen/commit/9c867c8aac977c75420ab07ac173eb3c7af3259e)) - Support Try, Throw tags and some build-in functions in Java (box/box-codegen[#579](https://github.com/box/box-java-sdk-gen/issues/579)) ([#20](https://github.com/box/box-java-sdk-gen/issues/20)) ([8b49f52](https://github.com/box/box-java-sdk-gen/commit/8b49f5295e3d19c4dd2272c451e441e73c54e13e)) - Support uploads and downloads (box/box-codegen[#572](https://github.com/box/box-java-sdk-gen/issues/572)) ([9528060](https://github.com/box/box-java-sdk-gen/commit/95280609434e693f6ee62116b40a8a37735a6237)) - Support uploads and downloads in Java (box/box-codegen[#572](https://github.com/box/box-java-sdk-gen/issues/572)) ([e02111b](https://github.com/box/box-java-sdk-gen/commit/e02111bb21d01448d46dca1cc607b79b5cd9d09a)) ### 0.1.1 (2024-11-04) ### New Features and Enhancements - Generate initial SDK (box/box-codegen[#570](https://github.com/box/box-codegen/issues/570)) ([#3](https://github.com/box/box-codegen/issues/3)) ([8750f1c](https://github.com/box/box-codegen/commit/8750f1ce0742d77ebe57678478f52bd2c52c228b)) --- ## Untitled *Type: page* Box Java SDK Gen Project Status build Maven Central Version Platform Coverage We are excited to introduce the Beta Release of the latest… # Box Java SDK Gen [](http://opensource.box.com/badges) [](https://coveralls.io/github/box/box-java-sdk-gen?branch=main) We are excited to introduce the Beta Release of the latest generation of Box Java SDK Gen, designed to elevate the developer experience and streamline your integration with the Box Content Cloud. With this SDK, you’ll have access to: 1. Full API Support: The new generation of Box SDKs empowers developers with complete coverage of the Box API ecosystem. You can now access all the latest features and functionalities offered by Box, allowing you to build even more sophisticated and feature-rich applications. 2. Rapid API Updates: Say goodbye to waiting for new Box APIs to be incorporated into the SDK. With our new auto-generation development approach, we can now add new Box APIs to the SDK at a much faster pace (in a matter of days). This means you can leverage the most up-to-date features in your applications without delay. 3. Embedded Documentation: We understand that easy access to information is crucial for developers. With our new approach, we have included comprehensive documentation for all objects and parameters directly in the source code of the SDK. This means you no longer need to look up this information on the developer portal, saving you time and streamlining your development process. 4. Enhanced Convenience Methods: Our commitment to enhancing your development experience continues with the introduction of convenience methods. These methods cover various aspects such as chunk uploads, classification, and much more. 5. Seamless Start: The new SDKs integrate essential functionalities like authentication, automatic retries with exponential backoff, exception handling, request cancellation, and type checking, enabling you to focus solely on your application's business logic. Embrace the new generation of Box SDKs and unlock the full potential of the Box Content Cloud. # Table of contents - [Box Java SDK Gen](#box-java-sdk-gen) - [Table of contents](#table-of-contents) - [Installing](#installing) - [Getting Started](#getting-started) - [Documentation](#documentation) - [Upgrades](#upgrades) [Integration Tests](#integration-tests) [Running integration tests locally](#running-integration-tests-locally) - [Create Platform Application](#create-platform-application) - [Export configuration](#export-configuration) - [Start integration tests](#start-integration-tests) [3rd Party Libraries & Licenses](#3rd-party-libraries--licenses) [Questions, Bugs, and Feature Requests?](#questions-bugs-and-feature-requests) [Copyright and License](#copyright-and-license) # Installing To generate a .jar file download the source code and run the following command: ``` ./gradlew build ``` .jar file will be generated in the build/libs directory. The SDK is also available on [Maven Central Repository](https://mvnrepository.com/artifact/com.box/box-java-sdk-gen). To include the SDK in your project, add the following dependency to your `pom.xml` file: ``` <dependency> <groupId>com.box</groupId> <artifactId>box-java-sdk-gen</artifactId> <version>VERSION</version> </dependency> ``` To include the SDK in your project using Gradle, add the following dependency to your `build.gradle` file: ``` implementation 'com.box:box-java-sdk-gen:VERSION' ``` Where `VERSION` is the version of the SDK you want to use. You can find the latest version in the [Maven Central Repository](https://mvnrepository.com/artifact/com.box/box-java-sdk-gen). # Getting Started To get started with the SDK, get a Developer Token from the Configuration page of your app in the Box Developer Console. You can use this token to make test calls for your own Box account. The SDK provides an `BoxDeveloperTokenAuth` class, which allows you to authenticate using your Developer Token. Use instance of `BoxDeveloperTokenAuth` to initialize `BoxClient` object. Using `BoxClient` object you can access managers, which allow you to perform some operations on your Box account. The example below demonstrates how to authenticate with Developer Token and print names of all items inside a root folder. ``` BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("DEVELOPER_TOKEN"); BoxClient client = new BoxClient(auth); client.folders.getFolderItems("0").getEntries().forEach(item -> { System.out.println(item.toString()); }); ``` # Documentation Browse the [docs](https://developer.box.com/70400d3b005c8fd7c1996054b99f7d4d/README.md) or see [API Reference](https://developer.box.com/reference/) for more information. # Upgrades The SDK is updated regularly to include new features, enhancements, and bug fixes. If you are upgrading from our legacy SDKs to this new generation SDKs is a straightforward process. Checkout the [migration guide](MIGRATION_GUIDE.md) and [changelog](https://developer.box.com/4b323e45efe58b0e83c392d780b1215d/CHANGELOG.md) for more information. # Integration Tests ## Running integration tests locally ### Create Platform Application To run integration tests locally you will need a `Custom App` created in the Box Developer Console with `Server Authentication (with JWT)` selected as authentication method. Once created you can edit properties of the application: - In section `App Access Level` select `App + Enterprise Access`. You can enable all `Application Scopes`. - In section `Advanced Features` enable `Make API calls using the as-user header` and `Generate user access tokens`. Now select `Authorization` and submit application to be reviewed by account admin. ### Export configuration Select `Configuration` tab and in the bottom in the section `App Settings` download your app configuration settings as JSON. 1. Encode configuration file to Base64, e.g. using command: `base64 -i path_to_json_file` 2. Set environment variable: `JWT_CONFIG_BASE_64` with base64 encoded jwt configuration file 3. Set environment variable: `BOX_FILE_REQUEST_ID` with ID of file request already created in the user account, `BOX_EXTERNAL_USER_EMAIL` with email of free external user which not belongs to any enterprise. 4. Set environment variable: `WORKFLOW_FOLDER_ID` with the ID of the Relay workflow that deletes the file that triggered the workflow. The workflow should have a manual start to be able to start it from the API. 5. Set environment variable: `APP_ITEM_ASSOCIATION_FILE_ID` to the ID of the file with associated app item and `APP_ITEM_ASSOCIATION_FOLDER_ID` to the ID of the folder with associated app item. 6. Set environment variable: `APP_ITEM_SHARED_LINK` to the shared link associated with app item. 7. Set environment variable: `SLACK_AUTOMATION_USER_ID` to the ID of the user responsible for the Slack automation, `SLACK_ORG_ID` to the ID of the Slack organization and `SLACK_PARTNER_ITEM_ID` to the ID of the Slack partner item. ### Start integration tests To run integration tests locally, you can use the following command: ``` ./gradlew test --stacktrace ``` # 3rd Party Libraries & Licenses The Java SDK Gen uses third-party libraries that are required for usage. Their licenses are listed below: [jackson-annotations v2.17.2](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations/2.17.2) Maven: `com.fasterxml.jackson.core:jackson-annotations:2.17.2` Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) [jackson-core v2.17.2](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.17.2) Maven: `com.fasterxml.jackson.core:jackson-core:2.17.2` Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) [jackson-databind v2.17.2](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.17.2) Maven: `com.fasterxml.jackson.core:jackson-databind:2.17.2` Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) [okhttp v4.12.0](https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/4.12.0) Maven: `com.squareup.okhttp3:okhttp:4.12.0` Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) [okio v3.5.0](https://mvnrepository.com/artifact/com.squareup.okio/okio/3.5.0) Maven: `com.squareup.okio:okio:3.5.0` Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) [jose4j v0.9.6](https://mvnrepository.com/artifact/org.bitbucket.b_c/jose4j/0.9.6) Maven: `org.bitbucket.b_c:jose4j:0.9.6` Licence: [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) [bcprov-jdk18on v1.78.1](https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk18on/1.78.1) Maven: `org.bouncycastle:bcprov-jdk18on:1.78.1` Licence: [MIT](https://opensource.org/licenses/MIT) [bcpkix-jdk18on v1.78.1](https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk18on/1.78.1) Maven: `org.bouncycastle:bcpkix-jdk18on:1.78.1` Licence: [MIT](https://opensource.org/licenses/MIT) The following libraries are required for running tests: [junit-jupiter-api v5.10.0](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api/5.10.0) Maven: `org.junit.jupiter:junit-jupiter-api:5.10.0` Licence: [EPL 2.0](https://www.eclipse.org/legal/epl-2.0/) [junit-jupiter-engine v5.10.0](https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine/5.10.0) Maven: `org.junit.jupiter:junit-jupiter-engine:5.10.0` Licence: [EPL 2.0](https://www.eclipse.org/legal/epl-2.0/) # Questions, Bugs, and Feature Requests? Need to contact us directly? Browse the issues tickets! Or, if that doesn't work, file a new one and we will get back to you. If you have general questions about the Box API, you can post to the [Box Developer Forum](https://forum.box.com/). # Copyright and License Copyright 2023 Box, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- ## Untitled *Type: page* Contributing All contributions are welcome to this project. Contributor License Agreement Before a contribution can be merged into this… # Contributing All contributions are welcome to this project. ## Contributor License Agreement Before a contribution can be merged into this project, please fill out the Contributor License Agreement (CLA) located at: [http://opensource.box.com/cla](http://opensource.box.com/cla) To learn more about CLAs and why they are important to open source projects, please see the [Wikipedia entry](http://en.wikipedia.org/wiki/Contributor_License_Agreement). ## Code of Conduct This project adheres to the [Box Open Code of Conduct](http://opensource.box.com/code-of-conduct/). By participating, you are expected to uphold this code. ## How to contribute - **File an issue** - if you found a bug, want to request an enhancement, or want to implement something (bug fix or feature). - **Send a pull request** - this project is generated using [Box Codegen](https://github.com/box/box-codegen) based on[Box OpenAPI 3.0 Specification](https://github.com/box/box-openapi), so if you want found something you want to change in the generated code, you'll need to modify the codegen project and submit a pull request there. --- ## Untitled *Type: page* Version Lifecycle We use a modified version of Semantic Versioning for all changes. It is strongly encouraged that you pin at least the… # Version Lifecycle We use a modified version of [Semantic Versioning](https://semver.org/) for all changes. It is strongly encouraged that you pin at least the major version and potentially the minor version to avoid pulling in breaking changes. Increasing the major version of an SDK indicates that this SDK underwent significant and substantial changes to support new idioms and patterns in the language. Major versions are introduced when public interfaces (e.g. classes, methods, types, etc.), behaviours, or semantics have changed. Semantic Versions take the form of `MAJOR.MINOR.PATCH`. When bugs are fixed in the library in a backwards-compatible way, the PATCH level will be incremented by one. PATCH changes should not break your code and are generally safe for upgrade. When a new feature set comes online or a small breaking change is introduced, the MINOR version will be incremented by one and the PATCH version resets to zero. MINOR changes may require some amount of manual code change for upgrade. These backwards-incompatible changes will mostly be limited to a small number of function signature changes. The MAJOR version is used to indicate the family of technology represented by the library. Breaking changes that require extensive reworking of code will cause the MAJOR version to be incremented by one, and the MINOR and PATCH versions will be reset to zero. Since frequent major updates can be very disruptive, we will only introduce this type of breaking change when absolutely necessary. New MAJOR versions will be communicated in advance via: - An email announcement is sent to affected accounts, announcing our plans to end support for the specific SDK version. The email will outline the path to end-of-support, specify the campaign timelines, and provide upgrade guidance. - Box SDK documentation, such as API reference documentation, user guides, SDK product marketing pages, and GitHub readme(s) are updated to indicate the campaign timeline and provide guidance on upgrading affected applications. - Deprecation warnings are added to the SDKs, outlining the path to end-of-support and linking to the SDK documentation. Deprecations are introduced in minor releases. We will not introduce new deprecations in patch releases. These deprecations will preserve the existing behaviour while emitting a warning that provide guidance on: - How to achieve similar behaviour if an alternative is available - The version in which the deprecation will be enforced. Deprecations will only be enforced in major releases. For example, if a behaviour is deprecated in version 1.2.0, it will continue to work, with a warning, for all releases in the 1.x series. The behaviour will change and the deprecation will be removed in the next major release (2.x.x). --- ## Untitled *Type: page* Migration guide from box-java-sdk to box-java-sdk-gen Introduction Installation Maven Gradle Key differences Manager approach Immutable… # Migration guide from box-java-sdk to box-java-sdk-gen - [Introduction](#introduction) [Installation](#installation) - [Maven](#maven) - [Gradle](#gradle) [Key differences](#key-differences) - [Manager approach](#manager-approach) - [Immutable design](#immutable-design) - [Consistent method signature](#consistent-method-signature) [Authentication](#authentication) - [Developer Token](#developer-token) [JWT Auth](#jwt-auth) - [Using JWT configuration file](#using-jwt-configuration-file) - [Providing JWT configuration manually](#providing-jwt-configuration-manually) - [Authenticate user](#authenticate-user) [Client Credentials Grant](#client-credentials-grant) - [Obtaining Service Account token](#obtaining-service-account-token) - [Obtaining User token](#obtaining-user-token) [Switching between Service Account and User](#switching-between-service-account-and-user) [OAuth 2.0 Auth](#oauth-20-auth) - [Get Authorization URL](#get-authorization-url) - [Authenticate](#authenticate) [Store token and retrieve token callbacks](#store-token-and-retrieve-token-callbacks) [Downscope token](#downscope-token) [Revoke token](#revoke-token) [Configuration](#configuration) - [As-User header](#as-user-header) - [Custom Base URLs](#custom-base-urls) [Convenience methods](#convenience-methods) - [Chunked upload of big files](#chunked-upload-of-big-files) ## Introduction The new `box-java-sdk-gen` SDK library, which helps Java developers to conveniently integrate with Box API. In the contrary to the previous library (`box-java-sdk`), it is not manually maintained, but auto-generated based on Open API Specification. This means you can leverage the most up-to-date Box API features in your applications without delay. More information and benefits of using the new can be found in the [README](https://github.com/box/box-java-sdk-gen/blob/main/README.md) file. ## Installation To install a new Box Java SDK GENERATED library, you can use Maven or Gradle. The library is available in the [Maven Central Repository](https://search.maven.org/artifact/com.box/box-java-sdk-gen). The new Box Java SDK GENERATED library could be used in the same project along with the legacy one. If you want to use a feature available only in the new SDK, you don't need to necessarily migrate all your code to use Box Java SDK GENERATED at once. You can use a new feature from the new library, while keeping the rest of your code unchanged. Note that it may be required to use fully qualified class names from the new SDK to avoid conflicts with the old one. However, we recommend to fully migrate to the new SDK eventually. ### Maven To add a dependency to your Maven project, add the following to your `pom.xml` file: ``` <dependency> <groupId>com.box</groupId> <artifactId>box-java-sdk-gen</artifactId> <version>VERSION</version> </dependency> ``` ### Gradle To add a dependency to your Gradle project, add the following to your `build.gradle` file: ``` implementation 'com.box:box-java-sdk-gen:VERSION' ``` ## Key differences ### Manager approach The main difference between the old SDK and the new one is the way how API methods are aggregated into objects. **Old (`box-java-sdk`)** Firstly, in the old SDK to be able to perform any action on an API object, e.g. `User`, you first had to create its class. To do it is required to call: ``` BoxUser user = new BoxUser(api, "12345"); ``` to create a class representing an already existing User with id '12345', or create a new one with a call: ``` BoxUser.Info createdUserInfo = BoxUser.createAppUser(api, "A User"); BoxUser user = new BoxUser(api, createdUserInfo.getID()); ``` Then, you could perform any action on created class, which will affect the user, e.g. ``` BoxUser.Info info = user.new Info(); info.setName(name); user.updateInfo(info); ``` **New (`box-java-sdk-gen`)** In the new SDK the API methods are grouped into dedicated manager classes, e.g. `User` object has dedicated `UserManager` class. Each manager class instance is available in `BoxClient` object. The fields storing references to the managers are named in the plural form of the resource that the manager handles - `client.users` for `UsersManager`. If you want to perform any operation connected with a `User` you need to call a respective method of `UserManager`. For example, to get info about existing user you need to call: ``` UserFull user = client.users.getUsersById("12345"); ``` or to create a new user: ``` CreateUserRequestBody requestBody = new CreateUserRequestBody.Builder("John Doe").build(); UserFull user = client.users.createUser(requestBody); ``` The `UserFull` object returned by both of these methods is a data class - it does not contain any methods to call. To perform any action on `User` object, you need to still use a `UserManager` method for that. Usually these methods have a first argument, which accepts id of the object you want to access, e.g. to update a user name, call method: ``` UpdateUserByIdRequestBody requestBody = new UpdateUserByIdRequestBody.Builder().name("Mary").build(); UserFull updatedUser = client.users.updateUserById(user.getId(), requestBody); ``` ### Immutable design The new SDK is designed to be mostly immutable. This means that methods, which used to modify the existing object in old SDK now return a new instance of the class with the modified state. This design pattern is used to avoid side effects and make the code more predictable and easier to reason about. Methods, which returns a new modified instance of an object, will always have a prefix `with` in their names, e.g. **New (`box-java-sdk-gen`)** ``` BoxClient client = new BoxClient(auth); BoxClient asUserClient = client.withAsUserHeader("USER_ID"); ``` ### Consistent method signature To facilitate easier work with the new SDK, we have changed the API method signatures to be consistent and unified. **Old (`box-java-sdk`)** In the old SDK, API methods had numerous parameters, which were not grouped into any objects and were passed as separate arguments, e.g. the method for creating a sign request looked like this: ``` public static BoxSignRequest.Info createSignRequest(BoxAPIConnection api, List<BoxSignRequestFile> sourceFiles, List<BoxSignRequestSigner> signers, String parentFolderId, BoxSignRequestCreateParams optionalParams) ``` **New (`box-java-sdk-gen`)** In the new SDK, we have adopted an approach of aggregating parameters into types based on their nature (path, body, query, headers). This can be seen in the example corresponding to the above: ``` public SignRequest createSignRequest( SignRequestCreateRequest requestBody, CreateSignRequestHeaders headers) ``` According to the convention, if an API endpoint requires a parameter placed in the URL path, it will appear at the beginning of our method, such as `fileId` in this case. When a request allows for a body, as in `POST` or `PUT`, the method includes a parameter named `requestBody`. Following that, the method signature may include the `queryParams` parameter, followed by `headers`. The types of parameters `requestBody`, `queryParams`, and `headers` are specific to each endpoint and, in their definition, encompass all fields allowed by the API. It's worth noting here that when all fields of a particular type are optional, the entire parameter becomes optional as well. This allows us to pass only the parameters we actually want to provide when calling a given method, without the risk of not providing a sufficient number of parameters. ## Authentication The Box Java SDK Gen library offers the same authentication methods as the legacy one. Let's see the differences of their usage: ### Developer Token **Old (`box-java-sdk`)** ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); ``` The new SDK provides a convenient `BoxDeveloperTokenAuth`, which allows authenticating using developer token without necessity to provide a Client ID and Client Secret **New (`box-java-sdk-gen`)** ``` BoxDeveloperTokenAuth auth = new BoxDeveloperTokenAuth("YOUR-DEVELOPER-TOKEN"); BoxClient client = new BoxClient(auth); ``` ### JWT Auth #### Using JWT configuration file **Old (`box-java-sdk`)** The static method, which reads the JWT configuration file has been changed: ``` Reader reader = new FileReader("src/example/config/config.json"); BoxConfig boxConfig = BoxConfig.readFrom(reader); IAccessTokenCache tokenCache = new InMemoryLRUAccessTokenCache(100); BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(boxConfig, tokenCache); ``` **New (`box-java-sdk-gen`)** ``` TokenStorage tokenStorage = new InMemoryTokenStorage(); // or any other implementation of TokenStorage JWTConfig config = JWTConfig.fromConfigFile("src/example/config/config.json", tokenStorage); BoxJWTAuth auth = new BoxJWTAuth(config); BoxClient client = new BoxClient(auth); ``` #### Providing JWT configuration manually Some params in `JWTConfig` constructor have slightly different names than one in old `JWTAuth` class. **Old (`box-java-sdk`)** ``` JWTEncryptionPreferences jwtPreferences = new JWTEncryptionPreferences(); jwtPreferences.setPublicKeyID("PUBLIC-KEY-ID"); jwtPreferences.setPrivateKeyPassword("PRIVATE-KEY-PASSWORD"); jwtPreferences.setPrivateKey("PRIVATE-KEY"); jwtPreferences.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256); IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(100); BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection .getUserConnection("USER-ID", "CLIENT-ID","CLIENT-SECRET", jwtPreferences, accessTokenCache); BoxUser.Info userInfo = BoxUser.getCurrentUser(api).getInfo(); ``` **New (`box-java-sdk-gen`)** ``` TokenStorage tokenStorage = new InMemoryTokenStorage(); JWTConfig config = new JWTConfig.Builder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "JWT_KEY_ID", "PRIVATE_KEY", "PRIVATE_KEY_PASSWORD") .enterpriseId("123456") .tokenStorage(tokenStorage) .build(); BoxJWTAuth auth = new BoxJWTAuth(config); BoxClient client = new BoxClient(auth); ``` #### Authenticate user In old SDK method for user authentication was named `BoxDeveloperEditionAPIConnection getUserConnection(String userId, BoxConfig boxConfig, IAccessTokenCache accessTokenCache)` and was accepting user id. The method was returning a new instance of `BoxDeveloperEditionAPIConnection` class, which was exchanging the existing token with the one with the user access. **Old (`box-java-sdk`)** ``` BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getUserConnection("USER_ID", boxConfig, tokenCache); ``` **New (`box-java-sdk-gen`)** In new SDK, to authenticate as user you need to call `public BoxJWTAuth withUserSubject(String userId, TokenStorage tokenStorage)` method with id of the user to authenticate. The method returns a new instance of `BoxJWTAuth` class, which will perform authentication call in scope of the user on the first API call. The `tokenStorage` parameter is optional and allows to provide a custom token storage for the new instance of `BoxJWTAuth` class. The new auth instance can be used to create a new user client instance. ``` BoxJWTAuth userAuth = auth.withUserSubject("USER_ID"); BoxClient userClient = new BoxClient(userAuth); ``` ### Client Credentials Grant #### Obtaining Service Account token To authenticate as enterprise, the only difference between the old and the new SDK, is using the `CCGConfig` as a middle step. **Old (`box-java-sdk`)** ``` BoxCCGAPIConnection api = BoxCCGAPIConnection.applicationServiceAccountConnection( "client_id", "client_secret", "enterprise_id" ); ``` **New (`box-java-sdk-gen`)** ``` CCGConfig config = new CCGConfig.Builder("YOUR_CLIENT", "YOUR_CLIENT_SECRET") .enterpriseId("ENTERPRISE_ID") .build(); BoxCCGAuth auth = new BoxCCGAuth(config); BoxClient client = new BoxClient(auth); ``` #### Obtaining User token To authenticate as user, the only difference between the old and the new SDK, is using the `CCGConfig` as a middle step. **Old (`box-java-sdk`)** ``` BoxCCGAPIConnection api = BoxCCGAPIConnection.userConnection( "client_id", "client_secret", "user_id" ); ``` **New (`box-java-sdk-gen`)** ``` CCGConfig config = new CCGConfig.Builder("YOUR_CLIENT", "YOUR_CLIENT_SECRET") .userId("USER_ID") .build(); BoxCCGAuth auth = new BoxCCGAuth(config); BoxClient client = new BoxClient(auth); ``` ### Switching between Service Account and User In old SDK, if you want to switch between the Service Account and User, you need to create another API connection. In the new SDK, to keep the immutability design, the methods switching authenticated subject were replaced with methods returning a new instance of `BoxCCGAuth` class. The new instance will fetch a new token on the next API call. The new auth instance can be used to create a new client instance. You can also specify `tokenStorage` parameter to provide a custom token storage for the new instance. The old instance of `BoxCCGAuth` class will remain unchanged and will still use the old token. **New (`box-java-sdk-gen`)** ``` BoxCCGAuth userAuth = auth.withUserSubject("USER_ID"); BoxClient userClient = new BoxClient(userAuth); ``` ``` BoxCCGAuth entAuth = auth.withEnterpriseSubject("ENTERPRISE_ID"); BoxClient entClient = new BoxClient(entAuth); ``` ### OAuth 2.0 Auth #### Get Authorization URL To get authorization url in the new SDK, you need to first create the `BoxOAuth` class using `OAuthConfig` class. Then to get authorization url, call `public String getAuthorizeUrl(GetAuthorizeUrlOptions options)`. Note that this method accepts the instance of `GetAuthorizeUrlOptions` class, which allows specifying extra options to API call. **Old (`box-java-sdk`)** In the old SDK, we did not have any method to get the authorization URL. Instead, we had to manually create the URL. ``` String authorizationUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code"; ``` **New (`box-java-sdk-gen`)** ``` BoxOAuth auth = new BoxOAuth(new OAuthConfig.Builder("CLIENT_ID", "CLIENT_SECRET").build()); String authorizationUrl = auth.getAuthorizeUrl(); ``` #### Authenticate The method for authenticating using the authorization code has been changed. With the old SDK, you had to provide the authorization code to the `BoxAPIConnection` class constructor. In the new SDK, you need to call the `public AccessToken getTokensAuthorizationCodeGrant(String authorizationCode)` method of the `BoxOAuth` class. The method now returns an AccessToken object with `accessToken` and `refreshToken` fields, while the old one was creating a new instance of `BoxAPIConnection` class. **Old (`box-java-sdk`)** ``` BoxAPIConnection client = new BoxAPIConnection( "[CLIENT_ID]", "[CLIENT_SECRET]", "[CODE]" ); ``` **New (`box-java-sdk-gen`)** ``` auth.getTokensAuthorizationCodeGrant("AUTHORIZATION_CODE"); BoxClient client = new BoxClient(auth); ``` ### Store token and retrieve token callbacks In the new SDK you can define your own class delegated for storing and retrieving a token. It has to inherit from `TokenStorage` and implement all of its abstract methods. Next step would be to pass an instance of this class to the AuthConfig constructor. **New (`box-java-sdk-gen`)** ``` TokenStorage customTokenStorage = new TokenStorage() { @Override public void store(AccessToken accessToken) { // Store the access token } @Override public AccessToken get() { // Retrieve the access token return null; } @Override public void clear() { // Clear the access token } }; OAuthConfig config = new OAuthConfig.Builder("CLIENT_ID", "CLIENT_SECRET") .tokenStorage(customTokenStorage) .build(); BoxOAuth auth = new BoxOAuth(config); ``` or reuse one of the provided implementations: `InMemoryTokenStorage`: ``` TokenStorage tokenStorage = new InMemoryTokenStorage(); OAuthConfig config = new OAuthConfig.Builder("CLIENT_ID", "CLIENT_SECRET") .tokenStorage(tokenStorage) .build(); BoxOAuth auth = new BoxOAuth(config); ``` ### Downscope token The process of downscoping token in the new SDK is similar to the old one. The main difference is that in the new SDK you need to call `downscopeToken` method of the `BoxOAuth` class instead of `getLowerScopedToken` method of the `BoxAPIConnection` class. **Old (`box-java-sdk`)** ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); String resource = "https://api.box.com/2.0/files/RESOURCE-ID"; List<String> scopes = new ArrayList<String>(); scopes.add("item_preview"); scopes.add("item_content_upload"); ScopedToken token = api.getLowerScopedToken(scopes, resource); ``` **New (`box-java-sdk-gen`)** ``` String resource = "https://api.box.com/2.0/files/123456789"; List<String> scopes = List.of("item_preview"); AccessToken downscopedToken = auth.downscopeToken(scopes, resource, null, null); BoxDeveloperTokenAuth downscopedAuth = new BoxDeveloperTokenAuth(downscopedToken.getAccessToken()); BoxClient downscopedClient = new BoxClient(downscopedAuth); ``` ### Revoke token To revoke current client's tokens in the new SDK, you need to call `revokeToken` method of the auth class instead of `revoke` method. **Old (`box-java-sdk`)** ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); api.revokeToken(); ``` **New (`box-java-sdk-gen`)** ``` client.auth.revokeToken() ``` ## Configuration ### As-User header The As-User header is used by enterprise admins to make API calls on behalf of their enterprise's users. This requires the API request to pass an `As-User: USER-ID` header. The following examples assume that the client has been instantiated with an access token with appropriate privileges to make As-User calls. In old SDK you could call client `asUser(String userID)` method to create a new client to impersonate the provided user. **Old (`box-java-sdk`)** ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-ACCESS-TOKEN"); api.asUser("USER-ID"); ``` **New (`box-java-sdk-gen`)** In the new SDK the method was renamed to `withAsUserHeader` in the `BoxClient` class, and returns a new instance of `BoxClient` class with the As-User header appended to all API calls made by the client. The method accepts only user id as a parameter. ``` BoxClient userClient = client.withAsUserHeader("USER-ID"); ``` Additionally `BoxClient` offers a `withExtraHeaders(Map<String, String> extraHeaders)` method, which allows you to specify the custom set of headers, which will be included in every API call made by client. Calling the `client.withExtraHeaders()` method creates a new client, leaving the original client unmodified. ``` BoxClient clientWithExtraHeaders = client.withExtraHeaders(new HashMap<>() {{ put("X-My-Header", "124"); }}); ``` ### Custom Base URLs **Old (`box-java-sdk`)** In old SDK you could specify the custom base URLs, which will be used for API calls made by setting the new values of static variables of the `API` class. ``` BoxAPIConnection api = new BoxAPIConnection("YOUR-DEVELOPER-TOKEN"); api.setBaseAppUrl("https://example.app.com"); api.setBaseURL("https://example.com"); api.setUploadURL("https://upload.example.com"); api.setTokenURL("https://example.com/token"); ``` **New (`box-java-sdk-gen`)** In the new SDK this functionality has been implemented as part of the `BoxClient` class. By calling the `client.withCustomBaseUrls()` method, you can specify the custom base URLs that will be used for API calls made by client. Following the immutability pattern, this call creates a new client, leaving the original client unmodified. ``` BaseUrls baseUrls = new BaseUrls.Builder() .baseUrl("https://new-base-url.com") .uploadUrl("https://my-company-upload-url.com") .oauth2Url("https://my-company.com/oauth2") .build(); BoxClient clientWithCustomBaseUrl = client.withCustomBaseUrls(baseUrls); ``` ## Convenience methods ### Chunked upload of big files For large files or in cases where the network connection is less reliable, you may want to upload the file in parts. This allows a single part to fail without aborting the entire upload, and failed parts are being retried automatically. **Old (`box-java-sdk`)** In the old SDK, you could use the `uploadLargeFile` method of the `BoxFolder` class to upload a large file. This method accepted a `FileInputStream` as the input stream and the file size as a parameter. The method also required ``` File myFile = new File("My Large_File.txt"); FileInputStream stream = new FileInputStream(myFile); BoxFolder rootFolder = BoxFolder.getRootFolder(api); BoxFile.Info fileInfo = rootFolder.uploadLargeFile(inputStream, "My_Large_File.txt", myFile.length()); ``` **New (`box-java-sdk-gen`)** In the new SDK, the equivalent method is `chunked_uploads.uploadBigFile()`. It accepts a file-like object as the `file` parameter, and the `fileName` and `fileSize` parameters are now passed as arguments. The `parentFolderId` parameter is also required to specify the folder where the file will be uploaded. ``` InputStream file = new FileInputStream(myFile); String fileName = "My_Large_File.txt"; long fileSize = 1234556L; String parentFolderId = "123456789"; File uploadedFile = client.getChunkedUploads().uploadBigFile(file, fileName, fileSize, parentFolderId); ``` --- ---