Overview of SharePoint Search API for SharePoint User Profiles

Introduction

The SharePoint Search API offers a powerful way to access user profile data, allowing you to query user properties like name, email, job title, and department. Here’s a guide on how to use the SharePoint Search API to get user profiles.

  1. What It Does: The SharePoint Search API allows you to search for people (user profiles) in the organization, using specific keywords or filters.
  2. Common Use Cases: Retrieving a user directory, displaying employee profiles, creating people search features, and filtering users based on department or location.

Here are the steps to get SharePoint User's Profile properties using Search REST API.

Step 1. Setting Up Authentication.

  1. Registering an App in Azure AD: Register an application in Azure Active Directory to use the SharePoint API securely.
    • Generate the Client ID and Client Secret.
    • Grant Sites.Read.All and User.ReadBasic.All permissions for basic profile information, or User.Read.All if you need detailed profiles.
  2. Obtaining an Access Token: Use the OAuth 2.0 flow to authenticate and get an access token, which is required for each API call.

Step 2. Constructing the Search API Request for User Profiles.

The URL format for SharePoint Online.

https://<tenant-name>.sharepoint.com/_api/search/postquery

Request Body for User Profile Search

{
    "request": {
        "__metadata": { 
            "type": "Microsoft.Office.Server.Search.REST.SearchRequest" 
        },
        "Querytext": "*",
        "SourceId": "B09A7990-05EA-4AF9-81EF-EDFAB16C4E31", // ID for people results source
        "SelectProperties": {
            "results": [
                "PreferredName",
                "WorkEmail",
                "JobTitle",
                "Department",
                "PictureURL"
            ]
        },
        "RowLimit": 10
    }
}

JavaScript Code Example with Fetch API

async function getUserProfiles() {
    const accessToken = "<your_access_token>"; // Replace with your OAuth access token
    const endpoint = "https://<tenant-name>.sharepoint.com/_api/search/postquery";

    const requestBody = {
        "request": {
            "__metadata": { "type": "Microsoft.Office.Server.Search.REST.SearchRequest" },
            "Querytext": "*", // or specific query text, like "Department:IT"
            "SourceId": "B09A7990-05EA-4AF9-81EF-EDFAB16C4E31", // People result source
            "SelectProperties": {
                "results": [
                    "PreferredName",
                    "WorkEmail",
                    "JobTitle",
                    "Department",
                    "PictureURL"
                ]
            },
            "RowLimit": 10
        }
    };

    const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
            "Authorization": `Bearer ${accessToken}`,
            "Accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose"
        },
        body: JSON.stringify(requestBody)
    });

    if (response.ok) {
        const data = await response.json();
        const results = data.d.postquery.PrimaryQueryResult.RelevantResults.Table.Rows.results;

        results.forEach(user => {
            console.log({
                Name: user.Cells.find(cell => cell.Key === 'PreferredName').Value,
                Email: user.Cells.find(cell => cell.Key === 'WorkEmail').Value,
                JobTitle: user.Cells.find(cell => cell.Key === 'JobTitle').Value,
                Department: user.Cells.find(cell => cell.Key === 'Department').Value,
                Picture: user.Cells.find(cell => cell.Key === 'PictureURL').Value
            });
        });
    } else {
        console.error("Error fetching user profiles:", response.status, response.statusText);
    }
}

getUserProfiles();

Key parts of the request

  1. Authorization Header: The Authorization header includes the OAuth 2.0 Bearer token needed to authenticate with the API.
  2. Content-Type: The header Content-Type: application/json;odata=verbose ensures that the API receives and interprets the request as JSON.
  3. Body Content: The request body includes.
    • Query text: Set to * to retrieve all users or customize the query with a filter (e.g., JobTitle: Manager).
    • SourceId: Specifies the people's result source.
    • SelectProperties: Lists the properties to retrieve for each user profile, such as PreferredName, WorkEmail, and JobTitle.
    • RowLimit: Limits the number of results returned (e.g., 10).

Note. We can add filtering and pagination options too.

  1. Filtering Results: Change Querytext to filter by specific user properties (e.g., Querytext='Department: Sales').
  2. Pagination: Add StartRow to the request body to retrieve results in batches for pagination.

Conclusion

Using POST /_api/search/postquery is effective when working with complex queries, avoiding URL length limits, and selecting multiple profile properties. This approach can be extended to search for other types of data within SharePoint by changing the SourceId and adjusting the SelectProperties to meet your needs.