Logo vun Api Resource

Api Resource

Organisatioun
api-platform
api-resource

Creates or modifies API Platform resources with DTOs and Object Mapper. Use whenever the user wants to add an API endpoint, expose an entity or any data over HTTP, create or reshape a resource, define input/output DTOs, configure nested sub-resources with uriVariables, or map entities/documents to API representations — even if they just say 'add an endpoint for X' or 'expose X in the API'.

Iwwersiicht

Editeurapi-platform
Repositoryskillset
Skill-Nummapi-resource
Stären
29
Forks
1
Matgeliwwert Fichieren
Nëmmen Instruktiounen
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    Vum api-platform op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Api Resource an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/api-platform/skillset/tree/main/skills/api-resource
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

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/api-resource .claude/skills/api-resource
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Api Resource an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Api Resource automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Api Resource net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Creating API Platform Resources

Design-First Principle

An API Platform resource is built from three concerns (see https://api-platform.com/docs/core/design/):

  1. Resource declaration — a plain PHP object marked #[ApiResource] describing the public shape. Single source of truth for Hydra, OpenAPI and GraphQL.
  2. Data retrieval — a state provider hydrates that object (Get, GetCollection).
  3. Data persistence — a state processor writes it (Post, Put, Patch, Delete).

Design the public shape first; the resource class doesn't have to be a Doctrine entity. How you wire it to persistence is a separate decision:

ApproachWhenHookup
Entity as ResourcePrototyping, plain CRUD, internal model == public shape#[ApiResource] on the entity; built-in Doctrine provider/processor (zero wiring)
DTO with Object MapperDecoupled public shape over a Doctrine entity/document — whether fields match 1:1 or need renames/transformsstateOptions: new Options(entityClass:/documentClass:) and #[Map] on the DTO
Input DTOs per OperationWrite model differs from read model (stricter create/update payloads)per-operation input: + processor
Custom Provider/ProcessorNon-CRUD, external data, complex domain logic, CQRShand-written ProviderInterface/ProcessorInterface (see state-provider/state-processor)

Rule of thumb: entity-as-resource is convenient but couples your public contract to your schema — fine for prototypes, probably not for large or non-CRUD systems. Decouple with a DTO as soon as the two shapes diverge.

Entity as Resource (Simplest)

Mark the entity itself — built-in Doctrine providers/processors handle everything. No provider, processor, or mapping to write:

php
use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ApiResource]
class Book
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    public ?int $id = null;

    #[ORM\Column]
    public string $title = '';
}

Use this for prototypes and straight CRUD. Migrate to a DTO (strategies below) once the API shape must differ from the schema.

DTO with Object Mapper (Recommended)

One mechanism, not two: API Platform's ObjectMapperProvider / ObjectMapperProcessor activate only when both are present — stateOptions naming the entityClass: (or documentClass:) and a #[Map] attribute on the DTO (and on the input entity for writes). On read it runs map($entity, $resourceClass); on write map($inputDto, $entityClass) then persists via the Doctrine processor. There is no Object-Mapper mode without stateOptions.

Fields that line up by name map automatically; add #[Map(source: …)] to rename or transform: to convert. The same config covers both the trivial 1:1 case and arbitrary renames/transforms:

php
<?php
namespace App\ApiResource;

use ApiPlatform\Doctrine\Odm\State\Options;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use App\Document\Order as DocumentOrder;
use App\Transformer\CustomerTransformer;
use Symfony\Component\ObjectMapper\Attribute\Map;

#[ApiResource(
    operations: [
        new Get(stateOptions: new Options(documentClass: DocumentOrder::class)),
        new GetCollection(stateOptions: new Options(documentClass: DocumentOrder::class)),
    ]
)]
#[Map(target: DocumentOrder::class)]
final class Order
{
    public string $id;

    // Simple 1:1 field mapping (automatic when names match)
    public string $status;

    // Map from a different source field
    #[Map(source: 'customerName')]
    public string $buyer;

    // Transform with a custom callable
    #[Map(source: 'rawData', transform: new CustomerTransformer())]
    public CustomerDto $customer;
}

Custom Transformers

Implement TransformCallableInterface for complex mappings:

php
<?php
namespace App\Transformer;

use Symfony\Component\DependencyInjection\Attribute\Exclude;
use Symfony\Component\ObjectMapper\TransformCallableInterface;

#[Exclude]
final class CustomerTransformer implements TransformCallableInterface
{
    public function __construct(private readonly string $field = 'name') {}

    public function __invoke(mixed $value, object $source, ?object $target): mixed
    {
        // $value = source field value, $source = full source object
        $dto = new CustomerDto();
        $dto->name = $value[$this->field] ?? '';
        return $dto;
    }
}

Use #[Exclude] so Symfony's container doesn't try to autowire transformer constructor args.

Input DTOs per Operation

When the write model differs from the read model, give individual operations their own input: DTO and processor (the resource class stays the read model):

php
#[ApiResource(
    operations: [
        new Post(input: CreateOrderInput::class, processor: OrderCreateProcessor::class),
        new Patch(input: UpdateOrderInput::class, processor: OrderUpdateProcessor::class),
    ]
)]
class Order { /* read model */ }

Nested Sub-Resources with uriVariables

For resources nested under parents (e.g., /accounts/{accountId}/mailboxes/{mailboxId}/messages):

php
#[ApiResource(
    operations: [
        new Get(
            uriTemplate: '/accounts/{accountId}/mailboxes/{mailboxId}/messages/{id}',
            uriVariables: ['accountId', 'mailboxId', 'id'],
            stateOptions: new Options(
                handleLinks: MessageLinkHandler::class,
                documentClass: Message::class,
            )
        ),
        new GetCollection(
            uriTemplate: '/accounts/{accountId}/mailboxes/{mailboxId}/messages',
            uriVariables: ['accountId', 'mailboxId'],
            stateOptions: new Options(
                handleLinks: MessageLinkHandler::class,
                documentClass: Message::class,
            ),
            itemUriTemplate: '/accounts/{accountId}/mailboxes/{mailboxId}/messages/{id}',
        ),
    ]
)]

The handleLinks class validates parent ownership and applies security filters. See the securing-collections skill for implementation details.

Hidden IRI fields for URI generation:

php
#[ApiProperty(readable: false, writable: false)]
#[Map(source: 'account', transform: new DocumentIdTransformer())]
public string $accountId;

Custom Named Operations

Add non-CRUD actions on the same resource:

php
new Put(
    uriTemplate: '/orders/{id}/cancel',
    input: CancelOrderInput::class,
    processor: OrderCancelProcessor::class,
    name: '_api_order_cancel',
),
new Get(
    write: true, // triggers processor on GET
    uriTemplate: '/orders/{id}/download',
    processor: OrderDownloadProcessor::class,
    name: '_api_order_download',
),

Use write: true on Get operations that need a processor (e.g., file downloads): a Get's write phase is off by default, so the processor never fires until you flip the flag. See operations → Read & write phases for the read/write lifecycle.

Backed Enums

As a property

A backed enum property serializes to its ->value automatically:

php
#[ApiResource]
class Person
{
    public GenderType $genderType; // backed enum → {"genderType": "female"}
}

As a resource

Expose a backed enum as a read-only resource so clients can discover allowed values:

php
use ApiPlatform\Metadata\ApiResource;

#[ApiResource]
enum AvailabilityStatus: string
{
    case InStock = 'InStock';
    case OutOfStock = 'OutOfStock';
}

GET /availability_statuses lists all cases; GET /availability_statuses/InStock returns one.

High-Precision Numbers

For monetary/scientific values that must avoid float drift, type a property as \BcMath\Number (PHP 8.4 native, requires ext-bcmath). It serializes as a string to preserve precision:

php
class Invoice
{
    public ?\BcMath\Number $total; // → "300.55"
}

Laravel (Eloquent)

The design-first split, DTOs, Object Mapper, per-operation input:, nested uriVariables/handleLinks, custom operations and backed-enum resources all work on Laravel. Deltas:

  • Model as resource: #[ApiResource] on a class extending Illuminate\Database\Eloquent\Model; the Eloquent provider/processor handle CRUD with zero wiring.
  • Eloquent Options (ApiPlatform\Laravel\Eloquent\State\Options) uses modelClass: (not entityClass:/documentClass:); it carries modelClass + handleLinks only — no repositoryMethod.
  • Object Mapper is supported: pair stateOptions: new Options(modelClass: ProductModel::class) with #[Map(source: ProductModel::class)] on the DTO; per-property #[Map] and TransformCallableInterface are identical.
  • Properties: Eloquent models have no typed properties, so declare #[ApiProperty] at the class level with property: (#[ApiProperty(property: 'title', identifier: true)]). DTO/ApiResource classes use property-level attributes. \BcMath\Number and backed enums behave the same.

Checklist

When creating a new resource:

  • Create the DTO class in src/ApiResource/
  • Add #[ApiResource] with operations
  • Define provider for read operations (or use stateOptions)
  • Define processor for write operations
  • Add validation constraints to input DTOs
  • For nested resources: configure uriVariables and handleLinks
  • Add #[Map] attributes for entity/document mapping
  • Add #[ApiProperty] for OpenAPI documentation

Heefeg gestallte Froen

Wat mécht de KI-Skill Api Resource?

Creates or modifies API Platform resources with DTOs and Object Mapper. Use whenever the user wants to add an API endpoint, expose an entity or any data over HTTP, create or reshape a resource, define input/output DTOs, configure nested sub-resources with uriVariables, or map entities/documents to API representations — even if they just say 'add an endpoint for X' or 'expose X in the API'.

Firwat Api Resource op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Api Resource besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Api Resource an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/api-platform/skillset/tree/main/skills/api-resource an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Api Resource benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Api Resource benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Api Resource domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Api Resource gratis?

De Skill gëtt vum api-platform op GitHub publizéiert. Kuckt am Repository no de Lizenzbedéngungen. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇