Логотип Bc Api Query Generator

Bc Api Query Generator

Сообщество
fernandoartalf
bc-api-query-generator

Generates API query objects for Business Central that expose data via OData/REST endpoints using the QueryType = API pattern. Creates queries with single or multiple dataitems (table joins), proper API properties, column mappings, aggregation methods (Sum, Count, Average, Min, Max), filters, DataItemLink joins (InnerJoin, LeftOuterJoin, CrossJoin), and DataItemTableFilter. Supports multi-version APIs, date filters, and dimension columns. Use when asked to create an API query, generate a query endpoint, build a read-only API from joined tables, expose aggregated data via API, create reporting queries, or implement OData query endpoints.

Обзор

Издательfernandoartalf
РепозиторийAL-Copilot-Skills-Collection
Название навыкаbc-api-query-generator
Звёзды
28
Форки
8
Файлы в комплекте
3
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 3

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — fernandoartalf. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Bc Api Query Generator в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/fernandoartalf/AL-Copilot-Skills-Collection/tree/main/skills/bc-api-query-generator
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/fernandoartalf/AL-Copilot-Skills-Collection.git /tmp/AL-Copilot-Skills-Collection
mkdir -p .claude/skills
cp -r /tmp/AL-Copilot-Skills-Collection/skills/bc-api-query-generator .claude/skills/bc-api-query-generator
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Bc Api Query Generator в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Bc Api Query Generator, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Bc Api Query Generator не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Business Central API Query Generator

Generates production-ready AL API query objects following Microsoft's API standards. Handles single-table and multi-table join patterns, aggregation, filtering, and proper OData endpoint configuration.

Overview

API queries (QueryType = API) expose read-only data via OData endpoints. Unlike API pages, queries:

  • Support joining multiple tables via nested dataitems
  • Support aggregation methods (Sum, Count, Average, Min, Max)
  • Support filters exposed as OData query parameters
  • Are read-only — no INSERT, UPDATE, DELETE
  • Cannot be extended

This skill generates:

  • API query with proper metadata properties
  • Single or multi-dataitem layouts with join configuration
  • Column mappings with camelCase naming
  • Aggregation and filter elements
  • File placed following feature-based folder convention

Advanced patterns and join examples: references/query-examples.md

Prerequisites

  • AL workspace with established object ID range
  • Source table(s) identified with join relationships
  • Clear list of columns to expose
  • API publisher, group, and version defined

Quick Start

al
query [ID] "[Prefix] [Entity] API"
{
    QueryType = API;
    APIPublisher = '[publisher]';
    APIGroup = '[group]';
    APIVersion = 'v2.0';
    Caption = '[entityCaption]', Locked = true;
    EntityName = '[entityName]';         // camelCase, singular
    EntitySetName = '[entityNames]';     // camelCase, plural

    elements
    {
        dataitem([dataItemName]; "[Source Table]")
        {
            column([fieldAlias]; "[Field Name]")
            {
                Caption = '[Caption]', Locked = true;
            }
        }
    }
}

Endpoint URL: ../[publisher]/[group]/[version]/companies({id})/[entitySetName]

API Query Properties

PropertyGuideline
QueryTypeAlways API for web service queries
APIPublisherCompany/publisher identifier, lowercase, no spaces
APIGroupLogical group: sales, purchasing, inventory, finance, reporting
APIVersionUse 'v2.0' or list 'v1.0', 'v2.0' for multi-version support
CaptionUse camelCase entity name, always Locked = true
EntityNamecamelCase, singular (e.g., customerSale, itemLedgerEntry)
EntitySetNamecamelCase, plural (e.g., customerSales, itemLedgerEntries)

DataItem Pattern — Single Table

Use for simple read-only exposure of a single table:

al
query [ID] "[Prefix] [Entity] API"
{
    QueryType = API;
    APIPublisher = '[publisher]';
    APIGroup = '[group]';
    APIVersion = 'v2.0';
    Caption = '[entityCaption]', Locked = true;
    EntityName = '[entityName]';
    EntitySetName = '[entityNames]';

    elements
    {
        dataitem([dataItemName]; "[Source Table]")
        {
            // Primary key / identifier columns
            column([alias]; "[Key Field]")
            {
                Caption = '[Caption]', Locked = true;
            }

            // Business data columns
            column([alias]; "[Business Field]")
            {
                Caption = '[Caption]', Locked = true;
            }

            // Date columns
            column([alias]; "[Date Field]")
            {
                Caption = '[Caption]', Locked = true;
            }

            // Amount / numeric columns
            column([alias]; "[Amount Field]")
            {
                Caption = '[Caption]', Locked = true;
            }

            // Dimension columns (if applicable)
            column([alias]; "[Dimension Field]")
            {
                Caption = '[Caption]', Locked = true;
            }
        }
    }
}

DataItem Pattern — Multi-Table Join

Use for joining related tables. Nest dataitems to create SQL JOINs:

al
query [ID] "[Prefix] [Entity] API"
{
    QueryType = API;
    APIPublisher = '[publisher]';
    APIGroup = '[group]';
    APIVersion = 'v2.0';
    Caption = '[entityCaption]', Locked = true;
    EntityName = '[entityName]';
    EntitySetName = '[entityNames]';

    elements
    {
        dataitem([parentDataItem]; "[Parent Table]")
        {
            // Parent table columns
            column([alias]; "[Parent Field]")
            {
                Caption = '[Caption]', Locked = true;
            }

            dataitem([childDataItem]; "[Child Table]")
            {
                DataItemLink = "[Child FK Field]" = [parentDataItem]."[Parent PK Field]";
                SqlJoinType = InnerJoin;

                // Child table columns
                column([alias]; "[Child Field]")
                {
                    Caption = '[Caption]', Locked = true;
                }

                // Aggregation column example
                column([alias]; "[Amount Field]")
                {
                    Caption = '[Caption]', Locked = true;
                    Method = Sum;
                }

                // Filter element example
                filter([filterAlias]; "[Filter Field]")
                {
                    Caption = '[Caption]', Locked = true;
                }
            }
        }
    }
}

SqlJoinType Property

Sets the data item link type between data items to determine the records included in the resulting dataset. Always set on the lower (nested) data item. Works together with DataItemLink to combine records — except for CrossJoin, which requires DataItemLink to be blank.

al
SqlJoinType = InnerJoin;
Join TypeDescriptionWhen to Use
LeftOuterJoinReturns every record from the upper (parent) data item, even if no matching record exists in the lower data item. Non-matching lower fields return null/default values.Most common for API queries. Use when you need all parent records regardless of child matches (e.g., all customers even those with no ledger entries).
InnerJoinReturns only records where a match is found between linked fields in both data items. Records without matches in either table are excluded.Use when you only want records that exist in both tables (e.g., only items that have been sold).
RightOuterJoinReturns every record from the lower (child) data item, even if no matching record exists in the upper data item. Non-matching upper fields return null/default values.Use when the child table is the primary dataset and you want all child records even without parent matches. Less common in API queries.
FullOuterJoinReturns all records from both data items, including records that have no matching value in either table. Non-matching fields return null/default values on both sides.Use for complete datasets where no records should be excluded (e.g., reconciliation queries).
CrossJoinProduces a Cartesian product — every row from the upper data item combined with every row from the lower data item. DataItemLink must be blank.Rarely needed. Use for generating all possible combinations (e.g., item × location matrix). Can produce very large datasets — use with caution.

Remarks:

  • The SqlJoinType property is always set on the lower (nested) data item, never on the root data item.
  • For LeftOuterJoin, InnerJoin, RightOuterJoin, and FullOuterJoin, the DataItemLink property establishes an "equal to" (=) comparison between fields.
  • For CrossJoin, the DataItemLink property must be left blank — no field comparisons are made.
  • When no SqlJoinType is specified, the default is LeftOuterJoin.

Choosing the right join type:

LeftOuterJoin (most common for APIs):
  Parent: [A, B, C]    Child: [A, B]
  Result: [A+A, B+B, C+null]  ← All parents included

InnerJoin:
  Parent: [A, B, C]    Child: [A, B]
  Result: [A+A, B+B]          ← Only matches

RightOuterJoin:
  Parent: [A, B]       Child: [A, B, D]
  Result: [A+A, B+B, null+D]  ← All children included

FullOuterJoin:
  Parent: [A, B, C]    Child: [A, B, D]
  Result: [A+A, B+B, C+null, null+D]  ← All records from both

CrossJoin (no DataItemLink):
  Parent: [A, B]       Child: [X, Y]
  Result: [A+X, A+Y, B+X, B+Y]  ← Every combination

DataItemLink Syntax

al
DataItemLink = "[ChildField]" = [ParentDataItemName]."[ParentField]";
  • Links child dataitem to parent using foreign key relationship
  • Multiple links separated by commas:
    al
    DataItemLink = "Document Type" = [parentItem]."Document Type",
                   "Document No." = [parentItem]."No.";

DataItemTableFilter

Apply fixed filters to restrict data at the dataitem level:

al
dataitem([name]; "[Table]")
{
    DataItemTableFilter = "Document Type" = FILTER(Invoice | "Credit Memo");
    DataItemTableFilter = "Posting Date" = FILTER(<> 0D);
}

Aggregation Methods

Use the Method property on columns for aggregation:

MethodDescription
SumTotal of numeric values
CountNumber of records
AverageAverage of numeric values
MinMinimum value
MaxMaximum value
al
column(totalAmount; "Amount (LCY)")
{
    Caption = 'TotalAmount', Locked = true;
    Method = Sum;
}

Rule: When using aggregation methods, non-aggregated columns become implicit GROUP BY fields.

Filter Elements

Expose filters as OData query parameters:

al
filter(dateFilter; "Posting Date")
{
    Caption = 'DateFilter', Locked = true;
}
  • Filters appear as query parameters in the OData URL
  • Use for date ranges, document type filtering, and status filtering
  • Filter elements do not produce output columns

Column Naming Conventions

AL FieldColumn AliasCaptionPattern
"Entry No."entryNo'Entry No.' or Locked = truecamelCase alias
"Customer No."customerNumber'CustomerNumber', LockedDescriptive names
"Posting Date"postingDate'PostingDate', LockedRemove spaces
"Amount (LCY)"amountLCY'AmountLCY', LockedInclude qualifier
"Sales (LCY)"totalSalesAmount'TotalSalesAmount', LockedDescriptive for aggregation
"Global Dimension 1 Code"globalDimension1CodeStandard dimension naming

Rules:

  • Use camelCase for all column aliases
  • Set Caption with Locked = true for API queries to prevent translation issues
  • Use descriptive aliases for aggregated columns (e.g., totalSalesAmount instead of salesLCY)

API Query Design Workflow

  1. Define purpose — What data needs exposure? Who consumes it? What aggregations?
  2. Identify tables — Primary table and related tables for joins
  3. Plan joins — Define DataItemLink relationships and SqlJoinType
  4. Select columns — Pick fields to expose, decide on aggregations
  5. Add filters — Expose date ranges and key filtering parameters
  6. Allocate object ID — Query objects typically in dedicated range
  7. Implement query — Create .Query.al file following naming convention
  8. Test endpoint — Verify OData response structure and data

File Naming Convention

Follow the pattern: [Prefix][EntityName]API.Query.al

Examples:

  • BCSStatLedgerEntryAPI.Query.al
  • BCSCustomerSalesAPI.Query.al
  • BCSItemInventoryAPI.Query.al

Place in feature folder: src/[Feature]/Query/ or alongside related feature files.

Checklist

Before completing API query generation:

  • QueryType = API set
  • API properties defined (publisher, group, version, entity names)
  • Caption set with Locked = true
  • All dataitems have meaningful names
  • DataItemLink defined for multi-table joins
  • SqlJoinType specified for each nested dataitem
  • DataItemTableFilter applied where needed
  • Column aliases use camelCase
  • Column Captions with Locked = true
  • Aggregation Methods applied where needed
  • Filter elements added for date ranges and key parameters
  • File follows naming convention: [Prefix][Entity]API.Query.al

References

For complete examples:

External Resources

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Bc Api Query Generator?

Generates API query objects for Business Central that expose data via OData/REST endpoints using the QueryType = API pattern. Creates queries with single or multiple dataitems (table joins), proper API properties, column mappings, aggregation methods (Sum, Count, Average, Min, Max), filters, DataItemLink joins (InnerJoin, LeftOuterJoin, CrossJoin), and DataItemTableFilter. Supports multi-version APIs, date filters, and dimension columns. Use when asked to create an API query, generate a query endpoint, build a read-only API from joined tables, expose aggregated data via API, create reportin...

Зачем использовать Bc Api Query Generator в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Bc Api Query Generator — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Bc Api Query Generator в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/fernandoartalf/AL-Copilot-Skills-Collection/tree/main/skills/bc-api-query-generator. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Bc Api Query Generator?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Bc Api Query Generator?

С любым количеством. В TypingMind вы можете использовать Bc Api Query Generator с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Bc Api Query Generator?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — fernandoartalf. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇