How-To: PostQuery in SharePoint 2013 Search REST API

I have received several question from colleagues and through this blog about using the postquery method in the SharePoint 2013 Search REST API to POST the search query.

Here, I would like to share how that can be achieved. Search in SharePoint 2013 is a key player, and many of the features in SharePoint 2013 are now based on Search as the enabling platform. In that regard, proper documentation about what can be achieved with Search is more important now than ever. Through this blog, I’ll try to share any tips or tricks I come across, and I would kindly ask you to share any suggestions or requests you may have about topics you’d like covered.

OK, enough of the talking, let’s get back to the subject of this post. As noted in my previous post “SharePoint 2013 Search REST API” that describes the different methods and parameters available on the Search REST API, the postquery method can be used to POST the query to the service to overcome URI length restrictions when using the HTTP GET based method query.

The postquery method takes a Microsoft.Office.Server.Search.REST.SearchRequest object as parameter. The SearchRequest class is an internal class in Microsoft.Office.Server.Search.dll.

The HTTP POST request body representing a SearchRequest can be formatted in JSON as follows:

{

 'request': {

     'Querytext': 'sharepoint',

     'StartRow':1,

     'RowLimit':8,

     'SelectProperties': {

          'results': ['Title','ContentSource','DisplayAuthor']

     },

     'TrimDuplicates':true,

     'Refiners': 'companies,contentclass,ContentType(filter=7/0/*),FileExtension(filter=7/0/*),FileType(filter=6/0/*)',

     'RefinementFilters': {'results': ['filetype:equals("pptx")'] }

  }

}

One important thing to note here, is that when formatting the request as JSON, it is important to note that the Accept and ContentType headers must be set to “application/json;odata=verbose”. It is NOT enough with only “application/json”.

And here you can see a full raw HTTP POST request.

POST https://localhost/_api/search/postquery HTTP/1.1

Accept: application/json;odata=verbose

Content-Type: application/json;odata=verbose

Host: localhost

Content-Length: 419

 

{

 'request': {

     'Querytext': 'sharepoint',

     'StartRow':1,

     'RowLimit':8,

     'SelectProperties': {

          'results': ['Title','ContentSource','DisplayAuthor']

     },

     'TrimDuplicates':true,

     'Refiners':'companies,contentclass,ContentType(filter=7/0/*),FileExtension(filter=7/0/*),FileType(filter=6/0/*)',

     'RefinementFilters': {'results': ['filetype:equals("pptx")'] }

  }

}