Latest version

Query files/folders by metadata

post
https://api.box.com/2.0
/metadata_queries/execute_read

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.

Request

bearer [ACCESS_TOKEN]
application/json

Request Body

stringin bodyrequired
"0"

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.

string arrayin bodyoptional
["extension","created_at","item_status","metadata.enterprise_1234.contracts","metadata.enterprise_1234.regions.location"]

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.
stringin bodyrequired
"enterprise_123456.someTemplate"

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.

integerin bodyoptional
50
100
0
100

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.

stringin bodyoptional
"AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff"

Marker to use for requesting the next page.

object arrayin bodyoptional

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.

stringin bodyoptional
"asc"

The direction to order by, either ascending or descending.

The ordering direction must be the same for each item in the array.

Value is one of ASC,DESC,asc,desc

stringin bodyoptional
"amount"

The metadata template field to order by.

The field_key represents the key value of a field from the metadata template being searched for.

stringin bodyoptional
"value >= :amount"

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.

associative arrayin body

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.

objectin body
"100"

The value for the argument being used in the metadata search.

The type of this parameter must match the type of the corresponding metadata template field.

Response

Returns a list of files and folders that match this metadata query.

application/jsonClient error

Returns an error when the request body is not valid.

  • invalid_query - Any of the provided body parameters might be incorrect. This can mean the query is incorrect, as well as some cases where the from value does not represent a valid template.
  • unexpected_json_type - An argument from the query string is not present in query_param. For example, query of name = :name requires the query_param to include a value for the name argument, for example { "name": "Box, Inc" }.
application/jsonClient error

Returns an error when a metadata template with the given scope and templateKey can not be found. The error response will include extra details.

  • instance_not_found - The template was not found. Please make sure to use the full template scope including the enterprise ID, like enterprise_12345.
application/jsonClient error

An unexpected client error.

post
Query files/folders by metadata
You can now try out some of our APIs live, right here in the documentation.
Log in

Request Example

cURL
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
     }'
TypeScript Gen
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);
Python Gen
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"],
    },
)
.NET Gen
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"}) } } });
Java
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);
	}
}
Python
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}')
Node
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": ""
		}
		*/
	});

Response Example

{
  "entries": [
    {
      "etag": "1",
      "id": "12345",
      "type": "file",
      "file_version": {
        "id": "12345",
        "type": "file_version",
        "sha1": "134b65991ed521fcfe4724b7d814ab8ded5185dc"
      },
      "name": "Contract.pdf",
      "sequence_id": "3",
      "sha1": "85136C79CBF9FE36BB9D05D0639C70C265C18D37",
      "content_created_at": "2012-12-12T10:53:43-08:00",
      "content_modified_at": "2012-12-12T10:53:43-08:00",
      "created_at": "2012-12-12T10:53:43-08:00",
      "created_by": {
        "id": "11446498",
        "type": "user",
        "login": "ceo@example.com",
        "name": "Aaron Levie"
      },
      "description": "Contract for Q1 renewal",
      "item_status": "active",
      "modified_at": "2012-12-12T10:53:43-08:00",
      "modified_by": {
        "id": "11446498",
        "type": "user",
        "login": "ceo@example.com",
        "name": "Aaron Levie"
      },
      "owned_by": {
        "id": "11446498",
        "type": "user",
        "login": "ceo@example.com",
        "name": "Aaron Levie"
      },
      "parent": {
        "etag": "1",
        "id": "12345",
        "type": "folder",
        "name": "Contracts",
        "sequence_id": "3"
      },
      "path_collection": {
        "entries": [
          {
            "etag": "1",
            "id": "12345",
            "type": "folder",
            "name": "Contracts",
            "sequence_id": "3"
          }
        ],
        "total_count": 1
      },
      "purged_at": "2012-12-12T10:53:43-08:00",
      "shared_link": {
        "access": "open",
        "download_count": 3,
        "download_url": "https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg",
        "effective_access": "company",
        "effective_permission": "can_download",
        "is_password_enabled": true,
        "permissions": {
          "can_download": true,
          "can_edit": false,
          "can_preview": true
        },
        "preview_count": 3,
        "unshared_at": "2018-04-13T13:53:23-07:00",
        "url": "https://www.box.com/s/vspke7y05sb214wjokpk",
        "vanity_name": "my_url",
        "vanity_url": "https://acme.app.box.com/v/my_url/"
      },
      "size": 629644,
      "trashed_at": "2012-12-12T10:53:43-08:00",
      "allowed_invitee_roles": [
        "editor"
      ],
      "classification": {
        "color": "#FF0000",
        "definition": "Content that should not be shared outside the company.",
        "name": "Top Secret"
      },
      "comment_count": 10,
      "disposition_at": "2012-12-12T10:53:43-08:00",
      "expires_at": "2012-12-12T10:53:43-08:00",
      "expiring_embed_link": {
        "access_token": "c3FIOG9vSGV4VHo4QzAyg5T1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ",
        "expires_in": 3600,
        "restricted_to": [
          {
            "object": {
              "etag": "1",
              "id": "12345",
              "type": "folder",
              "name": "Contracts",
              "sequence_id": "3"
            },
            "scope": "item_download"
          }
        ],
        "token_type": "bearer",
        "url": "https://cloud.app.box.com/preview/expiring_embed/..."
      },
      "extension": "pdf",
      "has_collaborations": true,
      "is_accessible_via_shared_link": true,
      "is_associated_with_app_item": true,
      "is_externally_owned": true,
      "is_package": true,
      "lock": {
        "app_type": "office_wopiplus",
        "created_at": "2012-12-12T10:53:43-08:00",
        "created_by": {
          "id": "11446498",
          "type": "user",
          "login": "ceo@example.com",
          "name": "Aaron Levie"
        },
        "expired_at": "2012-12-12T10:53:43-08:00",
        "id": "11446498",
        "is_download_prevented": true,
        "type": "lock"
      },
      "metadata": {
        "enterprise_27335": {
          "marketingCollateral": {
            "$canEdit": true,
            "$id": "01234500-12f1-1234-aa12-b1d234cb567e",
            "$parent": "folder_59449484661",
            "$scope": "enterprise_27335",
            "$template": "marketingCollateral",
            "$type": "properties-6bcba49f-ca6d-4d2a-a758-57fe6edf44d0",
            "$typeVersion": 2,
            "$version": 1
          }
        }
      },
      "permissions": {
        "can_delete": true,
        "can_download": true,
        "can_invite_collaborator": true,
        "can_rename": true,
        "can_set_share_access": true,
        "can_share": true,
        "can_annotate": true,
        "can_comment": true,
        "can_preview": true,
        "can_upload": true,
        "can_view_annotations_all": true,
        "can_view_annotations_self": true
      },
      "representations": {
        "entries": [
          {
            "content": {
              "url_template": "https://dl.boxcloud.com/api/2.0/internal_files/123/versions/345/representations/png_paged_2048x2048/content/{+asset_path}?watermark_content=4567"
            },
            "info": {
              "url": "https://api.box.com/2.0/internal_files/123/versions/345/representations/png_paged_2048x2048"
            },
            "properties": {
              "dimensions": "2048x2048",
              "paged": true,
              "thumb": true
            },
            "representation": "png",
            "status": {
              "state": "success"
            }
          }
        ]
      },
      "shared_link_permission_options": [
        "can_preview"
      ],
      "tags": [
        "approved"
      ],
      "uploader_display_name": "Ellis Wiggins",
      "version_number": "1",
      "watermark_info": {
        "is_watermarked": true
      }
    }
  ],
  "limit": 100,
  "next_marker": "0!-M7487OpVfBTNBV-XsQjU50gQFlbFFu5nArMWD7Ck61GH_Qo40M1S2xN5zWZPBzEjaQS1SOjJiQoo5BsXEl1bCVLRZ2pTqo4SKp9tyqzWQK2L51KR_nC1EgF5I_TJSFw7uO2Bx4HweGETOjh5_2oPSWw5iMkM-OvGApeR0lGFO48FDKoyzJyLgz5aogxoKd8VE09CesOOnTnmZvrW0puylDc-hFjY5YLmWFBKox3SOWiSDwKFkmZGNHyjEzza1nSwbZg6CYsAdGsDwGJhuCeTNsFzP5Mo5qx9wMloS0lSPuf2CcBInbIJzl2CKlXF3FvqhANttpm2nzdBTQRSoJyJnjVBpf4Q_HjV2eb4KIZBBlLy067UCVdv2AAWQFd5E2i6s1YiGRTtgMEZntOSUYD4IYLMWWm5Ra7ke_SP32SL3GSjbBQYIyCVQ.."
}