Cloud storage integrations

Box API by Name with HttpCurl

Give your application names such as images and penguins.jpg. Configure HttpCurl once with a collection of curl requests and their outputs, then ask for an operation. HttpCurl plans the intermediate requests needed to resolve missing IDs.

The examples use Chilkat 11.5.0 or later. Most requests use HttpCurl, which accepts curl-style requests and can carry response values into later calls. The language selector changes the example links throughout this page.

1. Choose how your application authenticates

Choose authentication according to whose content the app needs and whether a person signs in. All three flows produce an access token used in Authorization: Bearer ... on subsequent API calls.

The examples insert the actual token into the authorization header before passing the command to HttpCurl. They do not rely on SetVar to expand a placeholder inside a header. Keep tokens in protected application configuration and avoid logging authenticated request commands.

ApplicationFlowStart here
A user connects their existing Box accountOAuth 2.0 authorization codeAuthorize a User with OAuth 2.0
A scheduled job or backend service runs unattendedClient Credentials Grant (CCG)Get a Service Account Token with Client Credentials
A backend authenticates with a private keyJWT bearer grantGet a Service Account Token with JWT

In the Box Developer Console, create the appropriate User or Server app, configure its scopes and access level, and complete any required administrator authorization. Read-only browsing needs permission to read content; upload and content updates need write permission. Webhooks and enterprise features may need additional scopes, configuration, or entitlements. Changing app configuration may require reauthorization.

The CCG example explicitly sends Box's box_subject_type and box_subject_id. An enterprise subject gives the app's service account an access token; it does not sign the app in as the enterprise administrator. JWT signs a short-lived assertion with the application's private key and exchanges it for a token.

The interactive OAuth example uses a local development callback at http://localhost:3017/. Register that exact URI and run the example where the browser and listener can communicate. A deployed web application needs a server-side callback at its registered HTTPS URI. Keep client secrets in a trusted environment.

Token lifetime is separate from ID lifetime. User OAuth refresh tokens are single-use and valid for 60 days. Save the replacement refresh token immediately after a successful refresh and serialize refresh operations for the same account. CCG and JWT applications obtain another access token by repeating their grant, rather than using a user refresh token.

Box references: authentication choices, CCG setup, and token refresh.

2. Set up the request collection once

Create one HttpCurl object for the authenticated Box account. Register intermediate curl requests with AddFunction, and describe their outputs with AddOutput or AddOutput2. Registration sends no HTTP requests. Keep this configured object and pass it to the code that performs individual operations.

Registered requestRequired inputsDefined outputs
findParentParent name selected by its WHERE filterparent_id
findFolderparent_id; selected folder namefolder_id
findFilefolder_id; selected filenamefile_id
findDestinationDestination name selected by its WHERE filterdestination_id
getFileDetailsfile_idfile_version_id, file_sha1
getEnterpriseAuthenticated userenterprise_id, when available

The registry contains read-only prerequisites. Unused requests never run: a basic download does not fetch enterprise information or file-version details. Add more requests and outputs as your application's operations require them.

Each published task example repeats a clearly marked BEGIN ONE-TIME SETUP block so it can run independently. In an application, extract that block into your initialization routine and run only the BEGIN OPERATION portion against the existing object. The reuse example actually performs multiple operations on the same configured object.

3. Supply names and select their outputs

Operation inputs are the strings parentName, folderName, and fileName. The object remembers the previous selections in parent_name, folder_name, and file_name. Each operation compares the requested names with those stored selections, retaining IDs when names are unchanged and rebinding filters plus invalidating IDs when they change. For images/penguins.jpg, use parent /, folder images, and file penguins.jpg. Box's root ID 0 is handled internally; the caller never has to discover it.

This introductory registry supports a named parent directly under root and a named folder beneath it. With parent /, the folder is directly under root. Destination names select root children. These separate names are not an arbitrary slash-delimited path resolver.

Known: parent_name = "/", folder_name = "images", file_name = "penguins.jpg"
Unknown: folder_id, file_id

findFolder: entries WHERE name == "images"       → folder_id
findFile:   entries WHERE name == "penguins.jpg" → file_id
Target:     GET /files/{{file_id}}/content

AddOutput2 searches the response array and extracts the ID from the matching entry. Its WHERE value is literal in the tested library: passing {{folder_name}} there does not create a dynamic binding. The examples read the selected name with GetVar and pass its current value to AddOutput2. When a name changes, update that filter; the registered curl statement remains unchanged.

AddOutput handles a fixed JSON path. For example, getFileDetails maps file_version.id to file_version_id and sha1 to file_sha1. The verified-download example needs the version ID, so the planner adds that prerequisite automatically.

Start troubleshooting account visibility with GET /2.0/users/me. A service account has its own content and permissions. A successful lookup under one identity says nothing about access under another.

Selection does not imply pagination. The registry's name lookups inspect one page of at most 1000 children and assume the matching names identify the expected types. The explicit paginated examples traverse all file-list pages after resolving the folder, and the filename lookup also checks item type. For large ancestor listings, extend the traversal to each ancestor level and seed the resulting IDs into this same object. The dependency engine does not paginate by itself.

Box references: folder listings, current user, and search.

4. Execute a target and reuse what is known

After selecting names and invalidating stale state, call DoYourThing once with the final curl request. Do not manually run each lookup. For a cold download the planner runs findFolder → findFile → targetCurl. If folder_id is already known, it skips the folder lookup. If file_id is known, only the target runs.

ExaminePlan shows that sequence without sending requests. The setup example previews a cold plan, and the reuse example shows how the plan becomes shorter after earlier operations populate the object.

What changed?Refresh the selectionClear cached variables
FilenamefindFile output filterfile_id, file_version_id, file_sha1
Folder namefindFolder output filterfolder_id and file state
Parent namefindParent output filter; / uses rootparent_id, folder_id and file state
Destination namefindDestination output filterdestination_id
New contents for the same fileKeep its name selectionfile_version_id and file_sha1; revalidate file_id when needed
Authenticated account or token changesRebuild registration with the new authorization headerStart with fresh state; never reuse IDs across accounts blindly

Changing a name variable alone does not update a stored WHERE filter or invalidate dependent IDs. The examples make both actions explicit. After a rename or move, update the selected names as well as clearing stale IDs. Do not call ClearVar("*") casually: it also removes known inputs such as names and the stored access token.

Before each target request, ClearTargetOutput("*") removes extraction rules left by the previous target. This is separate from ClearVar: it preserves the intermediate function definitions and cached IDs. Register the current target's outputs, if any, and verify that they were populated.

The examples insert the actual bearer token into headers before registration, because header placeholders are not expanded by SetVar. Changing the token variable alone does not update previously registered commands. Reinitialize the registry when refreshing its credentials, and do not log those authenticated commands.

More detail: HttpCurl dependency engine and HttpCurl API overview.

5. Build writes on the same setup

The same name-based prerequisites support file information, shared links, new versions, moves, metadata, and webhook registration. Creating or modifying content stays an explicit target operation so the application can control its side effects. Creating a folder maps response id to folder_id; uploading a file maps entries[0].id to file_id. Keep those returned IDs for immediate follow-up work.

The local-file multipart example first resolves the named destination folder through the registry, then builds its attributes field using that resolved ID. The tested HttpCurl build does not expand variables inside multipart -F attributes, so this is explicitly two phases. The in-memory and chunked examples also resolve names first, then use their appropriate transfer APIs. They still require no IDs from the caller.

Direct uploads support files up to 50 MB, subject to account limits. Uploading a new version targets the existing file selected by name; a duplicate name sent to the new-file endpoint is a conflict. Downloads follow Box's redirect. Create local input files and the qa_output directory before running transfer examples.

The project workflow selects the parent folder documents, creates a project folder, uploads an invoice, applies the pre-existing metadata template, and creates a collaborators-only link. It keeps creation outputs for subsequent operations; only the enterprise scope is resolved when metadata needs it. If a write fails, preserve its returned IDs and resume deliberately rather than blindly replaying creation steps.

Box references: uploads and downloads and version selection.

6. Choose a sharing mechanism

A shared link points to content with a chosen access level. A collaboration grants a particular user or group a role. These are separate operations. The link example uses collaborators, so only people who already have access can use it; it does not invite the recipient.

The collaboration example invites a specified user as a viewer. Inspect whether the invitation is pending or accepted. Use the minimum suitable role and account for enterprise restrictions on external domains and shared links.

Renaming and moving preserve a file's ID, but moving can change inherited access. The trash/restore example uses a disposable test file and demonstrates recoverable removal, subject to the account's trash policy.

Box references: shared links, collaborations.

7. Connect documents to business records

Metadata lets the application attach business fields to a file instead of encoding everything in its filename. For these examples, have an administrator create an enterprise template whose template key is projectDocument, with string fields customerId and status. The scope is enterprise_{{enterprise_id}}; the registered getEnterprise request obtains that ID from the authenticated user profile. An account without enterprise membership cannot supply that output. Template display names and keys are not interchangeable.

The metadata example creates an instance with customerId = CUST-1001 and status = received, reads it, and changes the status to approved using JSON Patch. An existing instance should be read or updated rather than created again. The query example finds matching records using a parameterized customer ID and follows query markers.

Box reference: metadata templates, instances, and queries. Availability depends on the account's features and permissions.

8. React to uploads and other changes

A V2 webhook sends notifications to your application's public HTTPS endpoint. Register it on an accessible non-root folder, configure signature keys in the Box Developer Console, and keep those keys in protected application configuration.

The verification example operates on a captured request: exact body bytes plus the delivery timestamp and signature headers. It checks the timestamp window, calculates HMAC-SHA256 over body bytes followed by timestamp bytes, and accepts a valid primary or secondary signature. It uses randomized HMAC comparison; a native web receiver can use its language's standard constant-time byte comparison. Never parse and reserialize JSON before verifying its signature.

Your receiver still needs to validate the expected webhook/target, durably queue verified work, and return a 2xx response promptly. Deduplicate using the event ID in the body: delivery IDs change on retries. A standalone CkScript example does not install or host an HTTP receiver.

Polling is an alternative when the application cannot receive callbacks. The user-events example stores event IDs and the next stream position, starts at now on its first run, and processes a bounded batch on later runs. Its demonstration action is logging. In a production worker, coordinate the business action, deduplication record, and checkpoint to tolerate crashes and repeated delivery.

Box references: V2 webhooks, signature verification, events.

9. Upload larger files in parts

Box's chunked-upload API accepts files from 20 MB. Create a session, use the returned part size, upload each byte range with its digest, then commit the acknowledged parts and whole-file digest. The example uses explicit Http requests so response headers and transfer control remain visible.

This sequential example supports inputs up to 2 GB to keep offsets within a portable integer range. It saves the session and acknowledged-parts manifest. If a part request fails ambiguously, inspect the server's list-parts endpoint before retrying: an already uploaded part is immutable. The sample does not automatically resume an interrupted process, and rerunning it starts a new session.

A commit may return 202 Accepted while Box finishes processing. Honor Retry-After and retry the commit within a bounded loop. If the example stops while commit is pending, preserve its manifests and resume that commit later rather than uploading the file again.

Box references: chunked uploads, commit a session.

Troubleshoot before adding more requests

SymptomWhat to inspect
HTTP status 0No usable HTTP response. Inspect connection, DNS, TLS, proxy settings, and Chilkat diagnostics.
401Token expiration and the selected authentication flow. Refresh a user token or acquire a new CCG/JWT token.
403 or inaccessible contentIdentity from users/me, app scopes/authorization, and access to the specific item. The token does not bypass Box permissions.
404 or missing search resultCorrect item ID, current access, deletion/movement, and search indexing delay. Recheck the folder rather than assuming the name identifies a unique item.
409Name conflict or an already-existing resource. Choose deliberately between reuse, rename, or uploading a new version.
429Honor Retry-After. Apply bounded backoff with jitter; do not blindly retry writes whose outcome is unknown.
Download/commit not readyCheck the endpoint's documented status and Retry-After behavior. Only report completion after the expected success response.
Dependency output missingUse ExaminePlan; check the array/path mapping, expected name/type, and whether another page is needed.

HttpCurl exposes StatusCode and FailReason; FailedCurl helps identify a failed dependency. Curl text, token responses, and diagnostics can contain credentials, so redact them before logging or sharing. Each example checks its expected HTTP status rather than treating a received response as application success.

Box reference: rate limits and retries.

All Box examples, in learning order

Each example is self-contained. Replace its placeholders with your own configuration, use the required Box permissions, and follow its stated input-file and setup requirements.

  1. Get a Service Account Token with Client Credentials
  2. Authorize a User with OAuth 2.0
  3. Refresh and Save Rotated OAuth Tokens
  4. Get a Service Account Token with JWT
  5. Identify the User Behind an Access Token
  6. Set Up Reusable HttpCurl Requests and Outputs
  7. Reuse HttpCurl and Invalidate Cached IDs
  8. List All Files and Subfolders with Pagination
  9. Find a File by Name Across All Folder Pages
  10. Create a Folder and Capture Its ID
  11. Get File Information
  12. Search Files with Offset Pagination
  13. Upload a Local File with HttpCurl
  14. Upload a File from BinData
  15. Upload a New Version of an Existing File
  16. Download a File to Disk with HttpCurl
  17. Download Binary Content into BinData
  18. Download a UTF-8 Text File into Memory
  19. Resolve Folder and File IDs with the HttpCurl Dependency Engine
  20. Resolve a File Version by Name and Verify the Download
  21. Rename and Move a File
  22. Move a File to Trash and Restore It
  23. Create a Shared Link with Explicit Access
  24. Invite a Folder Collaborator
  25. Apply, Read, and Update File Metadata
  26. Query Documents by Customer Metadata
  27. Create a V2 Folder Webhook
  28. Poll User Events and Save a Checkpoint
  29. Verify a Captured V2 Webhook Signature
  30. Upload a Large File in Parts and Commit the Session
  31. Create a Project Folder, Upload, Tag, and Link a Document

Guide reviewed October 29, 2026. The examples explain API patterns; account limits, administrator policies, and product availability still apply. Consult the linked Box documentation for current service behavior.