Логотип Serialization Groups

Serialization Groups

Организация
api-platform
serialization-groups

Configures serialization with normalizationContext/denormalizationContext and #[Groups] in API Platform — per-operation contexts, #[Context] per-property overrides, and read/write group naming. Use when the user mentions serialization groups, #[Groups], normalizationContext, denormalizationContext, hiding/exposing fields per operation, write-only or read-only properties, controlling embedded relation depth, or 'why is this field showing up / missing' in the JSON output.

Обзор

Издательapi-platform
Репозиторийskillset
Название навыкаserialization-groups
Звёзды
29
Форки
1
Встроенные файлы
Только инструкции
Ссылки
  • Инструкции в формате Markdown

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

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

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

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

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

    Опубликовано на GitHub: api-platform. Перед установкой изучите исходные материалы.

Установка

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

1

Установка в TypingMind

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

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/api-platform/skillset/tree/main/skills/serialization-groups
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Новый навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

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

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

Claude Code — .claude/skills
git clone --depth 1 https://github.com/api-platform/skillset.git /tmp/skillset
mkdir -p .claude/skills
cp -r /tmp/skillset/skills/serialization-groups .claude/skills/serialization-groups
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

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

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

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

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

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

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

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

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

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

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

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

Serialization Groups

Prefer one resource class per representation over groups for new designs. Before reaching for groups, consider a DTO split: one class per output shape and per input shape, each with a flat, explicit set of properties (see api-resource). Reasons groups are a poor default:

  • The public shape becomes implicit and scattered. To know what GET /books returns you must mentally union every #[Groups] tag across the class hierarchy and cross-reference each operation's normalizationContext. A dedicated BookOutput DTO states the shape in one place.
  • They complicate the metadata. Per-operation contexts, per-property #[Context], and group inheritance interact in ways that are hard to predict and hard to test.
  • They block streaming serialization. API Platform's JsonStreamer path needs one static shape per class; a class whose output varies by group can't be streamed and falls back to the slower object normalizer.

Use groups when: you're working in an existing codebase already built on them (stay consistent), or a DTO split is genuinely overkill (one tiny read/write asymmetry on an internal resource). Otherwise, split the class.

The two contexts

normalizationContext governs reading (entity → JSON). denormalizationContext governs writing (JSON → entity). A property is only serialized/deserialized if one of its #[Groups] is listed in the active context.

php
use ApiPlatform\Metadata\ApiResource;
use Symfony\Component\Serializer\Attribute\Groups;

#[ApiResource(
    normalizationContext: ['groups' => ['book:read']],
    denormalizationContext: ['groups' => ['book:write']],
)]
class Book
{
    #[Groups(['book:read'])]                 // appears in output, ignored on input
    public ?int $id = null;

    #[Groups(['book:read', 'book:write'])]   // read and write
    public string $title = '';

    #[Groups(['book:write'])]                // write-only, e.g. a password
    public ?string $secret = null;
}

A property with no group in the active context is invisible: a field present on the entity but absent from the response is almost always a missing read group.

Naming convention

Use resource:operation-style group names — book:read, book:write, book:item:read. This keeps groups namespaced per resource so a read group on one class never accidentally pulls properties on another. Pairing a broad book:read with a narrower book:item:read lets item operations expose more than collections (see next section).

Per-operation contexts

Override the resource-level context on a single operation. Common pattern: a lean collection, a richer item view.

php
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;

#[ApiResource(normalizationContext: ['groups' => ['book:read']])]
#[GetCollection]                                                  // book:read only
#[Get(normalizationContext: ['groups' => ['book:read', 'book:item:read']])]
#[Patch(denormalizationContext: ['groups' => ['book:write']])]
class Book
{
    #[Groups(['book:read'])]
    public string $title = '';

    #[Groups(['book:item:read'])]            // only on the single-item GET
    public ?string $description = null;
}

Controlling embedded relations

A relation is embedded as a full object when the related class has a property in a group shared with the parent's context; otherwise it serializes as an IRI/string. This is how you choose embed-vs-reference:

php
#[ApiResource(normalizationContext: ['groups' => ['book:read']])]
class Book
{
    #[Groups(['book:read'])]
    public ?Author $author = null;          // embedded only if Author has a 'book:read' property
}

class Author
{
    #[Groups(['book:read'])]
    public string $name = '';               // this property pulls Author inline
}

Drop the book:read group from Author::$name and author collapses back to an IRI. This implicit coupling is exactly the kind of thing a DTO split makes explicit.

Per-property context override with #[Context]

#[Context] overrides serializer options for one property without a new group — useful for date formats or switching the normalization group on a single relation (embed the same related type at two depths):

php
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;

class Book
{
    #[Groups(['book:read'])]
    #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
    public ?\DateTimeInterface $publishedAt = null;

    #[Groups(['book:read'])]
    #[Context(['normalization' => ['groups' => ['author:summary']]])]
    public ?Author $author = null;          // serialized with author:summary, not book:read
}

The normalization/denormalization keys scope the override to one direction. See the parallel example in state-provider (Per-Property Serialization Context).

Interaction with other features

  • Validation groups are separate from serialization groups — don't reuse the same names expecting them to align. See operations for validationContext.
  • security expressions on properties (security: "is_granted(...)") gate fields independently of groups; both must pass.

Laravel (Eloquent)

API Platform uses the Symfony Serializer on Laravel too, so normalizationContext / denormalizationContext, the two-context model, per-operation contexts and embed-vs-IRI behaviour are identical. The one difference: Eloquent models have no typed properties, so #[Groups] can't be attached per property. Declare groups at the class level via #[ApiProperty(serialize: …, property: …)]:

php
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use Symfony\Component\Serializer\Attribute\Groups;

#[ApiResource(normalizationContext: ['groups' => ['book:read']])]
#[ApiProperty(serialize: new Groups(['book:read']), property: 'title')]
#[ApiProperty(serialize: new Groups(['book:read']), property: 'author')]
class Book extends Model {}

DTO/ApiResource classes (not extending Model) use property-level #[Groups] as shown above. The name_converter (default SnakeCaseToCamelCaseNameConverter) is set in config/api-platform.php.

Checklist

  • Considered a DTO-per-shape split before adding groups (see api-resource)
  • Group names namespaced per resource (book:read, not bare read)
  • Write-only secrets carry only the write group
  • Embedded-vs-IRI relations verified against actual JSON, not assumed
  • #[Context] used for one-off format/group tweaks instead of a whole new group

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

Что делает навык ИИ Serialization Groups?

Configures serialization with normalizationContext/denormalizationContext and #[Groups] in API Platform — per-operation contexts, #[Context] per-property overrides, and read/write group naming. Use when the user mentions serialization groups, #[Groups], normalizationContext, denormalizationContext, hiding/exposing fields per operation, write-only or read-only properties, controlling embedded relation depth, or 'why is this field showing up / missing' in the JSON output.

Зачем использовать Serialization Groups в TypingMind?

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

Как установить Serialization Groups в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/api-platform/skillset/tree/main/skills/serialization-groups. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Serialization Groups?

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

Со сколькими моделями ИИ можно использовать Serialization Groups?

С любым количеством. Если модель поддерживает навыки, вы можете использовать с ней Serialization Groups: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama и другие — всё в TypingMind с вашими собственными ключами API.

Бесплатен ли навык ИИ Serialization Groups?

Навык опубликован на GitHub автором api-platform. Условия лицензии можно найти в репозитории. Вы платите только своему поставщику ИИ за использованные токены.

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

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

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

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

Все

Создайте свою рабочую ИИ-среду сейчас

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