Use the Microsoft Search API to query data

Important

APIs under the /beta version in Microsoft Graph are subject to change. Use of these APIs in production applications is not supported. To determine whether an API is available in v1.0, use the Version selector.

You can use the Microsoft Search API to query Microsoft 365 data in your apps.

Search requests run in the context of the signed-in user, identified using an access token with delegated permissions.

Caution

Resources used in a Microsoft Search API request and response have had properties renamed or removed, or are being deprecated. Find more details about the deprecation. Update search API queries in any earlier apps accordingly.

Common use cases

The Microsoft Search API provides a query method to search across your data in Microsoft Search, where you pass a searchRequest in the request body, defining the specifics of your search.

This section lists the common use cases of the query method, based on the properties and parameters you set in the query searchRequest body.

Search requests run on behalf of the user. Search results are scoped to enforce any access control applied to the items. For example, in the context of files, permissions on the files are evaluated as part of the search request. Users can't access more items in a search than they can otherwise obtain from a corresponding GET operation with the same permissions and access control.

Use cases Properties to define in the query request body
Scope search results based on entity types entityTypes
Page results from and size
Get the most relevant emails enableTopResults
Get selected properties fields
Use KQL in query terms query
Collapse search results collapseProperties
Sort search results sortProperties
Refine results using aggregations aggregations
Search custom types imported using connectors contentSources
Request spelling correction queryAlterationOptions
Search display layout (preview) resultTemplateOptions

Scope search based on entity types

Define the scope of the search request using the entityTypes property in the query request payload. The following table describes the types available to query and the supported permissions to access the data.

EntityType Permission scope required to access the items Source Comment
acronym Acronym.Read.All Microsoft Search Acronyms in Microsoft Search in your organization.
bookmark Bookmark.Read.All Microsoft Search Bookmarks in Microsoft Search in your organization.
chatMessage Chat.Read, Chat.ReadWrite, ChannelMessage.Read.All Teams Teams messages.
message Mail.Read, Mail.ReadWrite Exchange Online Email messages.
event Calendars.Read, Calendars.ReadWrite Exchange Online Calendar events.
drive Files.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite.All SharePoint Document libraries.
driveItem Files.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite.All SharePoint and OneDrive Files, folders, pages, and news.
list Sites.Read.All, Sites.ReadWrite.All SharePoint and OneDrive Lists. Document libraries are also returned as lists.
listItem Sites.Read.All, Sites.ReadWrite.All SharePoint and OneDrive List items. Files and folders are also returned as list items; listItem is the super class of driveItem.
externalItem ExternalItem.Read.All Microsoft Graph connectors All content ingested with the Microsoft Graph connectors API.
person People.Read Exchange Online Personal contacts and contacts or addressable objects in your organization.
qna QnA.Read.All Microsoft Search Questions and answers in Microsoft Search in your organization.
site Sites.Read.All, Sites.ReadWrite.All SharePoint Sites in SharePoint.

Page search results

Control pagination of the search results by specifying the following two properties in the query request body:

  • from - An integer that indicates the 0-based starting point to list search results on the page. The default value is 0.

  • size - An integer that indicates the number of results to be returned for a page. The default is 25 results. The maximum is 1000 results.

Note the following limits if you're searching the event or message entity:

  • from must start at zero in the first page request; otherwise, the request results in an HTTP 400 Bad request.
  • The maximum number of results per page (size) is 25 for message and event.

The upper limit for SharePoint or OneDrive items is 1000. A reasonable page size is 200. A larger page size generally incurs higher latency.

Best practices:

  • Specify a smaller first page in the initial request. For example, specify from as 0, size as 25.

  • Paginate subsequent pages by updating the from and size properties. You can increase the page size in each subsequent request. The following table shows an example.

    Page from size
    1 0 25
    2 25 50
    3 75 75
    4 150 100

Get the most relevant emails

When searching the message entity, specifying enableTopResults as true returns a hybrid list of messages: the first three messages in the response are sorted by relevance; the remaining messages are sorted by date/time.

Get selected properties

When searching an entity type, such as message, event, drive, driveItem, list, listItem, site, externalItem, or person, you can include in the fields property specific entity properties to return in the search results. This is similar to using the OData system query option, $select in REST requests. The search API doesn't technically support these query options because the behavior is expressed in the POST body.

For all these entity types, specifying the fields property reduces the number of properties returned in the response, optimizing the payload over the wire.

The listItem, driveItem and externalItem entities are the only supported entities that allow getting extended retrievable fields configured in the schema. You can't retrieve extended properties from all the other entities by using the search API. For example, if you created a retrievable field for externalItem in the search schema, or if you have a retrievable custom column on a listItem or driveItem, you can retrieve these properties from search. To retrieve an extended property on a file, specify the listItem or driveItem type in the request.

If the fields specified in the request are either not present in the schema, or not marked as retrievable, they won't be returned in the response. Invalid fields in the request are silently ignored.

If you don't specify any fields in the request, you'll get the default set of properties for all types. For extended properties, listItem, driveItem and externalItem behave differently when no fields are passed in the request:

  • listItem won't return any custom field.
  • driveItem will return an internal listItem with an empty field.
  • externalItem will return all the fields marked with the retrievable attribute in the Microsoft Graph connector schema for that particular connection.

Keyword Query Language (KQL) support

Specify free text keywords, operators (such as AND, OR), and property restrictions in KQL syntax in the actual search query string (query property of the query request body). The XRANK operator boosts the dynamic rank of items based on certain term occurrences within the match expression, without changing which items match the query. The syntax and command depend on the entity types (in the entityTypes property) you target in the same query request body.

Depending on the entity type, the searchable properties vary. For details, see:

Collapse search results

The collapseProperties property contains a set of criteria, fields, and limit size, which are used for collapsing results in a response body. Using collapseProperties only impacts the recall but not ranking/sorting.

The query method lets you customize the collapse property by specifying collapseProperties on the requests parameter, which is a collection of collapseProperty objects. This allows you to specify a set of one or more collapse properties.

Collapsing results is currently supported on the following entity types: driveItem, listItem, drive, list, site, externalItem.

The properties on which the collapse clause is applied need to be queryable and either sortable or refinable. For multi-level collapse, each subsequent property limit size specified in a multi-level request should be less than or equal to the previous; otherwise, the response returns an HTTP 400 Bad Request error.

For examples that show how to collapse results, see collapse search results.

Sort search results

Search results in the response are sorted in the following default sort order:

  • message and event are sorted by date.
  • All SharePoint, OneDrive, person and connector types are sorted by relevance.

The query method lets you customize the search order by specifying the sortProperties on the requests parameter, which is a collection of sortProperty objects. This allows you to specify a list of one or more sortable properties and the sort order.

Sorting results is currently only supported on the following SharePoint and OneDrive types: driveItem, listItem, list, site.

The properties on which the sort clause is applied need to be sortable in the SharePoint search schema. If the property specified in the request isn't sortable or doesn't exist, the response returns an error, HTTP 400 Bad Request. You can't specify to sort documents by relevance using sortProperty.

When specifying the name of a sortProperty object, you can either use the property name from the Microsoft Graph type (for example, in driveItem), or the name of the managed property in the search index.

See sort search results for examples that show how to sort results.

Refine results using aggregations

Aggregations (also known as refiners in SharePoint) are a popular way to enhance a search experience. In addition to the results, they provide some level of aggregate information on the matching set of search results. For example, you can provide information on the most represented authors of the documents matching the query, or the most represented file types, etc.

In the searchRequest, specify the aggregations that should be returned in addition to the search results. The description of each aggregation is defined in the aggregationOption, which specifies the property on which the aggregation should be computed, and the number of searchBucket to be returned in the response.

The properties on which the aggregation is requested need to be refinable in the SharePoint search schema. If the property specified isn't refinable or doesn't exist, the response returns HTTP 400 Bad Request.

Once the response is returned containing the collection of searchBucket objects, it's possible to refine the search request to only the matching elements contained in one searchBucket. This is achieved by passing back the aggregationsFilterToken value in the aggregationFilters property of the subsequent searchRequest.

Aggregations are currently supported for any refinable property on the following SharePoint and OneDrive types: driveItem, listItem, list, site, and on Microsoft Graph connectors externalItem.

See refine search results for examples that show using aggregation to enhance and narrow down search results.

Request spelling correction

Spelling correction is a popular way to handle mismatches between typos in a user query and the correct words in matched contents. When typos are detected in the original user query, you can get the search result either for the original user query or the corrected alternate query. You can also get the spelling correction information for typos in the queryAlterationResponse property of the searchResponse.

In the searchRequest, specify the queryAlterationOptions that should be applied to the query for spelling corrections. For details about the queryAlterationOptions property, see searchAlterationOptions.

For examples that show how to use spelling corrections, see Request spelling correction.

Search display layout

The search API allows you to render search results from connectors, by using the display layout or result template configured by the IT admin for each connector. The result templates are Adaptive Cards, which are a semantically meaningful combination of layout and data.

To get the result template in the searchResponse, you have to set true the enableResultTemplate property, defined in the resultTemplateOptions, in the searchRequest. The response includes a resultTemplateId for every search hit, which maps to one of the display layouts included in the resultTemplates dictionary that is included in the response.

See Use search display layout for examples.

The Search API enables guest users to search for items within SharePoint or OneDrive that have been shared with them. To access the list of guest users, go to the Microsoft 365 admin center, and in the left navigation, choose Users, and select Guest users.

Error handling

The search API returns error responses as defined by OData error object definition, each of which is a JSON object containing a code and a message.

Known limitations

The search API has the following limitations:

  • The query method is defined to allow passing a collection of one or more searchRequest instances at once. However, the service currently supports only a single searchRequest at a time.

  • The searchRequest resource supports passing multiple types of entities at a time. The following table lists the combinations that are supported.

    Entity Type acronym bookmark message chatMessage drive driveItem event externalItem list listItem person qna site
    acronym True True - - - - - - - - - True -
    bookmark True True - - - - - - - - - True -
    chatMessage - - - True - - - - - - - - -
    drive - - - - True True - True True True - - True
    driveItem - - - - True True - True True True - - True
    event - - - - - - True - - - - - -
    externalItem - - - - True True - True True True - - True
    list - - - - True True - True True True - - True
    listItem - - - - True True - True True True - - True
    message - - True - - - - - - - - - -
    person - - - - - - - - - - True - -
    qna True True - - - - - - - - - True -
    site - - - - True True - True True True - - True
  • The contentSource property, which defines the connection to use, is only applicable when entityType is specified as externalItem.

  • The search API doesn't support custom sort for acronym, bookmark, message, chatMessage, event, person, qna, or externalItem.

  • The search API doesn't support aggregations for acronym, bookmark, message, event, site, person, qna, or drive.

  • The search API doesn't support xrank for acronym, bookmark, message, chatMessage, event, person, qna, or externalItem.

  • Guest search doesn't support searches for acronym, bookmark, message, chatMessage, event, person, qna, or externalItem.

  • Customizations in SharePoint search, such as a custom search schema or result sources, can interfere with Microsoft Search API operations.

  • The search API doesn't support the site-level search schema. Use the tenant-level or default search schema.

Schema change deprecation warning

Effective August 31, 2023, the beta version of the externalItem resource in the Microsoft Graph namespace will be deprecated. Going forward, use the version of the resource in the Microsoft.Graph.ExternalConnectors namespace. Make sure that you update any namespace dependencies before the specified date. Alternatively, consider transitioning to the v1.0 version of the API.

In the beta version, properties used in a search request and response have been renamed or removed. In most cases, the original properties are being deprecated and replaced by the current properties, as listed in the following table.

We recommend that you update existing apps to use the current property and type names, and to get current property names in the response. For backward compatibility, the original properties and types are accessible and functional until September 30, 2023, after which they'll be removed.

Resource Change type Original property Current property
searchRequest Rename property stored_fields fields
searchQuery Rename property query_string queryString
searchQueryString Deprecate resource Not applicable Not applicable
searchHit Rename property _id hitId
searchHit Rename property _score rank
searchHit Remove property _sortField Not applicable
searchHit Rename property _source resource
searchHit Rename property _summary summary
entityTypes Rename enum value unknownfuturevalue unknownFutureValue