Friday, April 5, 2019

Use Sharepoint search API using HTTP POST requests

As you probably know it is possible to use Sharepoint search API programmatically by calling /_api/search/query endpoint with HTTP GET and provide KQL query and details (like selected managed properties) in query string. Popular Search Query Tool uses the same technique. However query string approach has own limitation, e.g. max 4kb length limit which is common for ASP.Net applications. If your query is built dynamically and you don’t know the actual length on compile time you may use search API with HTTP POST and provide KQL query in request body. If you want to use search API with HTTP POST you need to use slightly different endpoint: /_api/search/postquery. Let’s see how it works in Postman tool.

The first thing which we need to get is to obtain access token. It can be done by sending another HTTP POST request to the following address: https://accounts.accesscontrol.windows.net/{tenant_name}.onmicrosoft.com/tokens/OAuth/2. In request body we need to provide several parameters which are described in the following list:

  • grant_type = client_credentials
  • client_id – client id of your Sharepoint app (you should register it in advance using /_layouts/15/appregnew.aspx and then grant appropriate permissions using /_layouts/15/appinv.aspx) in the following form {cliend_id}@{tenant_id}. You may check tenant id in Azure portal > Azure Active Directory > Properties > Directory ID
  • client_secret – client secret of your Sharepoint app
  • resource – should have value in the form 00000003-0000-0ff1-ce00-000000000000/{tenant_name}.onmicrosoft.com@{tenant_id}

so request should look like this in Postman:

If everything was configured properly you should get success response which should contain access_token in the response body. Copy it’s value – it will be needed on the next step.

Now we are ready to send search POST requests to search API endpoint. We will use https://{tenant_name}.sharepoint.com/_api/search/postquery address for that. Let’s get list of all sites using the following KQL query:

contentclass:STS_Site

Request body should look like this:

{
   "request":{
      "Querytext":"contentclass:STS_Site",
      "RowLimit":100,
      "SelectProperties":{
         "results":[
            "Title",
            "SiteID",
            "OriginalPath"
         ]
      }
   }
}

After that switch to Authorization type and select Type = Bearer Token and specify value of access_token which was obtained on the previous step:

On the Headers tab add Accept and Content-type headers with “application/json;odata=verbose” (note that it is important to specify these headers exactly like this: if you will specify different odata version request may return error because parameters schema may be different.):

If everything was done properly when you will execute POST request in Postman you will get list of Sharepoint sites in your tenant.

No comments:

Post a Comment