Building Custom APIs in Dataverse

Building Custom API in Dataverse

Introduction

In this article, we’ll explore how to create custom APIs in Dataverse. We’ll cover the benefits of using custom APIs and provide you with a step-by-step guide on how to build them. We’ll also share some best practices for using and maintaining custom APIs in Dataverse. By the end of this article, you’ll have a clear understanding of how custom APIs can help you streamline your data management efforts and enable your team to make better decisions.

Estimated reading time: 12 minutes

Table of contents

What are the Custom APIs?

Custom API is a modern, code-first approach that offers developers a more efficient way to create APIs in Dataverse for server-side operations.

Previously, developers could only use custom process actions to define APIs, but these were limited by the underlying technology. Custom process actions primarily aimed to offer a no-code experience for API creation. Developers often used this method to define the API signature while implementing all the logic using plugins.

Custom API acknowledges this pattern and provides a first-class experience for developers. By eliminating the need to support logic defined in a designer, developers can create APIs in a manner similar to how native Dataverse APIs are developed.

Some of the key advantages of custom API include:

  • Implementing logic on the main operation stage instead of stages before and after the main operation.
  • Preventing other developers from registering additional steps on your API to change its behavior.
  • Custom APIs cannot be disabled like custom process actions.
  • Creating a custom API using code.
  • Effortlessly editing files in a solution to create or modify a Custom API.
  • Marking your custom API as private to indicate that it’s not supported for use by other developers.
  • Creating a Function that can be invoked using GET with the Web API.
  • Setting a privilege that a user must have to use the custom API.

How To Build Custom APIs: Step-by-step Guide

A Custom API can include logic implemented with a plugin or can be created without a plugin by using business events to pass data about an event that other subscribers will respond to. However, in some cases, you may need to combine a Custom API with a plugin to define an operation that will be delegated to Dataverse to compute and return the result.

To create a Custom API, there are several different methods that you can use, such as:

  • Plugin registration tool – he Plugin registration tool (PRT) includes a designer to create Custom API. The PRT is a Windows client application that is part of the developer tools you can download from NuGet. Click on a specific link for further information.
  • Power Apps – Using forms to enter data. You don’t need to install a separate tool, you must create a separate record for each part of the Custom API. Click on a specific link for further information.
  • With Code – After you understand the data model, you can create Custom API very quickly using Postman. Or you can build your own experience to create Custom API.. Click on a specific link for further information.
  • With solution files – When you use Application Lifecycle Management (ALM) tools you can create or modify Custom API definitions with XML files in a solution that is included in your source code repository. The Custom API will be created when you import the solution generated from your source code. Click on a specific link for further information.
  • There are some tools created by the community:

In this section, we’ll walk you through the process of building custom APIs in Dataverse using Plugin registration tool . We will demonstrate how to create a straightforward Custom API that can calculate the age of an individual based on their birthdate and a specified date.

Using Plugin registration tool

See Dataverse development tools for information about downloading these tools.

Using PAC CLI command:

pac tool prt

Connect using the Plugin registration tool

  1. Launch the PluginRegistration.exe to open the tool.
  2. Click Create new Connection to connect to your instance.
  3. Make sure Office 365 is selected.
  4. If you are connecting using a Microsoft account other than one you are currently using, click Show Advanced and enter your credentials. Otherwise, leave Sign-in as current user selected.
  5. If your Microsoft Account provides access to multiple environments, select Display list of available organizations.
building a custom API
  1. Click Login.
  2. After you connected, you will see any existing regustered plugins, custom workflow activities and data providers.
building a custom API

Create Custom API

In the Register menu, select the Register new Custom API command. This will open the form to create a Custom API.

Utilize the data provided in the table below to generate the Custom API. To obtain more information regarding the columns in the Custom API table, please click on the provided link.

LabelDescriptionCan be changed
Display NameA localizable nameYes
NameA friendly, non-localizable nameYes
SolutionCreate a new solution or select an existing one. Setting this value will set the appropriate customization prefix for the Unique Name field.Yes
Unique NameThe name of the Custom API. This value should contain only alphanumeric characters and no spaces.
The full name includes the customization prefix determined by selecting the solution.
No
DescriptionA localizable description. For use when the message is exposed to be called in an app.Yes
AssemblyOptional. Select an assembly that contains a plugin type that will define what the Custom API does.Yes
PluginOptional. Select a plugin type within the selected assembly. You may set this later.Yes
Allowed Custom Processing Step TypeWhich types of processing steps you will allow.No
Binding TypeWhat kind of entity binding. We can use the following binding types:
Global – When the operation does not apply to a specific table.
Entity – When the operation accepts a single record of a specific table as a parameter.
EntityCollection – When the operation applies changes to, or returns a collection of a specific table.
No
Bound Entity Logical NameIf you select Binding Type Entity or EntityCollection you should enter the logical name of the table representing that type.No
Execute Privilege NameThe name of a privilege that will control whether someone can use the API. For further information: Secure your Custom API with a privilegeYes
FunctionWhether to create a Function.No
PrivateWhether the Custom API should be private.Yes
Custom API

You have the option to either continue adding Request Parameters and Response Properties, or you can choose to save the Custom API and add them at a later time.

Create Request parameters

It is not mandatory for a Custom API to include any request parameters. However, if you wish to create new request parameters while generating a Custom API or while modifying an existing one, you can do so by clicking on the + Add Request Parameter button. This will open up the Parameter form for you to fill out.

Create Response properties

It is not obligatory for a Custom API designed for an action to have any response properties. Nonetheless, if you wish to generate new response properties while creating or modifying a Custom API, you can do so by clicking on the + Add Response Parameter button. This will open up the Parameter form for you to input the necessary information.

Testing if the Custom API created

If you haven’t set the IsPrivate property for your Custom API, you can retrieve the service definition from the CSDL $metadata document using a GET request, even through your browser. This allows you to view the Action or Function created, along with any related ComplexType representing the return value.

To access the $metadata document, follow these steps:

  1. Open your browser and enter the URL for your Dataverse environment. The format should be: https://yourorg.crm.dynamics.com.
  2. Modify the URL by appending the endpoint for the $metadata document: /api/data/v9.2/$metadata. The complete URL should look like this: https://yourorg.crm.dynamics.com/api/data/v9.2/$metadata.
  3. Press Enter to send the GET request. The browser will display the CSDL $metadata document, which includes the definitions for all available APIs, including your Custom API.

To locate your Custom API within the $metadata document:

  1. Use the browser’s search functionality (Ctrl+F) to find the name of your Custom API.
  2. Once found, you will see the Action or Function definition created for your Custom API, along with any related ComplexType used to represent the return value.

Creating the Plugin

We can now add the implementation of our Custom API using a c# plugin.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;

namespace DiscoverPP.CustomAPIs
{
    [CrmPluginRegistration("discover_AgeCalculation")]
    public class AgeCalculation : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Get the input parameters from the comtext

            var inputparameters = context.InputParameters;
            var outputparameters = context.OutputParameters;

            var birthday = (DateTime)inputparameters["Birthday"];
            var ageatdate = (DateTime)inputparameters["AgeAtDate"];

            // Use the input parameters to perform your business logic.

            var age = ageatdate.Year - birthday.Year;

            if (birthday > ageatdate.AddYears(-age))
            {
                age--;
            }
            outputparameters["Age"] = age;

        }
    }
}

Deploying a Custom API Plugin using spkl

In order to wire up your Custom API definition to the plugin, you’ll need to deploy the plugin to your Dynamics 365 instance. This can be done easily using spkl tool (for further information, visit this link). Here is the step-by-step guide:

  1. Install spkl – Before you start, make sure you have the spkl tool installed. You can install by running the following from the Nuget Console:
Install-Package spkl
  1. Configure the spkl settings – Navigate to root directory of your plugin project and find the spkl.json configuration file. The configuration file should look like this:
"solutions": [
      {
        "profile": "default,debug",
        /*
            The unique name of the solution to extract, unpack, pack and import
            */
        "solution_uniquename": "CustomAPI",
        /*
            The relative folder path to store the extracted solution metadata xml files
            */
        "packagepath": "package",
        /*
            The relative path name of the solution to pack into
            */
        "solutionpath": "solution_{0}_{1}_{2}_{3}.zip",
        /*
            Set to 'unmanaged', 'managed', 'both_unmanaged_import' or 'both_managed_import' - default to 'unmanaged' if omitted
            */
        "packagetype": "unmanaged",
        /*
            Set to 'true' to increment the minor version number before importing from the xml files
            */
        "increment_on_import": false,
  1. Deploy plugin – To deploy your plugin, run the following command:
C:\repo\Blog\DiscoverPP.CustomAPIs\DiscoverPP.CustomAPIs.Code\spkl>deploy-plugins.bat

Testing and Troubleshooting Custom APIs

Once you have built and deployed your custom API, it’s important to thoroughly test and troubleshoot it to ensure that it works as expected and doesn’t cause any issues for your users or other systems. Here are some tips and best practices for testing and troubleshooting your custom APIs:

Using Postman to Test Dataverse Custom APIs

Postman is a versatile tool that is commonly used to test APIs, including Dataverse Custom APIs. Using Postman, you can send HTTP requests to your Dataverse Custom API endpoints and easily see the response, which can help you to test different scenarios and catch any errors.

Implementing Logging and Monitoring for Dataverse Custom APIs

Monitoring your Custom APIs is essential for identifying issues, ensuring optimal performance, and maintaining a high-quality user experience. Dynamics 365 provides the Plugin Trace Service for monitoring plugins, while Azure Application Insights can be used for monitoring and analytics of your web services. Here’s an overview of both services and how they can be used to monitor your custom APIs:

  • Plugin Trace Service – is a built-in monitoring tool in Dynamics 365 that allows you to log and trace the execution of your plugins, including Custom APIs. It provides detailed information about the performance and any issues that arise during the execution of your plugins.
  • Azure Application Insights – is a powerful application performance management and analytics service that can be used to monitor your Custom APIs

Error handling

Error handling is a crucial aspect of developing Custom APIs, as it helps to manage unexpected issues that may arise during the API’s operation. Proper error handling, combined with informative custom error messages, can significantly improve the user experience and make it easier to troubleshoot issues. Here are some best practices for implementing error handling and custom error messages in your custom APIs:

  • Understand the type of errors
  • Use try-catch blocks
  • Validate input data
  • Implement custom error messages

Conclusion

In this article, we have discussed the benefits of custom APIs in Microsoft Dataverse and how they can simplify your data management efforts. By creating custom APIs, you can expose your Dataverse data to external systems and enable easier integration with third-party applications.

Key Takeaways

  • Custom APIs enable you to securely expose your Dataverse data to external systems and enable easier integration with third-party applications.
  • You can create custom APIs using various methods, including Power Apps, Power Automate, Azure Functions, and .NET assemblies.
  • Custom APIs can be used to retrieve, create, update, and delete data in Dataverse, as well as perform custom business logic.
  • When creating custom APIs, it is important to consider security, authentication, and authorization.

Next Steps

  • Identify the data in your Dataverse environment that needs to be exposed to external systems and determine the appropriate custom API method to use.
  • Determine the security requirements for your custom API and implement the necessary authentication and authorization methods.
  • Test your custom API to ensure it is functioning properly and troubleshoot any issues as needed.
  • Continue to refine and optimize your custom API as your organization’s needs evolve.

Resource Links

These links below gave me inspiration and use cases in this post:

Comments are closed.