Getting started

Migrating from FOSRestBundle

If you plan to migrate from FOSRestBundle, you might want to read this guide to get started with API Platform.

FOSRestBundle からの移行を計画している場合は、このガイドを読んで API プラットフォームを使い始めることをお勧めします。

Installing API Platform

If you are starting a new project, the easiest way to get API Platform up is to install the API Platform Distribution. It comes with the API Platform core library integrated with the Symfony framework, the schema generator, Doctrine ORM, Elasticsearch-PHP, NelmioCorsBundle and Behat. Doctrine MongoDB ODM can also be enabled by following the MongoDB documentation. Basically, it is a Symfony edition packaged with the best tools to develop a REST API and sensible default settings.

新しいプロジェクトを開始する場合、API プラットフォームを起動する最も簡単な方法は、API プラットフォーム ディストリビューションをインストールすることです。Symfony フレームワークと統合された API プラットフォーム コア ライブラリ、スキーマ ジェネレーター、Doctrine ORM、Elasticsearch-PHP、NelmioCorsBundle が付属しています。および Behat.Doctrine MongoDB ODM は、MongoDB のドキュメントに従って有効にすることもできます。基本的には、REST API と適切なデフォルト設定を開発するための最適なツールがパッケージ化された Symfony エディションです。

Alternatively, you can use Composer to install the standalone bundle in an existing Symfony Flex project:

または、Composer を使用して、スタンドアロン バンドルを既存の Symfony Flexproject にインストールすることもできます。

composer require api

作曲家はAPIが必要です

There are no mandatory configuration options although many settings are available.

多くの設定が利用可能ですが、必須の構成オプションはありません。

Warning: If you are migrating from an older version of API Platform than 2.7, make sure you read the Upgrade Guide.

警告: 2.7 より古いバージョンの API プラットフォームから移行する場合は、必ずアップグレード ガイドをお読みください。

Before Reading this Documentation

If you haven't read it already, take a look at the Getting Started guide. This tutorial covers basic concepts required to understand how API Platform works including how it implements the REST pattern and what JSON-LD and Hydra formats are.

まだ読んでいない場合は、入門ガイドをご覧ください。このチュートリアルでは、REST パターンの実装方法や、JSON-LD および Hydra 形式とは何かなど、API プラットフォームの仕組みを理解するために必要な基本的な概念について説明します。

Mapping the Entities

Create an API Resource screencast
Watch the Create an API Resource screencast

API リソースの作成のスクリーンキャストを見る

API Platform is able to automatically expose entities mapped as "API resources" through a REST API supporting CRUD operations. To expose your entities, you can use Docblock annotations, XML and YAML configuration files.

API プラットフォームは、CRUD 操作をサポートする REST API を介して「API リソース」としてマップされたエンティティを自動的に公開できます。エンティティを公開するには、Docblock 注釈、XML および YAML 構成ファイルを使用できます。

Here is an example of entities mapped using annotations which will be exposed through a REST API:

以下は、REST API を介して公開されるアノテーションを使用してマップされたエンティティの例です。

<?php
// api/src/Entity/Product.php
namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity]
#[ApiResource]
class Product // The class name will be used to name exposed resources
{
    #[ORM\Id, ORM\Column, ORM\GeneratedValue]
    private ?int $id = null;

    /**
     * A name property - this description will be available in the API documentation too.
     *
     */
    #[ORM\Column] 
    #[Assert\NotBlank]
    public string $name = '';

    // Notice the "cascade" option below, this is mandatory if you want Doctrine to automatically persist the related entity
    /**
     * @var Offer[]|ArrayCollection
     *
     */
    #[ORM\OneToMany(targetEntity: Offer::class, mappedBy: 'product', cascade: ['persist'])] 
    public iterable $offers;

    public function __construct()
    {
        $this->offers = new ArrayCollection(); // Initialize $offers as a Doctrine collection
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    // Adding both an adder and a remover as well as updating the reverse relation is mandatory
    // if you want Doctrine to automatically update and persist (thanks to the "cascade" option) the related entity
    public function addOffer(Offer $offer): void
    {
        $offer->product = $this;
        $this->offers->add($offer);
    }

    public function removeOffer(Offer $offer): void
    {
        $offer->product = null;
        $this->offers->removeElement($offer);
    }

    // ...
}
<?php
// api/src/Entity/Offer.php
namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * An offer from my shop - this description will be automatically extracted from the PHPDoc to document the API.
 *
 */
#[ORM\Entity]
#[ApiResource(types: ['https://schema.org/Offer'])]
class Offer
{
    #[ORM\Id, ORM\Column, ORM\GeneratedValue]
    private ?int $id = null;

    #[ORM\Column(type: 'text')]
    public string $description = '';

    #[ORM\Column]
    #[Assert\Range(minMessage: 'The price must be superior to 0.', min: 0)]
    public float $price = -1.0;

    #[ORM\ManyToOne(targetEntity: Product::class, inversedBy: 'offers')]
    public ?Product $product = null;

    public function getId(): ?int
    {
        return $this->id;
    }
}

It is the minimal configuration required to expose Product and Offer entities as JSON-LD documents through an hypermedia web API.

これは、hypermediaweb API を介して JSON-LD ドキュメントとして Product および Offer エンティティを公開するために必要な最小限の構成です。

If you are familiar with the Symfony ecosystem, you noticed that entity classes are also mapped with Doctrine ORM annotations and validation constraints from the Symfony Validator Component. This isn't mandatory. You can use your preferred persistence and validation systems. However, API Platform has built-in support for those libraries and is able to use them without requiring any specific code or configuration to automatically persist and validate your data. They are a good default option and we encourage you to use them unless you know what you are doing.

Symfony エコシステムに精通している場合は、エンティティークラスが Doctrine ORM アノテーションと Symfony バリデーターコンポーネントからの検証制約にもマッピングされていることに気付いたでしょう。これは必須ではありません。好みの永続化システムと検証システムを使用できます。ただし、API プラットフォームにはこれらのライブラリのサポートが組み込まれており、データを自動的に永続化して検証するための特定のコードや構成を必要とせずに使用できます。これらは適切なデフォルト オプションであり、何をしているのかわからない場合は使用することをお勧めします。

Thanks to the mapping done previously, API Platform will automatically register the following REST operations for resources of the product type:

以前に行ったマッピングのおかげで、API プラットフォームは製品タイプのリソースに対して次の REST 操作を自動的に登録します。

Product

Method URL Description
GET /products Retrieve the (paginated) collection
POST /products Create a new product
GET /products/{id} Retrieve a product
PUT /products/{id} Update a product
PATCH /products/{id} Apply a partial modification to a product
DELETE /products/{id} Delete a product

The same operations are available for the offer method (routes will start with the /offers pattern). Route prefixes are built by pluralizing the name of the mapped entity class. It is also possible to override the naming convention using operation path namings.

offer メソッドでも同じ操作を使用できます (ルートは /offers パターンで始まります)。ルート プレフィックスは、マップされたエンティティ クラスの名前を複数形にすることで作成されます。操作パスの命名を使用して命名規則をオーバーライドすることもできます。

As an alternative to annotations, you can map entity classes using YAML or XML:

アノテーションの代わりに、YAML または XML を使用してエンティティ クラスをマップできます。

[codeSelector]

[コードセレクター]

# api/config/api_platform/resources.yaml
resources:
    App\Entity\Product: ~
    App\Entity\Offer:
        shortName: 'Offer'                   # optional
        description: 'An offer from my shop' # optional
        types: ['https://schema.org/Offer']   # optional
        paginationItemsPerPage: 25           # optional
<?xml version="1.0" encoding="UTF-8" ?>
<!-- api/config/api_platform/resources.xml -->

<resources xmlns="https://api-platform.com/schema/metadata/resources-3.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="https://api-platform.com/schema/metadata/resources-3.0
        https://api-platform.com/schema/metadata/resources-3.0.xsd">
    <resource class="App\Entity\Product" />
    <resource
        class="App\Entity\Offer"
        shortName="Offer" <!-- optional -->
        description="An offer from my shop" <!-- optional -->
    >
        <types>
            <type>https://schema.org/Offer</type> <!-- optional -->
        </types>
    </resource>
</resources>

[/codeSelector]

[/コードセレクター]

If you prefer to use YAML or XML files instead of annotations, you must configure API Platform to load the appropriate files:

アノテーションの代わりに YAML または XML ファイルを使用する場合は、適切なファイルをロードするように API プラットフォームを構成する必要があります。

# api/config/packages/api_platform.yaml
api_platform:
    mapping:
        paths: 
            - '%kernel.project_dir%/src/Entity' # default configuration for annotations
            - '%kernel.project_dir%/config/api_platform' # yaml or xml directory configuration

If you want to serialize only a subset of your data, please refer to the Serialization documentation.

データのサブセットのみをシリアル化する場合は、シリアル化のドキュメントを参照してください。

You're done!

あなたは終わった!

You now have a fully featured API exposing your entities. Run the Symfony app with the Symfony Local Web Server (symfony server:start) and browse the API entrypoint at http://localhost:8000/api.

これで、エンティティを公開するフル機能の API ができました。Symfony ローカル Web サーバー (symfony server:start) で Symfony アプリを実行し、http://localhost:8000/api で API エントリポイントを参照します。

Interact with the API using a REST client (we recommend Postman) or an Hydra-aware application (you should give Hydra Console a try). Take a look at the usage examples in the features directory.

REST クライアント (Postman をお勧めします) または Hydra 対応アプリケーション (Hydra Console を試してみてください) を使用して API と対話します。 features ディレクトリにある使用例を見てみましょう。