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
501000100

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.

stringin bodyoptional
"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
     }'
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": ""
		}
		*/
	});
TypeScript (Beta)
await client.search.searchByMetadataQuery({
  ancestorFolderId: '0',
  from: searchFrom,
  query: 'testName >= :value',
  queryParams: { ['value']: '0.0' },
} satisfies MetadataQuery);
Python (Beta)
client.search.search_by_metadata_query(search_from, '0', query='testName >= :value', query_params={'value': '0.0'})

Response Example

{
  "entries": [
    {
      "id": "12345",
      "etag": "1",
      "type": "file",
      "sequence_id": "3",
      "name": "Contract.pdf",
      "sha1": "85136C79CBF9FE36BB9D05D0639C70C265C18D37",
      "file_version": {
        "id": "12345",
        "type": "file_version",
        "sha1": "134b65991ed521fcfe4724b7d814ab8ded5185dc"
      },
      "description": "Contract for Q1 renewal",
      "size": 629644,
      "path_collection": {
        "total_count": 1,
        "entries": [
          {
            "id": "12345",
            "etag": "1",
            "type": "folder",
            "sequence_id": "3",
            "name": "Contracts"
          }
        ]
      },
      "created_at": "2012-12-12T10:53:43-08:00",
      "modified_at": "2012-12-12T10:53:43-08:00",
      "trashed_at": "2012-12-12T10:53:43-08:00",
      "purged_at": "2012-12-12T10:53:43-08:00",
      "content_created_at": "2012-12-12T10:53:43-08:00",
      "content_modified_at": "2012-12-12T10:53:43-08:00",
      "created_by": {
        "id": "11446498",
        "type": "user",
        "name": "Aaron Levie",
        "login": "ceo@example.com"
      },
      "modified_by": {
        "id": "11446498",
        "type": "user",
        "name": "Aaron Levie",
        "login": "ceo@example.com"
      },
      "owned_by": {
        "id": "11446498",
        "type": "user",
        "name": "Aaron Levie",
        "login": "ceo@example.com"
      },
      "shared_link": {
        "url": "https://www.box.com/s/vspke7y05sb214wjokpk",
        "download_url": "https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg",
        "vanity_url": "https://acme.app.box.com/v/my_url/",
        "vanity_name": "my_url",
        "access": "open",
        "effective_access": "company",
        "effective_permission": "can_download",
        "unshared_at": "2018-04-13T13:53:23-07:00",
        "is_password_enabled": true,
        "permissions": {
          "can_download": true,
          "can_preview": true,
          "can_edit": false
        },
        "download_count": 3,
        "preview_count": 3
      },
      "parent": {
        "id": "12345",
        "etag": "1",
        "type": "folder",
        "sequence_id": "3",
        "name": "Contracts"
      },
      "item_status": "active"
    }
  ],
  "limit": 100,
  "next_marker": "0!-M7487OpVfBTNBV-XsQjU50gQFlbFFu5nArMWD7Ck61GH_Qo40M1S2xN5zWZPBzEjaQS1SOjJiQoo5BsXEl1bCVLRZ2pTqo4SKp9tyqzWQK2L51KR_nC1EgF5I_TJSFw7uO2Bx4HweGETOjh5_2oPSWw5iMkM-OvGApeR0lGFO48FDKoyzJyLgz5aogxoKd8VE09CesOOnTnmZvrW0puylDc-hFjY5YLmWFBKox3SOWiSDwKFkmZGNHyjEzza1nSwbZg6CYsAdGsDwGJhuCeTNsFzP5Mo5qx9wMloS0lSPuf2CcBInbIJzl2CKlXF3FvqhANttpm2nzdBTQRSoJyJnjVBpf4Q_HjV2eb4KIZBBlLy067UCVdv2AAWQFd5E2i6s1YiGRTtgMEZntOSUYD4IYLMWWm5Ra7ke_SP32SL3GSjbBQYIyCVQ.."
}