Logo Api Resource

Api Resource

Tổ chức
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'.

Tổng quan

Nhà phát hànhapi-platform
Kho mãskillset
Tên kỹ năngapi-resource
Sao
29
Bản fork
1
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được api-platform công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Api Resource trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/api-platform/skillset/tree/main/skills/api-resource
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

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
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Api Resource trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Api Resource ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Api Resource không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

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

Câu hỏi thường gặp

Kỹ năng AI Api Resource làm được gì?

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'.

Vì sao nên dùng Api Resource trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Api Resource là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Api Resource trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/api-platform/skillset/tree/main/skills/api-resource. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Api Resource?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Api Resource với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Api Resource với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Api Resource có miễn phí không?

Kỹ năng này được api-platform phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇