02 de dezembro de 2026
Dataverse: custom APIs vs actions para contratos de serviço reutilizáveis
Precisa expor lógica de negócio como um endpoint estável no Dataverse? Veja quando usar custom API em vez de custom action, com plugins, bound/unbound e governança por ALM.
Quando a lógica de negócio precisa ser invocada de vários lugares — um botão de model-driven app, um fluxo do Power Automate, um agente do Copilot Studio, uma aplicação externa via Web API — espalhar a mesma regra em cada ponto de consumo é um convite ao retrabalho e à inconsistência. O Dataverse oferece dois mecanismos para empacotar essa lógica como uma mensagem própria, invocável como qualquer verbo nativo da plataforma: custom actions (o modelo clássico, baseado em processo) e custom APIs (o modelo moderno, declarativo). Eles parecem resolver o mesmo problema, mas têm diferenças arquiteturais que determinam governança, performance e manutenção em escala.
O que cada um realmente é
Uma custom action é um tipo de processo (workflow com categoria Action) definido no process designer. Você declara input/output arguments e pode compor a lógica com os steps no-code do workflow clássico e/ou plugar código registrando um plugin no SdkMessageProcessingStep gerado para aquela action. Ou seja: uma action pode executar tanto lógica declarativa (steps) quanto lógica de plugin.
Uma custom API é uma definição de mensagem pura, modelada por tabelas de metadado (CustomAPI, CustomAPIRequestParameter, CustomAPIResponseProperty). Ela não carrega steps no-code — é apenas o contrato (nome da mensagem, parâmetros de entrada e saída, binding) acoplado a um plugin principal registrado via a propriedade PluginType. A lógica vive inteiramente em código.
Na prática, a custom API é o sucessor recomendado pela Microsoft para definir mensagens customizadas quando a lógica é pro-code. A custom action continua válida, mas sua força é exatamente permitir a composição no-code.
Binding: unbound, bound to entity, bound to collection
Ambos os mecanismos suportam binding, que determina como a mensagem é chamada na Web API:
- Unbound — função/ação global, sem alvo. Ex.:
POST /api/data/v9.2/dyn_RecalcularCreditoGlobal. - Bound to entity — opera sobre um registro específico de uma tabela. A chamada carrega o
entityIdno path:POST /accounts(id)/Microsoft.Dynamics.CRM.dyn_RecalcularLimite. - Bound to collection — opera no nível da tabela/coleção.
Choose unbound para operações que não pertencem a um registro único (ex.: um job de reconciliação). Use bound quando a operação é semanticamente uma extensão daquele tipo de registro — isso deixa o contrato muito mais legível para quem consome a Web API.
Function vs Action e o critério de side effect
A custom API tem uma propriedade crítica: IsFunction. Quando marcada como function, ela é invocada via GET, não pode ter side effects e seus parâmetros vão na URL — ideal para consultas/cálculos puros que você quer poder compor em queries OData. Quando é action (o padrão), é invocada via POST e pode escrever dados. Modelar uma leitura pura como function deixa explícito o contrato de idempotência para quem integra.
Enabled for workflow / Allowed custom processing step type
Aqui mora uma decisão de governança que a custom API controla e a action não controla tão bem:
- AllowedCustomProcessingStepType define se outros desenvolvedores podem registrar plugins adicionais na sua mensagem (None, AsyncOnly ou SyncAndAsync). Em uma custom API que é parte de um produto/solução gerenciada, deixar
Noneprotege seu contrato de ser estendido por código de terceiros de forma não prevista. - IsPrivate esconde a mensagem do metadata público, útil para APIs internas que não devem virar ponto de extensão.
- EnabledForWorkflow permite (ou não) que a mensagem apareça como ação chamável dentro de processos.
Com custom action, qualquer plugin pode se pendurar no step da action com muito menos controle sobre isso.
Transação, execução e performance
Uma custom API cujo plugin roda no pipeline síncrono participa da transação do Dataverse: se ela lança exceção, tudo faz rollback, exatamente como um plugin comum. Isso é poderoso para encapsular uma operação atômica (ex.: debitar saldo + criar lançamento + atualizar status em uma única chamada transacional). Já a custom action com steps no-code tende a ser mais pesada: o engine de workflow adiciona overhead, e misturar steps declarativos com plugin numa mesma action costuma gerar comportamento difícil de depurar. Para lógica crítica de alto volume, a custom API com plugin único e enxuto é consistentemente mais rápida e previsível.
Roteiro de decisão
- A lógica é inteiramente pro-code (C#) e você quer um contrato estável e versionável? Custom API.
- É uma leitura/cálculo puro sem efeito colateral que você quer compor em OData? Custom API marcada como function.
- Precisa que analistas montem/ajustem a lógica em no-code (steps de workflow) sem recompilar? Custom action ainda faz sentido — ou, melhor ainda, custom API chamada por um fluxo do Power Automate que carrega a parte no-code.
- Precisa travar quem pode estender a mensagem e escondê-la do metadata público? Custom API (AllowedCustomProcessingStepType None + IsPrivate).
- A operação é atômica e precisa de rollback transacional? Plugin síncrono por trás de uma custom API bound.
Cuidados de produção
- Versione o contrato: adicionar parâmetro de saída é seguro; remover/renomear parâmetro de entrada quebra consumidores. Trate a assinatura da sua custom API como uma API pública de verdade.
- Empacote
CustomAPI, seus request/response parameters e oPluginType/assembly na mesma solução gerenciada, senão o deploy entre ambientes falha por dependência quebrada. - Respeite o limite de 2 minutos de execução do pipeline; operações longas devem ser disparadas pela API mas processadas assincronamente (fila no Dataverse, Service Bus).
- Segurança: a custom API respeita as security roles do chamador por padrão; se o plugin faz operações que o usuário não poderia, avalie rodar em contexto de impersonation consciente — nunca dar privilégio demais por conveniência.
Fechamento
Transformar lógica de negócio recorrente em uma mensagem própria do Dataverse é o que separa um ambiente onde cada regra existe em um só lugar — testável, versionada e governada — de um onde a mesma conta está copiada em cinco fluxos e três botões. Na Dynamic Soluções desenhamos essas camadas de serviço no Dataverse com ALM previsível, contratos estáveis e governança de extensão, seja em projetos sob demanda ou dentro dos planos de suporte contínuo. Se sua operação está crescendo em cima da Power Platform, vale estruturar isso antes que a dívida técnica apareça.
When business logic needs to be invoked from several places — a model-driven app button, a Power Automate flow, a Copilot Studio agent, an external application through the Web API — spreading the same rule across each consumption point is an invitation to rework and inconsistency. Dataverse offers two mechanisms to package that logic as its own message, callable like any native platform verb: custom actions (the classic, process-based model) and custom APIs (the modern, declarative model). They seem to solve the same problem, but their architectural differences determine governance, performance and maintenance at scale.
What each one actually is
A custom action is a type of process (a workflow with the Action category) defined in the process designer. You declare input/output arguments and can compose the logic with classic workflow no-code steps and/or plug in code by registering a plugin on the SdkMessageProcessingStep generated for that action. In other words: an action can run both declarative logic (steps) and plugin logic.
A custom API is a pure message definition, modeled by metadata tables (CustomAPI, CustomAPIRequestParameter, CustomAPIResponseProperty). It carries no no-code steps — it is only the contract (message name, input and output parameters, binding) coupled to a main plugin registered via the PluginType property. The logic lives entirely in code.
In practice, the custom API is Microsoft's recommended successor for defining custom messages when the logic is pro-code. The custom action remains valid, but its strength is precisely enabling no-code composition.
Binding: unbound, bound to entity, bound to collection
Both mechanisms support binding, which determines how the message is called in the Web API:
- Unbound — a global function/action with no target. E.g.:
POST /api/data/v9.2/dyn_RecalculateGlobalCredit. - Bound to entity — operates on a specific record of a table. The call carries the
entityIdin the path:POST /accounts(id)/Microsoft.Dynamics.CRM.dyn_RecalculateLimit. - Bound to collection — operates at the table/collection level.
Choose unbound for operations that don't belong to a single record (e.g., a reconciliation job). Use bound when the operation is semantically an extension of that record type — it makes the contract far more readable for whoever consumes the Web API.
Function vs Action and the side-effect criterion
The custom API has a critical property: IsFunction. When marked as a function, it is invoked via GET, cannot have side effects and its parameters go in the URL — ideal for pure queries/calculations you want to compose in OData queries. When it is an action (the default), it is invoked via POST and can write data. Modeling a pure read as a function makes the idempotency contract explicit for integrators.
Enabled for workflow / Allowed custom processing step type
Here lies a governance decision the custom API controls and the action doesn't control as well:
- AllowedCustomProcessingStepType defines whether other developers can register additional plugins on your message (None, AsyncOnly or SyncAndAsync). On a custom API that is part of a product/managed solution, leaving it
Noneprotects your contract from being extended by third-party code in unforeseen ways. - IsPrivate hides the message from the public metadata, useful for internal APIs that shouldn't become an extension point.
- EnabledForWorkflow allows (or not) the message to appear as a callable action inside processes.
With a custom action, any plugin can hook onto the action's step with far less control over this.
Transaction, execution and performance
A custom API whose plugin runs in the synchronous pipeline participates in the Dataverse transaction: if it throws, everything rolls back, exactly like a regular plugin. This is powerful for encapsulating an atomic operation (e.g., debit a balance + create an entry + update status in a single transactional call). A custom action with no-code steps, on the other hand, tends to be heavier: the workflow engine adds overhead, and mixing declarative steps with a plugin in the same action usually produces behavior that's hard to debug. For high-volume critical logic, a custom API with a single lean plugin is consistently faster and more predictable.
Decision guide
- Is the logic entirely pro-code (C#) and do you want a stable, versionable contract? Custom API.
- Is it a pure read/calculation with no side effect that you want to compose in OData? Custom API marked as a function.
- Do you need analysts to build/adjust the logic in no-code (workflow steps) without recompiling? A custom action still makes sense — or, better yet, a custom API called by a Power Automate flow carrying the no-code part.
- Do you need to lock down who can extend the message and hide it from public metadata? Custom API (AllowedCustomProcessingStepType None + IsPrivate).
- Is the operation atomic and does it need transactional rollback? A synchronous plugin behind a bound custom API.
Production caveats
- Version the contract: adding an output parameter is safe; removing/renaming an input parameter breaks consumers. Treat your custom API's signature like a real public API.
- Package the
CustomAPI, its request/response parameters and thePluginType/assembly in the same managed solution, otherwise cross-environment deploys fail on a broken dependency. - Respect the pipeline's 2-minute execution limit; long operations should be triggered by the API but processed asynchronously (Dataverse queue, Service Bus).
- Security: the custom API respects the caller's security roles by default; if the plugin performs operations the user couldn't, consider running under deliberate impersonation — never grant excess privilege for convenience.
Closing
Turning recurring business logic into a Dataverse message of its own is what separates an environment where each rule exists in a single place — testable, versioned and governed — from one where the same calculation is copied across five flows and three buttons. At Dynamic Soluções we design these service layers in Dataverse with predictable ALM, stable contracts and extension governance, whether in on-demand projects or within ongoing support plans. If your operation is growing on top of the Power Platform, it's worth structuring this before technical debt shows up.
