Skip to main content

Command Palette

Search for a command to run...

Implementing Dataverse Search Using Web API in PowerApps and Dynamics 365 CE

Learn how to use the /api/search/v2.0/query Web API to perform customized Dataverse searches in PowerApps and Dynamics 365 CE.

Updated
5 min read
A

A seasoned Techno-Functional Professional with 7+ years of experience in Information Technology (IT), specializing in Microsoft Dynamics 365 Customer Engagement (CE) and Power Platform Solutions. I bring extensive expertise in out-of-the-box and custom configurations, customizations, integrations and data migrations. My skill set includes proficiency in working with Model Driven Apps, Canvas Apps, Power Pages (formerly Power Portals), Power Automate, Approval flows, Code Activities, Plugins, Workflows, Business Rules, JavaScript, HTML Web Resources, PCF Controls, Chatbots, SSRS Reports, Microsoft Copilot, Azure OpenAI, Azure Web Services, Azure Functions, Azure Logic Apps, Blazor Web Assemblies, C# and requirement analysis.

In this blog post, we'll explore how to access Dataverse using the Web API to implement search functionality. This approach allows you to retrieve and manage data stored in Dataverse (formerly Common Data Service) efficiently. Whether you're building a web application or integrating with other services, understanding how to leverage the Web API for search is essential.

Dataverse (formerly known as Common Data Service) is a cloud-based data storage and management platform provided by Microsoft. It allows users to store and manage data used by business applications. The Dataverse Search functionality enables users to perform searches across the data stored within Dataverse, providing a powerful way to query and retrieve relevant information.

By using Dataverse Search, you can query various types of data, including entities and fields, and filter results based on specific criteria. This feature is particularly useful for applications that need to provide search capabilities to end users, allowing them to find data quickly and efficiently.

Accessing Dataverse using the Web API provides several advantages:

  • Flexibility: The Web API allows for dynamic querying and integration with various applications, offering greater control over how data is accessed and manipulated.

  • Scalability: Web APIs are designed to handle a large number of requests and can scale according to the needs of your application.

  • Standard Protocol: The Web API uses standard HTTP methods (GET, POST, PUT, DELETE), making it easy to integrate with different technologies and platforms.

  • Security: The Web API supports OAuth 2.0 for secure authentication and authorization, ensuring that only authorized users can access the data.

Using the Web API for Dataverse search allows you to harness these benefits and build robust, scalable applications that can interact with Dataverse data seamlessly.

Implementation

Below are two code examples demonstrating how to implement search in Dataverse using the Web API. The first example shows how to perform a search, and the second example demonstrates how to handle the API call to retrieve results.

public async Task<HttpResponseData> SearchKWArticles()
{
    try
    {
        // Retrieve an access token for authentication from a helper method
        String token = await GetAccessTokenAsync();

        // Initialize the response variable
        HttpResponseData response = null;

        // Define hardcoded search parameters
        string searchQuery = "sample search text";  // The search query string
        bool countResults = true;  // Whether to count the number of results
        int topResults = 10;  // Maximum number of results to return
        string[] orderBy = new string[] { "createdon desc" };  // Sort results by creation date in descending order
        string filter = "createdon gt 1900-01-01";  // Filter results based on creation date

        // Define the Web API endpoint for performing the search
        String urlForConfigs = "/api/search/v2.0/query";

        // Construct the JSON request body for the Web API
        var jsonRequest = JsonConvert.SerializeObject(new
        {
            search = searchQuery,  // The search term
            count = countResults,  // Whether to count the results
            top = topResults,  // Limit on the number of results
            entities = JsonConvert.SerializeObject(new List<object>
            {
                new {
                    name = "knowledgearticle",  // The entity to search within
                    selectColumns = new List<string> { "title", "createdon","articlepublicnumber","description" },  // Columns to select
                    searchColumns = new List<string> { "title","articlepublicnumber","description" },  // Columns to search
                    filter = "statecode eq 3 and isprimary eq true"  // Filter to include only primary articles
                },
            }),
            orderby = JsonConvert.SerializeObject(orderBy),  // Sorting order
            filter = filter  // Additional filtering criteria
        });

        // Call the method to retrieve search results from the Web API
        String data = await RetrieveSuggestions(token, urlForConfigs, jsonRequest);

        // Create and configure the HTTP response with the search results
        response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "application/json; charset=utf-8");
        response.WriteString(data.Replace(_baseUrl, _impersonateUrl));  // Replace base URL if needed

        return response;
    }
    catch (Exception ex)
    {
        // Handle exceptions by returning a bad request response with the error message
        return CreateBadRequestResponse(req, ex.Message);
    }
}

Retrieving Search Results

private async Task<string> RetrieveSuggestions(string accessToken, string queryURL, object postBody)
{
    try
    {
        // Set the authorization header with the Bearer token for authentication
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        // Construct the full URL for the API request
        String url = _baseUrl + queryURL;

        // Send a POST request with the JSON body to the Web API
        var response = await _httpClient.PostAsJsonAsync(url, postBody);

        // Ensure the response indicates success
        response.EnsureSuccessStatusCode();

        // Read and return the response content as a string
        string content = await response.Content.ReadAsStringAsync();
        return content;
    }
    catch (Exception ex)
    {
        // Return error message in case of an exception
        return ex.Message;
    }
}

Additional Explanations

Here are some additional explanations to help you understand the code:

  • Access Token: The GetAccessTokenAsync method retrieves an OAuth 2.0 token needed for authenticating requests to the Web API. This token ensures secure access to the Dataverse data.

  • Search Parameters:

    • searchQuery: Defines the text or keywords used in the search.

    • countResults: Determines whether to include the count of search results.

    • topResults: Limits the number of results returned.

    • orderBy: Specifies how the results should be sorted.

    • filter: Applies additional conditions to filter the results based on specific criteria.

  • RetrieveSuggestions Method:

    • Sets the HTTP request header with the access token for authentication.

    • Sends the JSON payload to the Web API endpoint using a POST request.

    • Reads and returns the response from the API call, handling any exceptions by returning error messages.

Conclusion

Accessing Dataverse using the Web API enables you to perform powerful searches and retrieve relevant data efficiently. The provided code and explanations should help you integrate search capabilities into your applications and leverage the full potential of Dataverse.

More from this blog

C

Clever Wizard | Mastering Solutions

10 posts

A blog dedicated to simplifying complex business scenarios using Dynamics 365 CE, Power Platform, and Azure, empowering developers and organizations to implement innovative solutions with ease.