Логотип 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, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

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

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем api-platform. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Serialization Groups у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/api-platform/skillset/tree/main/skills/serialization-groups
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
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, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇