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.
Start with the search-based setup and download examples, which require Chilkat 11.7.0 or later. They register HttpCurl output rules once and evaluate their name variables when the requests run. Other download examples also demonstrate 11.7.0 variables in local output paths. 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.
| Application | Flow | Start here |
|---|---|---|
| A user connects their existing Box account | OAuth 2.0 authorization code | Authorize a User with OAuth 2.0 |
| A scheduled job or backend service runs unattended | Client Credentials Grant (CCG) | Get a Service Account Token with Client Credentials |
| A backend authenticates with a private key | JWT bearer grant | Get 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.
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 request | Required inputs | Defined outputs |
|---|---|---|
| searchFolder | folder_query, folder_name | folder_id, folder_result_name, folder_parent_id, folder_search_count |
| searchFile | file_query, file_name, folder_id | file_id, file_result_name, file_parent_id, file_search_count |
This focused setup registers two read-only searches. AddOutput2 extracts each selected item's ID, name, and immediate parent ID; AddOutput extracts the response's total_count. The operation uses those extra outputs to validate the selection before saving the file.
The setup and download examples share a clearly marked BEGIN ONE-TIME SETUP block. It is repeated so the download example can run independently. In an application, run that block once and pass the same object to the BEGIN OPERATION code for each download. The folder name and filename need not be known when the output rules are registered.
3. Search by folder name and filename
Supply folderName = "images", fileName = "penguins.jpg", and a local destination such as qa_output/penguins.jpg. This example selects a folder directly under Box's root and a file directly inside that folder. It does not interpret an arbitrary slash-delimited path.
Both registered requests use GET /2.0/search with content_types=name. The folder search uses type=folder; the file search uses type=file and ancestor_folder_ids={{folder_id}}. These targeted searches resolve the IDs without listing every child in the folders.
Known: folder_name = "images", file_name = "penguins.jpg"
Derived inputs: folder_query = %22images%22
file_query = %22penguins.jpg%22
Unknown: folder_id, file_id
searchFolder: search names; select "images" → folder_id
searchFile: search within folder_id;
select "penguins.jpg" → file_id
targetCurl: GET /files/{{file_id}}/content
Application: validate search outputs, then save the bytes
The operation wraps each name in quotes for Box's phrase query, then URL-encodes the complete quoted text with StringBuilder.GetEncoded("url", "utf-8"). The encoded values are stored separately in folder_query and file_query. The output rules still compare the original names. This matters for characters such as &, which must not become query-parameter separators.
total_count = 1. The selected names must match exactly, the folder's immediate parent must be root (0), and the file's immediate parent must be the selected folder. Box's quoted search is phrase-based, and its ancestor filter includes subfolders. The checks prevent those broader matches from being saved as the requested file. Each request uses limit=2, while total_count reports the whole result count. Multiple results are rejected explicitly; this example does not paginate or choose among ambiguous candidates.Search uses an index, so newly created or renamed items may not appear immediately. Preserve IDs returned by creation or upload requests for immediate follow-up operations. Check the authenticated identity with GET /2.0/users/me when expected content is missing.
Box references: search parameters and ancestor scope, phrase matching, indexing, and search pagination.
How the examples use Chilkat 11.7.0
AddOutput2 searches a response array and extracts a value from the selected entry. Register the rule once with the variable reference itself. In Python, the file-ID rule is:
success = curl.AddOutput2("searchFile", "entries", "name", "{{file_name}}",
True, "id", "file_id")
In 11.7.0, {{file_name}} is stored as supplied and resolved every time this output is evaluated. Passing curl.GetVar("file_name") during setup would instead capture the value at registration time. Set the name later with SetVar; there is no need to register the rule again when the name changes.
| 11.7.0 feature | How it is used |
|---|---|
| Deferred AddOutput2 record selection | The WHERE values {{folder_name}} and {{file_name}} select records at execution time. Variable references are also supported in arrayPath, wherePath, and subPath. |
| Output-rule variables participate in planning | A referenced name is an input of its search function. The application can set it with SetVar, or another registered function can produce it first. These Box examples supply the names directly. |
| Deferred local output paths | Other download examples use -o "{{local_path}}". The path is resolved when the request runs. The search-based example holds bytes in memory for validation and then uses BinData.WriteFile(localPath). |
AddOutput continues to use a fixed JSON path: here it maps total_count to each search-count variable. Its jsonPath does not support the deferred references added to AddOutput2. For the full feature details, see the 11.7.0 release notes.
4. Execute a target and reuse what is known
After setting the names and encoded queries and clearing affected cached values, call DoYourThing once with the final download request. The engine runs searchFolder → searchFile → targetCurl for a cold download. If the folder ID and its validation fields are cached, it only needs the file search and download. With both selections cached, only the target runs.
ExaminePlan shows the sequence without sending requests. The setup example previews this cold plan. Keep the configured object to reuse it; do not repeat its AddFunction or AddOutput2 calls for each download.
Validation happens after the network download and before saving. The target follows Box's redirect and leaves the candidate content in memory. The application then checks the search counts, exact names, and immediate parents. Only a valid selection reaches GetResponseBd and BinData.WriteFile. A failed check reports the problem and clears the cached selection. This keeps one DoYourThing call, but makes the example suitable for small files such as penguins.jpg. It does not reject an ambiguous result before fetching its candidate content.
| What changed? | Refresh the selection | Clear cached variables |
|---|---|---|
| Filename | Set file_name and rebuild file_query | file_id, file_result_name, file_parent_id, file_search_count |
| Folder name | Set folder_name and rebuild folder_query | folder_id, folder_result_name, folder_parent_id, folder_search_count, plus all four file variables |
| Only the local destination | Change localPath | None |
| Remote rename, move, or changed search results | Refresh the relevant selection | Its ID and validation fields; also clear file state when refreshing the folder |
| Authenticated account or token changes | Rebuild registration with the new authorization header | Start with fresh state; never reuse IDs across accounts blindly |
Deferred evaluation does not automatically invalidate cached IDs or recheck remote changes. The operation compares the requested names with the stored selections and clears the affected fields when they differ. When names stay the same, it reuses the previously validated selection. Do not call ClearVar("*") casually: it also removes known names, encoded queries, and the stored access token.
The separate disk-download, reuse, and verified-download examples demonstrate -o "{{local_path}}". In 11.7.0, variable substitution also applies to --output, --output-dir, and the URL used by -O to derive a filename. An unresolved path variable is an error; a substituted value containing a .. directory segment is refused. Create the destination directory first.
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.
Other task examples and their setup
The setup and name-based download linked above use search dependencies. The other task examples currently include a broader standalone setup with findParent, findFolder, findFile, findDestination, getFileDetails, and getEnterprise. Their name lookups use folder listings. Use the setup included with each example; the two-search setup alone does not define all the outputs those operations need.
- Identify the User Behind an Access Token
- List All Files and Subfolders with Pagination
- Find a File by Name Across All Folder Pages
- Get File Information
The broader setup's ancestor lookups inspect one page of up to 1000 children. The explicit paginated browsing examples traverse all pages after resolving the folder, and the separate search example demonstrates offset pagination. Extend ancestor lookup when needed; the dependency engine does not paginate automatically.
5. Extend the request collection for writes
The same registration-and-execution pattern supports file information, shared links, new versions, moves, metadata, and webhook registration. Add the prerequisites and outputs required by the chosen operation, as shown in its standalone setup. 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.
- Create a Folder and Capture Its ID
- Upload a Local File with HttpCurl
- Upload a File from BinData
- Upload a New Version of an Existing File
- Download a File to Disk with HttpCurl
- Download Binary Content into BinData
- Download a UTF-8 Text File into Memory
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.
- Create a V2 Folder Webhook
- Verify a Captured V2 Webhook Signature
- Poll User Events and Save a Checkpoint
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
| Symptom | What to inspect |
|---|---|
| HTTP status 0 | No usable HTTP response. Inspect connection, DNS, TLS, proxy settings, and Chilkat diagnostics. |
| 401 | Token expiration and the selected authentication flow. Refresh a user token or acquire a new CCG/JWT token. |
| 403 or inaccessible content | Identity from users/me, app scopes/authorization, and access to the specific item. The token does not bypass Box permissions. |
| 404 or missing search result | Correct item ID, current access, deletion/movement, and search indexing delay. Recheck the folder rather than assuming the name identifies a unique item. |
| 409 | Name conflict or an already-existing resource. Choose deliberately between reuse, rename, or uploading a new version. |
| 429 | Honor Retry-After. Apply bounded backoff with jitter; do not blindly retry writes whose outcome is unknown. |
| Download/commit not ready | Check the endpoint's documented status and Retry-After behavior. Only report completion after the expected success response. |
| Dependency output missing | Use 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.
- Get a Service Account Token with Client Credentials
- Authorize a User with OAuth 2.0
- Refresh and Save Rotated OAuth Tokens
- Get a Service Account Token with JWT
- Identify the User Behind an Access Token
- Set Up Reusable HttpCurl Requests and Outputs
- Reuse HttpCurl and Invalidate Cached IDs
- List All Files and Subfolders with Pagination
- Find a File by Name Across All Folder Pages
- Create a Folder and Capture Its ID
- Get File Information
- Search Files with Offset Pagination
- Upload a Local File with HttpCurl
- Upload a File from BinData
- Upload a New Version of an Existing File
- Download a File to Disk with HttpCurl
- Download Binary Content into BinData
- Download a UTF-8 Text File into Memory
- Resolve Folder and File IDs with the HttpCurl Dependency Engine
- Resolve a File Version by Name and Verify the Download
- Rename and Move a File
- Move a File to Trash and Restore It
- Create a Shared Link with Explicit Access
- Invite a Folder Collaborator
- Apply, Read, and Update File Metadata
- Query Documents by Customer Metadata
- Create a V2 Folder Webhook
- Poll User Events and Save a Checkpoint
- Verify a Captured V2 Webhook Signature
- Upload a Large File in Parts and Commit the Session
- Create a Project Folder, Upload, Tag, and Link a Document
Guide reviewed October 30, 2026. The examples explain API patterns; account limits, administrator policies, and product availability still apply. Consult the linked Box documentation for current service behavior.