Extending Znode API Models and Responses

TABLE OF CONTENTS


Overview

  • Audience: Partner developers and client technical teams who build integrations, headless storefronts or back-office tools on Znode and need data that the standard API models do not carry.
  • Prepared for: Znode Partners and Clients
  • Product: Znode 10.x. Code examples were checked against Custom API SDK release 10.13.1.0 and the Znode10.Engine.CommercePortal.Client package version that release references (10.0.0-rc-45).
  • Components: Custom API SDK (Custom.Api.Core, Engine.Custom.Api), API gateway routes (CustomOcelot.json), Znode client NuGet packages, Commerce API, user-defined fields, custom tables.
  • Prerequisites: .NET 8 SDK; the Custom API SDK source downloaded with the Znode CLI; access to the Znode NuGet source; API credentials for your environment; a working custom endpoint (see the series guide Creating a Custom Znode API Endpoint).

This guide shows how to add your own fields to the data that Znode APIs return or accept, without changing the Znode platform. You build the extension in the Custom API SDK: call the Znode API through its typed client, add your fields in one clearly named block, and publish the result through the API gateway.

  • After reading it you can choose where custom data should live, design an extended request or response model that other developers understand, and change it later without breaking the applications that call it.
  • You cannot add properties to Znode's own API models or responses. A change to a Znode API goes through a Znode Support request.
  • Store the extra data in a built-in place first (attributes, user-defined fields, custom tables, External ID). Then return it from a Custom API endpoint that calls Znode, maps the fields you need, and adds your fields in one Custom block.
  • Treat that model as a public contract: add fields freely, but never rename, remove or retype one in place.

Every integration sooner or later needs a value that the standard Znode response does not contain: an ERP order status next to each order, a loyalty tier on the customer, a delivery window on the store. Znode 10 allows customization only in the Webstore application and in the Custom API. The Znode platform APIs themselves cannot be modified; a change to them goes through a support ticket.

The Custom API is the place where you extend Znode data contracts. The public API Customization Guide names "modifying response structures" as a Custom API use case, and "custom data posting and logic processing" as one of its key features. You do it by building a new endpoint that calls the Znode API, changes or adds data, and returns your own model.

Extend a model in the Custom API when:

  • A caller needs Znode data plus values from another source in one response.
  • You want to hide Znode fields a caller should not see, or rename them for a partner.
  • A write must carry extra fields that Znode stores elsewhere (for example a user-defined field).
  • You want a stable contract that you version yourself.

Choose something else when:

SituationUse instead
A built-in field already holds and returns the valueThe built-in field (check attributes and user-defined fields first)
You need to change a calculated cart or order totalA method override
You only need to react after something changedEvents and webhooks
You need the Znode API itself to return a new fieldA Znode Support request

Important: Do not try to reach the Znode database from the Custom API. The Custom API has no direct access to the Znode database or Entity Framework; it works only through the Znode APIs.

Glossary

TermMeaning in this guide
Znode API modelThe request or response shape a Znode API defines. You can read it and send it, but not change it.
Client modelThe C# class that a Znode client package (for example Znode.Engine.CommercePortal.Client) generates for an API model. CollectionResponseModel and CollectionDetailsResponseModel are examples.
Extended modelYour own request or response class in Custom.Api.Core. It holds the Znode fields you need plus your own fields.
Custom blockOne nested object (named Custom in this guide) that holds every field you add. It tells a reader at a glance which fields come from Znode and which come from you.
Enrichment sourceWhere the extra values come from: a user-defined field, a custom table, an ERP or another service.
Gateway routeAn entry in Engine.Custom.Api/Ocelot/CustomOcelot.json that sends a public path to your Custom API. Its Key must be customapi.
Additive changeA new optional field. Callers that do not know it keep working.
Breaking changeRemoving, renaming or retyping a field, or changing what a value means. Callers fail or misbehave.

Custom Data

Extending a response is easier when the data already has a home. Before you write a model, pick the lightest built-in option that can store the value. Some of these already appear in standard Znode responses, so you may not need an extended model at all.

The extra data is…Store it inHow it reaches an API response
A value on a product or categoryA PIM attribute in the product's attribute familyReturned with the product after the product or catalog is published
One value on a store, account, user, promotion, voucher, content container or formA user-defined field (Admin: Dev Center > User-defined Fields)Store: GlobalAttributes.Attributes[] on GET /v2/portals/{storeCode}. User: AdditionalAttributes[]. Account: Attributes[] on GET /v2/accounts/{accountCode}
A list, mapping, lookup or flag set (for example ERP ids to Znode ids)A custom tableNot added to other responses. Read it through the Dynamic Data Table API in your endpoint
An occasional key and value on one productA product custom fieldShown in the product's Additional Information tab on the storefront after publish
An identifier from another system on an order, user or accountExternal IDAlready a field on Znode models, for example ExternalId on each order in the Commerce API list
A changed cart or order totalA method override that returns the overridden valuesZnode applies the overridden values to its own response
Large, fast-changing or relational dataYour own data store behind a Custom API endpointOnly through your endpoint

Tip: User-defined field values are returned by the Core v2 entity calls listed above, so a caller that already reads the store, account or user may not need a new endpoint. The Webstore does not show a custom user-defined field by itself; showing it needs Webstore code.

Note: Znode contains an Order entity type for user-defined fields, but whether you can add your own fields to it on your release, and whether the Commerce API order calls return them, is not confirmed. Check Dev Center > User-defined Fields > Entity Attributes on your environment for an Order entity, then read one order through the Commerce API before relying on it. Until then, keep order-level custom data in a custom table keyed by order number.

Custom API Flow

Extended response flow: your application calls the API gateway (CustomOcelot.json route, Key: customapi); 1, the gateway routes to the Controller in the Custom API (Custom.Api.Core); 2, the Service calls the Znode API through a typed client (for example ICommerceCollectionsClient); 3, the Service reads ICacheService (InMemory or Redis), which reads your extension data (custom table, ERP, user-defined fields); 4, the Mapper builds your response model; 5, the extended response (Znode fields plus one Custom block) returns to your application.

An extended response: the Custom API calls Znode, adds your data from a cached source and returns one model.

  1. Route. Your application calls a public path on the API gateway. A route in CustomOcelot.json with Key: customapi sends it to your controller in Custom.Api.Core.
  2. Znode call. Your service calls the Znode API through a typed client that is registered in CustomDependencyRegistration, and gets the standard client model back.
  3. Enrichment. The service looks up your extra values. It reads ICacheService first and calls the source (custom table, ERP, user-defined field) only for values it does not have.
  4. Mapping. A mapper copies the Znode fields the caller needs into your extended model and puts your fields in the Custom block.
  5. Response. The controller returns the extended model. Callers see one stable contract that you own.

The timing of your change depends on the direction of the call. The API Customization Guide puts it this way: for a read (GET), apply changes after the Znode API returns data; for a write (POST), apply changes before you call the Znode API.

Read (GET) flow: request arrives, call Znode API, add custom fields, return extended response. Write (POST, PUT) flow: extended request, split the model, call Znode API with standard fields only, save custom part.

Design an Extended Model People Can Maintain

A custom field is cheap to add and expensive to explain later. These rules keep an extended model readable for the next developer and safe for the applications that call it.

Keep Znode Fields and Your Fields Apart

  • Copy Znode fields with the same name and meaning as in the Znode model (ClassNumber, ClassStatus, Total). A reader who knows the Znode API recognizes them at once.
  • Put every field you add into one nested Custom object. Do not scatter new fields among Znode ones, and do not reuse a Znode field name for a different value.
  • Return only the Znode fields the caller needs. Do not pass a whole client model through when a few fields are enough: it couples your callers to every future change in the Znode model.
  • Give each custom field a name that says what it is and where it comes from (ErpStatus, ErpLastSyncedUtc), and a unit or time zone where it matters.
  • Make new fields nullable. A missing value then reads as "unknown", not as 0 or false.

Composition or Inheritance

The client model classes are not sealed (checked in Znode10.Engine.CommercePortal.Client 10.0.0-rc-45), so you can either wrap selected fields in your own class or derive from a client class.

ApproachHow it worksEffectCost
Composition (recommended)Your class copies the Znode fields it needs and adds a Custom block.Your contract changes only when you change it. Mapping code is explicit and easy to test.You add a mapping line when you want another Znode field.
InheritanceYour class derives from the client class and adds a Custom property.Every Znode field appears in your response with no mapping code.When you update the client package, new or changed Znode fields flow into your contract unnoticed. Callers see every Znode field, including ones you meant to hide.

Treat the Model as a Contract

ChangeSafe for existing callers?What to do
Add a new optional field (in Custom)YesAdd it, document it, keep it nullable
Add a new optional request field with a safe defaultYesTreat a missing value exactly as before
Rename or remove a fieldNoPublish a new versioned route; keep the old one until callers move
Change a field's type (number to string, value to list)NoAdd a new field or a new version
Change what a value meansNoAdd a new field with the new meaning
Make an optional request field required, or tighten validationNoNew version, or accept both for a transition period
Change a status code for an existing caseNoNew version

Tip: Version in the route, for example /CustomOrder/v2/..., and run both versions side by side. This is the same pattern Znode uses for its own APIs (v2, v2.1 and v2.2 add operations next to v2).

Example - Extend the Order List With ERP Fields

The example returns a user's orders from the Commerce API, keeps six Znode fields, and adds an ERP order number and status from your ERP. It follows the shape of the SDK's own CustomPortalController and CustomService samples.

StepActionExpected result
1Create the model classes in Custom.Api.Core (code below: CustomOrderModels.cs).The project builds; the classes have XML comments.
2Define the enrichment source as an interface (IErpOrderStatusProvider) and implement it against your ERP or custom table.One call returns the custom fields for a set of order numbers.
3Add the service (CustomOrderService.cs). It calls Znode, maps the fields, and fills the Custom block from the cache or the provider.The service compiles against the client package.
4Register the service and the provider in App_Start/CustomDependencyRegistration.cs.The host starts without a "Unable to resolve service" error.
5Add the controller (CustomOrderController.cs).The new action appears in Swagger with the CustomOrderListResponse schema and its descriptions.
6Add the gateway route to Engine.Custom.Api/Ocelot/CustomOcelot.json with Key: customapi.The route sits next to the sample routes in the file.
7Run the Custom API locally and call the action from Swagger.HTTP 200 with a Custom block on each order, or 204 when the user has no orders.
8Deploy with the Znode CLI: znode deploy CustomAPISDK <Environment>.The deployment finishes and the route answers through the gateway (see the curl call below).

The Extended Response Model

All new fields sit in OrderCustomFields. The Znode fields keep their Znode names and types (checked against the client package).

C# model classes (CustomOrderModels.cs):

namespace Custom.Api.Core
{
    /// <summary>Orders of one user, with fields added by this Custom API.</summary>
    public class CustomOrderListResponse
    {
        /// <summary>Page number from the Znode response (1-based).</summary>
        public int? PageIndex { get; set; }

        /// <summary>Page size from the Znode response.</summary>
        public int? PageSize { get; set; }

        /// <summary>Total number of orders that match, from the Znode response.</summary>
        public int? TotalResults { get; set; }

        /// <summary>One entry per order.</summary>
        public List<CustomOrderSummary> Orders { get; set; } = new();
    }

    /// <summary>One order. Znode fields keep their Znode names; added fields are in Custom.</summary>
    public class CustomOrderSummary
    {
        /// <summary>Znode order number.</summary>
        public string? ClassNumber { get; set; }

        /// <summary>Znode order status.</summary>
        public string? ClassStatus { get; set; }

        /// <summary>Znode order date.</summary>
        public DateTime? OrderDate { get; set; }

        /// <summary>Znode order total.</summary>
        public double Total { get; set; }

        /// <summary>Znode store code.</summary>
        public string? StoreCode { get; set; }

        /// <summary>Znode External ID of the order.</summary>
        public string? ExternalId { get; set; }

        /// <summary>Fields added by this Custom API. Not part of the Znode model.</summary>
        public OrderCustomFields Custom { get; set; } = new();
    }

    /// <summary>Custom fields for an order. Source: the ERP. Null means unknown.</summary>
    public class OrderCustomFields
    {
        /// <summary>True when the ERP lookup succeeded for this order.</summary>
        public bool Available { get; set; }

        /// <summary>Order number in the ERP.</summary>
        public string? ErpOrderNumber { get; set; }

        /// <summary>Order status in the ERP, for example Released or Shipped.</summary>
        public string? ErpStatus { get; set; }

        /// <summary>When the ERP values were read, in UTC.</summary>
        public DateTime? ErpLastSyncedUtc { get; set; }
    }
}

The Enrichment Source

Keep the source behind an interface so you can swap an ERP call for a custom-table lookup, and mock it in tests. Ask for many orders in one call; one remote call per order makes the endpoint slow.

C# interface (IErpOrderStatusProvider):

namespace Custom.Api.Core
{
    /// <summary>
    /// Reads custom order fields from the system that owns them.
    /// </summary>
    public interface IErpOrderStatusProvider
    {
        /// <summary>
        /// Returns the custom fields for each order number found.
        /// Missing numbers are left out.
        /// </summary>
        Task<IReadOnlyDictionary<string, OrderCustomFields>> GetCustomFieldsAsync(
            IReadOnlyCollection<string> orderNumbers);
    }
}

The Service: Call Znode, Map, Enrich

The Znode call is the same as in the SDK sample CustomService.GetOrderList. The cache calls use the SDK's ICacheService (GetCacheData<T>, SetCacheData).

C# service (CustomOrderService.cs):

using System.Diagnostics;
using Znode.Engine.Api.Client;
using Znode.Engine.CommercePortal.Client;
using Znode.Libraries.Abstract.Client.Sorts;
using Znode.Libraries.Abstract.Helper;
using Znode.Libraries.Common.Logger;

namespace Custom.Api.Core
{
    /// <summary>
    /// Returns Znode orders extended with custom fields.
    /// </summary>
    public interface ICustomOrderService
    {
        /// <summary>
        /// Gets a user's orders from Znode and adds the ERP fields.
        /// </summary>
        Task<CustomOrderListResponse> GetOrdersWithErpStatusAsync(
            string userId,
            string portalCode);
    }

    /// <summary>
    /// Calls the Znode Commerce API, maps the result and fills the Custom block.
    /// </summary>
    public class CustomOrderService : ICustomOrderService
    {
        private static readonly TimeSpan CustomFieldsCacheLifetime = TimeSpan.FromMinutes(5);

        private readonly ICommerceCollectionsClient _commerceCollectionsClient;
        private readonly IErpOrderStatusProvider _erpOrderStatusProvider;
        private readonly ICacheService _cacheService;
        private readonly IZnodeLogging _znodeLogging;

        public CustomOrderService(
            ICommerceCollectionsClient commerceCollectionsClient,
            IErpOrderStatusProvider erpOrderStatusProvider,
            ICacheService cacheService,
            IZnodeLogging znodeLogging)
        {
            _commerceCollectionsClient = commerceCollectionsClient;
            _erpOrderStatusProvider = erpOrderStatusProvider;
            _cacheService = cacheService;
            _znodeLogging = znodeLogging;
        }

        public virtual async Task<CustomOrderListResponse> GetOrdersWithErpStatusAsync(
            string userId,
            string portalCode)
        {
            // 1. Call Znode (same pattern as the SDK sample).
            FilterCollection filters = new FilterCollection();
            filters.Add(new FilterTuple("UserId", FilterOperators.Equals, userId));

            SortCollection sorts = new SortCollection();

            Dictionary<string, string> headers = new Dictionary<string, string>
            {
                { "Znode-UserId", userId },
                { "Znode-PortalCode", portalCode },
                { "Znode-LocaleCode", "en-US" },
                { "Znode-PublishState", "Production" }
            };

            _commerceCollectionsClient.SetCustomHeadersExplicitly(headers);

            CollectionResponseModel znodeOrders =
                _commerceCollectionsClient.GetListByClassType(
                    "Orders",
                    filters,
                    sorts,
                    1,
                    50);

            // 2. Map only the Znode fields the caller needs.
            CustomOrderListResponse response = new CustomOrderListResponse
            {
                PageIndex = znodeOrders?.PaginationDetail?.PageIndex,
                PageSize = znodeOrders?.PaginationDetail?.PageSize,
                TotalResults = znodeOrders?.PaginationDetail?.TotalResults,
                Orders = (znodeOrders?.CollectionDetails ??
                          new List<CollectionDetailsResponseModel>())
                    .Select(order => new CustomOrderSummary
                    {
                        ClassNumber = order.ClassNumber,
                        ClassStatus = order.ClassStatus,
                        OrderDate = order.OrderDate,
                        Total = order.Total,
                        StoreCode = order.StoreCode,
                        ExternalId = order.ExternalId
                    })
                    .ToList()
            };

            // 3. Fill the Custom block.
            await AddCustomFieldsAsync(response.Orders);

            return response;
        }

        private async Task AddCustomFieldsAsync(List<CustomOrderSummary> orders)
        {
            List<string> missing = new List<string>();

            foreach (CustomOrderSummary order in
                     orders.Where(o => !string.IsNullOrEmpty(o.ClassNumber)))
            {
                OrderCustomFields? cached =
                    _cacheService.GetCacheData<OrderCustomFields>(
                        CacheKey(order.ClassNumber!));

                if (cached != null)
                {
                    order.Custom = cached;
                }
                else
                {
                    missing.Add(order.ClassNumber!);
                }
            }

            if (missing.Count == 0)
            {
                return;
            }

            try
            {
                IReadOnlyDictionary<string, OrderCustomFields> found =
                    await _erpOrderStatusProvider.GetCustomFieldsAsync(missing);

                foreach (CustomOrderSummary order in
                         orders.Where(o =>
                             o.ClassNumber != null &&
                             missing.Contains(o.ClassNumber)))
                {
                    if (found.TryGetValue(
                        order.ClassNumber!,
                        out OrderCustomFields? fields))
                    {
                        fields.Available = true;
                        order.Custom = fields;

                        _cacheService.SetCacheData(
                            CacheKey(order.ClassNumber!),
                            fields,
                            CustomFieldsCacheLifetime);
                    }
                }
            }
            catch (Exception ex)
            {
                // The Znode data is still returned; Custom.Available stays false.
                _znodeLogging.LogMessage(
                    ex.Message,
                    "CustomAPILoggingComponent",
                    TraceLevel.Error);
            }
        }

        private static string CacheKey(string orderNumber) =>
            $"order-custom-fields:{orderNumber}";
    }
}

What to change: the filter, the class type (Orders), the page size, the locale and publish state headers, the cache key and the cache lifetime. Keep the lifetime short for values that change often: the Custom API Caching Guide suggests 1 to 5 minutes for display pricing and always-live values for checkout pricing and inventory. The same guide recommends cache keys that include the environment, store and locale, so add them to CacheKey when one Custom API serves several stores.

Dependency Registration

Add two lines to RegisterCustomDI. ICommerceCollectionsClient is already registered by the SDK, and ICacheService is registered by RegisterCustomApiServices in the host.

C# dependency registration (CustomDependencyRegistration.cs):

// Custom.Api.Core/App_Start/CustomDependencyRegistration.cs, inside RegisterCustomDI

builder.Services.AddScoped<ICustomOrderService, CustomOrderService>();

builder.Services.AddScoped<IErpOrderStatusProvider, ErpOrderStatusProvider>(); // your implementation

The Controller

The controller follows the SDK sample CustomSampleEntityController: inject the service, return NoContent() for an empty result, Ok(model) otherwise, and log and return 500 on an exception. ProducesResponseType tells Swagger which model the action returns.

C# controller (CustomOrderController.cs):

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using Znode.Libraries.Common.Exceptions;
using Znode.Libraries.Common.Logger;

namespace Custom.Api.Core
{
    /// <summary>
    /// Order endpoints that extend the Znode order list.
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    public class CustomOrderController : ControllerBase
    {
        private readonly IZnodeLogging _znodeLogging;
        private readonly ICustomOrderService _customOrderService;

        public CustomOrderController(
            IZnodeLogging znodeLogging,
            ICustomOrderService customOrderService)
        {
            _znodeLogging = znodeLogging;
            _customOrderService = customOrderService;
        }

        /// <summary>
        /// Returns a user's orders. ERP fields are in the Custom block of each order.
        /// </summary>
        [HttpGet("GetOrdersWithErpStatus/{userId}/{portalCode}")]
        [ProducesResponseType(
            typeof(CustomOrderListResponse),
            StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> GetOrdersWithErpStatus(
            string userId,
            string portalCode)
        {
            try
            {
                // Check here that the caller is allowed to read this user's orders.
                CustomOrderListResponse response =
                    await _customOrderService.GetOrdersWithErpStatusAsync(
                        userId,
                        portalCode);

                if (response.Orders.Count == 0)
                {
                    return NoContent();
                }

                return Ok(response);
            }
            catch (ZnodeException ex)
            {
                _znodeLogging.LogMessage(
                    ex.Message,
                    "CustomAPILoggingComponent",
                    TraceLevel.Error);

                return StatusCode(StatusCodes.Status500InternalServerError);
            }
            catch (Exception ex)
            {
                _znodeLogging.LogMessage(
                    ex.Message,
                    "CustomAPILoggingComponent",
                    TraceLevel.Error);

                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }
    }
}

Important: The route takes a user id from the caller. Your endpoint must check that the caller may read that user's data, for example by comparing it with the user in the token. Znode does not enforce ownership for your custom endpoint.

The Gateway Route

JSON route to add to the routes in Engine.Custom.Api/Ocelot/CustomOcelot.json:

{
  "DownstreamPathTemplate": "/CustomOrder/GetOrdersWithErpStatus/{userId}/{portalCode}",
  "UpstreamPathTemplate": "/CustomOrder/GetOrdersWithErpStatus/{userId}/{portalCode}",
  "UpstreamHttpMethod": [
    "GET"
  ],
  "Key": "customapi",
  "SwaggerKey": "customapi",
  "Priority": 1
}

Call It Through the Gateway

HTTP call with curl:

curl -X GET "<your-api-gateway-url>/CustomOrder/GetOrdersWithErpStatus/<user-id>/<store-code>" \
  -H "Authorization: Bearer <your-jwt>" \
  -H "Accept: application/json"

A response has this shape (values are illustrative):

{
  "pageIndex": 1,
  "pageSize": 50,
  "totalResults": 1,
  "orders": [
    {
      "classNumber": "<order-number>",
      "classStatus": "SUBMITTED",
      "orderDate": "2026-11-20T14:05:00",
      "total": 120.5,
      "storeCode": "<store-code>",
      "externalId": null,
      "custom": {
        "available": true,
        "erpOrderNumber": "<erp-order-number>",
        "erpStatus": "Released",
        "erpLastSyncedUtc": "2026-11-20T14:10:00Z"
      }
    }
  ]
}

Note: The property casing above assumes ASP.NET Core's default JSON settings, which apply to Ok(model) because the SDK host calls AddControllers() without JSON options. The SDK's CustomBaseController.CreateOKResponse serializes with Newtonsoft.Json instead and keeps the C# names (PascalCase). Call your deployed endpoint once and check the casing before you publish the contract; then use the same method for every endpoint.

Extending a Request (Write) Model

For a write, accept one request model that holds the Znode fields and a Custom block, validate all of it, then split it: send the Znode part to the Znode API first, and save the custom part only after Znode accepts the record. Data annotations on the model give a 400 response for invalid input, because the controller carries [ApiController].

C# request model:

using System.ComponentModel.DataAnnotations;

namespace Custom.Api.Core
{
    /// <summary>
    /// Update request for an account with one extra field.
    /// </summary>
    public class CustomAccountUpdateRequest
    {
        /// <summary>
        /// Znode account code. Required.
        /// </summary>
        [Required]
        public string AccountCode { get; set; } = string.Empty;

        /// <summary>
        /// Fields added by this Custom API.
        /// </summary>
        public AccountCustomFields Custom { get; set; } = new();
    }

    /// <summary>
    /// Custom account fields. Stored in the account user-defined field PoApprovalCode.
    /// </summary>
    public class AccountCustomFields
    {
        /// <summary>
        /// Purchase order approval code, up to 50 characters.
        /// </summary>
        [StringLength(50)]
        public string? PoApprovalCode { get; set; }
    }
}

Where to save the custom part: a user-defined field value is written with PUT /v2/global-entity-attributes (Core API v2), a custom table row with the Dynamic Data Table API. The user-defined field call takes a list of values. Each value names the field (AttributeCode), the record (EntityType and EntityCode; for an account, the account code) and the locale. Send values for one entity type per request, and set the Znode-PortalCode header.

JSON request body for PUT /v2/global-entity-attributes:

[
  {
    "AttributeCode": "PoApprovalCode",
    "AttributeValue": "<approval-code>",
    "LocaleCode": "<locale-code>",
    "EntityType": "Account",
    "EntityCode": "<account-code>"
  }
]

Validate lengths, formats and required values in your code: the write call checks only that the field and the record exist and that dates, numbers and select options are valid. It does not check Required, maximum length, pattern or uniqueness, and it cannot clear a value (blank values are rejected). The response echoes each value with an IsSuccess flag; check it for every value.

Note: Send one test value from Swagger or Postman on a development environment before you code against this call, and confirm the locale code your store uses.

Wrapping an Existing Znode Route

Sometimes a caller already uses a Znode route and you want it to receive extra fields without changing its URL. The API Customization Guide describes this: add a route to CustomOcelot.json that redirects the request to your Custom API instead of the Znode API, use customapi as the key, and give the custom route a higher priority than the Znode route so that it takes precedence. Your code then calls the Znode API itself and returns the extended model. Treat this approach as unconfirmed until you have tested it on your environment (see the note below).

Important: A wrapped route changes the response for every caller of that path, including Znode's own applications if they call it through the gateway. Keep every Znode field with its original name, type and meaning, and only add fields. Prefer a new route when you can.

Note: Taking over a standard Znode route this way is not confirmed. The sources do not state (1) the priority values that the Znode routes use, so you know which value is "higher", or which route the gateway picks when both match, and (2) that the Znode client inside your Custom API reaches the Znode service directly (through ZnodeApiRootUri) and not back through the gateway path you took over. If your handler calls the same Znode route through the gateway, the request comes back to your handler and loops. To test it: ask Znode Support for the route priorities of your environment, deploy the route to a development environment, call the path through the gateway and check that the response contains your custom fields, and watch the Custom API logs for repeated calls to the same action.

Make Custom Fields Self-Explanatory

  • Write an XML <summary> on every class and property. Custom.Api.Core generates its documentation file (GenerateDocumentationFile is on, output bin\Custom.Api.Core.xml), and the host's SwaggerConfig includes that file, so your comments appear in Swagger.
  • Say in each custom field's comment where the value comes from and what null means.
  • Declare the response type with ProducesResponseType so Swagger shows the full schema, not just "200".
  • Keep a short change log of the model (version, date, field added) next to the code, and publish it with the API description that partners use. The series guide Documenting Custom APIs Alongside Znode API Reference covers this in depth.
  • The SDK's Swagger setup uses full type names as schema ids (CustomSchemaIds(type => type.FullName)), so a namespace rename changes the schema names that callers see. Pick namespaces once.

Configuration

SettingWherePurposeExample or default
KeyCustomOcelot.json routeSends the route to the Custom API. Must be customapicustomapi
PriorityCustomOcelot.json routeOrders routes that match the same path. Whether a custom route can take precedence over a Znode route is not confirmed; test it first1 in the SDK sample routes
UpstreamHttpMethodCustomOcelot.json routeHTTP methods the route accepts[ "GET" ]
ZnodeApiRootUriappsettings section of appsettings.json, or the environment variable appsettings__ZnodeApiRootUriURL of the Znode API that the clients call (the SDK README asks you to set it)<your-znode-api-url>
ZnodeApiDomainName and ZnodeApiDomainKeyappsettings section of appsettings.jsonClient name and client key the Custom API uses to authenticate to Znode (Basic credential); see the series guide Authenticating to Znode APIsSet per environment; never commit values
Caching.CacheTypeappsettings.jsonCache backend behind ICacheServiceInMemory or Redis
Caching.RedisCacheConnectionStringappsettings.jsonRedis connection when CacheType is RedisFrom an environment variable or key vault
Caching.CacheExpirationMinutesappsettings.jsonDefault cache lifetime60 in the SDK appsettings.json
GenerateDocumentationFileCustom.Api.Core.csprojProduces the XML file Swagger readsTrue in the SDK

Note: CustomBaseController.ToJson drops properties that hold their default value (0, false, null) when ZnodeApiSettings.MinifiedJsonResponse is on. Where that setting is configured for the Custom API is not confirmed in the SDK source. If you return models through CreateOKResponse, call an endpoint with a false or 0 custom value and check whether the property is present.

Golden Rules

  • Look for a built-in field first: A user-defined field or attribute that Znode already returns needs no extended model, no deployment and no upgrade work.
  • Batch and cache enrichment lookups: One remote call per item in a list response is the most common cause of a slow custom endpoint. Never cache checkout prices or inventory decisions.
  • Degrade gracefully: If the enrichment source fails, return the Znode data with the custom block marked as unavailable, and log the error, instead of failing the whole call.
  • Pin and review client package versions: When you update a Znode client package, rebuild, check the fields your mapper reads, and run your contract tests.
  • Do not log tokens, keys, card data or full request bodies. Log IDs and counts, as the SDK samples do with IZnodeLogging.
  • The SDK template's CORS policy allows any origin. Restrict it to your own front-end origins before you expose an extended endpoint in production.
  • Never expose the Dynamic Data Table API or its credentials to a browser. Put your own endpoint, with its own authorization, in front of custom-table data.

Troubleshooting

SymptomLikely causeFix
The action works on the Custom API host but returns 404 through the gatewayThe route is not registered (no route in CustomOcelot.json, or a Key other than customapi), or the upstream path or the downstream host or port is wrongAdd or correct the route and its path, host and port, redeploy with the Znode CLI
A wrapped Znode route still returns the standard responseThe gateway sends the call to the Znode route, not to yours. Taking over a Znode route with a higher priority is not confirmedAsk Znode Support for the route priorities of your environment, test on a development environment, or use a new route of your own
Host fails at start or on first call with "Unable to resolve service for type…"The service, provider or Znode client is not registeredAdd it to RegisterCustomDI
The Znode part of the response is emptyMissing or wrong context headers (Znode-PortalCode, Znode-UserId, Znode-LocaleCode, Znode-PublishState)Set the headers with SetCustomHeadersExplicitly before the call
Custom block is empty or available is falseThe enrichment source failed or has no record for that keyCheck the Custom API log; test the provider on its own
Custom values are out of dateCached longer than the data changesShorten the cache lifetime or remove the key when the source changes
A false or 0 custom field is missing from the JSONDefault values are dropped when minified JSON is on (CreateOKResponse)Use nullable types, return with Ok(), or document that a missing field means the default
Field names are camelCase on one endpoint and PascalCase on anotherSome actions use Ok(), others CreateOKResponsePick one method for all endpoints
The endpoint is slow on large listsOne enrichment call per itemBatch the lookup and cache per key
A user-defined field value is not in the store responseThe value is blank (the store response leaves blanks out) or the field is not in a group the entity usesSet a value; check the field's group and family under Dev Center > User-defined Fields
PUT /v2/global-entity-attributes returns 404 with "Invalid data: …"Unknown field code, a record that does not exist for that EntityType and EntityCode, or an invalid or blank valueCheck the codes named in the message; send a non-blank value of the field's type
401 from the gatewayMissing or expired tokenGet a new token; see the series guide Authenticating to Znode APIs

FAQ

Q: Can I add a property to a Znode API response directly?

No. Znode platform APIs cannot be modified by customers or partners. Build an extended endpoint in the Custom API, or raise a Znode Support request for a platform change.

Q: Can my Custom API read the Znode database to get the extra value faster?

No. The Custom API has no direct access to the Znode database. Use the Znode APIs, a user-defined field, a custom table or your own data store.

Q: Should I inherit from the Znode client model or copy fields?

Copy the fields you need (composition) for a stable contract. Inherit only when the caller truly needs every Znode field and you accept that client package updates change your response.

Q: Does the Webstore show my custom fields automatically?

No. Showing a custom field on the storefront needs Webstore code that calls your endpoint, typically through the Webstore's server side.

Q: How do I change a custom field's meaning or type later?

Add a new field or publish a new versioned route. Keep the old field and route until every caller has moved.

Q: Can a method override add fields to a Znode response?

No. A method override can change specific values in a few platform operations (for example overridden totals after cart calculation). Znode reads back only the documented overridden fields.

References

Source articles:

Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.