Getting Started With API Platform: Create Your API and Your Jamstack Site

The welcome page

API Platform is the most advanced API platform, in any framework or language.

API プラットフォームは、フレームワークや言語を問わず、最も高度な API プラットフォームです。

—Fabien Potencier (creator of Symfony)

—Fabien Potencier (Symfony の作成者)

API Platform is a powerful yet easy to use full stack framework dedicated to API-driven projects and implementing the Jamstack architecture.

API Platform は、強力でありながら使いやすいフルスタック フレームワークであり、API 駆動型プロジェクト専用で、Jamstack アーキテクチャを実装しています。

Introduction

API Platform contains a PHP library (Core) to create fully featured hypermedia (or GraphQL) web APIs supporting industry-leading standards: JSON-LD with Hydra, OpenAPI...

API プラットフォームには、業界をリードする標準をサポートするフル機能のハイパーメディア (または GraphQL) Web API を作成するための PHP ライブラリ (コア) が含まれています: Hydra を使用した JSON-LD、OpenAPI...

API Platform also provides ambitious JavaScript tools to create web and mobile applications based on the most popular frontend technologies in a snap. These tools parse the documentation of the API (or of any other API supporting Hydra or OpenAPI).

API Platform は、最も一般的なフロントエンド テクノロジーに基づいて Web およびモバイル アプリケーションを簡単に作成するための野心的な JavaScript ツールも提供します。これらのツールは、API (または Hydra または OpenAPI をサポートする他の A​​PI) のドキュメントを解析します。

API Platform is shipped with Docker and Kubernetes definitions, to develop and deploy instantly on the cloud.

API プラットフォームには Docker と Kubernetes の定義が同梱されており、クラウド上で即座に開発およびデプロイできます。

The easiest and most powerful way to get started is to download the API Platform distribution. It contains:

開始するための最も簡単で強力な方法は、API プラットフォーム ディストリビューションをダウンロードすることです。を含む:

  • the API skeleton, including the Core library, the Symfony framework (optional) and the Doctrine ORM (optional)
    Core ライブラリ、Symfony フレームワーク (オプション)、および Doctrine ORM (オプション) を含む API スケルトン
  • the client scaffolding tool to generate Next.js web applications from the API documentation (Nuxt.js, Vue, Create React App, React Native, Quasar and Vuetify are also supported)
    API ドキュメントから Next.js Web アプリケーションを生成するためのクライアント スキャフォールディング ツール (Nuxt.js、Vue、Create React App、React Native、Quasar、Vuetify もサポートされています)
  • a beautiful admin interface, built on top of React Admin, dynamically created by parsing the API documentation
    React Admin の上に構築され、API ドキュメントを解析することによって動的に作成される美しい管理インターフェース
  • all you need to create real-time and async APIs using the Mercure protocol
    Mercure プロトコルを使用してリアルタイムおよび非同期 API を作成するために必要なすべて
  • a Docker definition to start a working development environment in a single command, providing containers for the API and the Next.js web application
    API と Next.js Web アプリケーション用のコンテナーを提供する、単一のコマンドで作業中の開発環境を開始する Docker 定義
  • a Helm chart to deploy the API in any Kubernetes cluster
    任意の Kubernetes クラスターに API をデプロイするための Helm チャート

A Bookshop API

To discover how the framework works, we will create an API to manage a bookshop.

フレームワークがどのように機能するかを知るために、本屋を管理するための API を作成します。

To create a fully featured API, an admin interface and a Progressive Web App using Next.js, all you need is to design the public data model of our API and handcraft it as Plain Old PHP Objects.

Next.js を使用してフル機能の API、管理インターフェイス、およびプログレッシブ Web アプリを作成するには、API のパブリック データモデルを設計し、それをプレーン オールド PHP オブジェクトとして手作りするだけです。

API Platform uses these model classes to expose and document a web API having a bunch of built-in features:

API プラットフォームは、これらのモデル クラスを使用して、一連の組み込み機能を持つ Web API を公開および文書化します。

  • creating, retrieving, updating and deleting (CRUD) resources
    リソースの作成、取得、更新、および削除 (CRUD)
  • data validation
    データ検証
  • pagination
    ページネーション
  • filtering
    フィルタリング
  • sorting
    並べ替え
  • hypermedia/HATEOAS and content negotiation support (JSON-LD and Hydra, JSON:API, HAL...)
    ハイパーメディア/HATEOAS とコンテンツ ネゴシエーションのサポート (JSON-LD と Hydra、JSON:API、HAL...)
  • GraphQL support
    GraphQL のサポート
  • Nice UI and machine-readable documentations (Swagger UI/OpenAPI, GraphiQL...)
    優れた UI と機械可読ドキュメント (Swagger UI/OpenAPI、GraphiQL...)
  • authentication (Basic HTTP, cookies as well as JWT and OAuth through extensions)
    認証 (基本的な HTTP、Cookie、および拡張機能による JWT と OAuth)
  • CORS headers
    CORS ヘッダー
  • security checks and headers (tested against OWASP recommendations)
    セキュリティ チェックとヘッダー (OWASP 推奨事項に対してテスト済み)
  • invalidation-based HTTP caching
    無効化ベースの HTTP キャッシング
  • and basically everything needed to build modern APIs.
    基本的に、最新の API を構築するために必要なすべてが含まれています。

One more thing, before we start: as the API Platform distribution includes the Symfony framework, it is compatible with most Symfony bundles (plugins) and benefits from the numerous extensions points provided by this rock-solid foundation (events, Dependency Injection Container...). Adding features like custom or service-oriented API endpoints, JWT or OAuth authentication, HTTP caching, mail sending or asynchronous jobs to your APIs is straightforward.

始める前にもう 1 つ: API プラットフォーム ディストリビューションには Symfony フレームワークが含まれているため、ほとんどの Symfony バンドル (プラグイン) と互換性があり、この強固な基盤 (イベント、依存性注入コンテナー..カスタムまたはサービス指向の API エンドポイント、JWT または OAuth 認証、HTTP キャッシング、メール送信または非同期ジョブなどの機能を API に追加するのは簡単です。

Installing the Framework

Start by downloading the API Platform distribution, or generate a GitHub repository from the template we provide. You will add your own code and configuration inside this skeleton.

API プラットフォーム ディストリビューションをダウンロードすることから始めるか、提供されているテンプレートから GitHub リポジトリを生成します。このスケルトン内に独自のコードと構成を追加します。

Note: Avoid downloading the .zip archive, as it may cause potential permission issues, prefer the .tar.gz archive.

注: 許可の問題が発生する可能性があるため、.zip アーカイブのダウンロードは避け、.tar.gz アーカイブを優先してください。

API Platform is shipped with a Docker definition that makes it easy to get a containerized development environment up and running. If you do not already have Docker on your computer, it's the right time to install it.

API プラットフォームには、コンテナー化された開発環境を簡単に起動して実行できるようにする Docker 定義が付属しています。コンピューターに Docker がまだインストールされていない場合は、インストールするのに適した時期です。

Note: On Mac, only Docker for Mac is supported. Similarly, on Windows, only Docker for Windows is supported. Docker Machine is not supported out of the box.

注: Mac では、Docker for Mac のみがサポートされます。同様に、Windows では、Docker for Windows のみがサポートされます。 Docker Machine はそのままではサポートされていません。

Open a terminal, and navigate to the directory containing your project skeleton. Run the following command to start all services using Docker Compose:

ターミナルを開き、プロジェクトのスケルトンを含むディレクトリに移動します。次のコマンドを実行して、Docker Compose を使用してすべてのサービスを開始します。

Download and build the latest versions of the images:

イメージの最新バージョンをダウンロードしてビルドします。

docker compose build --pull --no-cache

Start Docker Compose in detached mode:

デタッチ モードで Docker Compose を起動します。

docker compose up -d 

Tip: be sure that the ports 80, 443 and 5432 of the host are not already in use. The usual offenders are Apache, NGINX and Postgres. If they are running, stop them and run docker compose up -d again.

ヒント: ホストのポート 80、443、および 5432 がまだ使用されていないことを確認してください。通常の攻撃者は、Apache、NGINX、および Postgres です。実行中の場合は、停止して docker compose up -d を再度実行します。

This starts the following services:

これにより、次のサービスが開始されます。

Name Description
caddy Caddy web server with the Mercure (real-time and async) and Vulcain (relations preloading) modules
php The API with PHP 8, Composer and sensitive configs
pwa Next.js project compatible with Create Client and having Admin preinstalled
database PostgreSQL database server

The following components are available:

次のコンポーネントが利用可能です。

URL Path Language Description
https://localhost/docs/ api/ PHP The API
https://localhost/ pwa/ JavaScript The Next.js application
https://localhost/admin/ pwa/pages/admin/ JavaScript The Admin

To see the container's logs, run:

コンテナーのログを表示するには、次を実行します。

docker compose logs -f

The -f option is to follow the logs.

-f オプションは、ログを追跡することです。

Project files are automatically shared between your local host machine and the container thanks to a pre-configured Docker volume. It means that you can edit files of your project locally using your preferred IDE or code editor, they will be transparently taken into account in the container. Speaking about IDEs, our favorite software to develop API Platform apps is PhpStorm with its awesome Symfony and Php Inspections plugins. Give them a try, you'll get auto-completion for almost everything and awesome quality analysis.

プロジェクト ファイルは、事前構成された Dockervolume のおかげで、ローカル ホスト マシンとコンテナーの間で自動的に共有されます。これは、お好みの IDE またはコード エディターを使用して、プロジェクトのファイルをローカルで編集できることを意味します。これらのファイルは、コンテナーで透過的に考慮されます。それらを試してみると、ほとんどすべてのオートコンプリートと素晴らしい品質分析が得られます。

PHP IntelliSense for Visual Studio Code also works well, and is free and open source.

Visual Studio Code 用の PHP IntelliSense も適切に機能し、無料のオープン ソースです。

The API Platform distribution comes with a dummy entity for test purpose: api/src/Entity/Greeting.php. We will remove it later.

API プラットフォーム ディストリビューションには、テスト用のダミー エンティティ api/src/Entity/Greeting.php が付属しています。後で削除します。

If you're used to the PHP ecosystem, you probably guessed that this test entity uses the industry-leading Doctrine ORM library as persistence system. It is shipped, in the API Platform distribution.

PHP エコシステムに慣れている場合は、このテスト エンティティが業界をリードする Doctrine ORMlibrary を永続化システムとして使用していることをおそらく推測したでしょう。 API プラットフォーム ディストリビューションで出荷されます。

Doctrine ORM is the easiest way to persist and query data in an API Platform project thanks to the bridge shipped with the distribution, but it's also entirely optional, and you may prefer to plug your own persistence system.

Doctrine ORM は、ディストリビューションに同梱されているブリッジのおかげで、API プラットフォーム プロジェクトでデータを永続化およびクエリする最も簡単な方法ですが、完全にオプションでもあり、独自の永続化システムをプラグインすることを好む場合もあります。

The Doctrine Bridge is optimized for performance and development convenience. For instance, when using Doctrine, API Platform is able to automatically optimize the generated SQL queries by adding the appropriate JOIN clauses. It also provides a lot of powerful built-in filters. Doctrine ORM and its bridge support most popular RDBMS including PostgreSQL, MySQL, MariaDB, SQL Server, Oracle and SQLite. There is also a shipped Doctrine MongoDB ODM optional support.

Doctrine Bridge は、パフォーマンスと開発の利便性のために最適化されています。たとえば、Doctrine を使用する場合、API Platform は、適切な JOIN 句を追加することで、生成された SQL クエリを自動的に最適化できます。また、多くの強力な組み込みフィルターも提供します。Doctrine ORM とそのブリッジは、PostgreSQL、MySQL、MariaDB、SQL Server、Oracle、SQLite を含む最も一般的な RDBMS をサポートします。同梱の Doctrine MongoDB ODM オプションのサポートもあります。

That being said, keep in mind that API Platform is 100% independent of the persistence system. You can use the one(s) that best suit(s) your needs (including NoSQL databases or remote web services) by implementing the right interfaces. API Platform even supports using several persistence systems together in the same project.

そうは言っても、API プラットフォームは永続化システムから 100% 独立していることに注意してください。適切なインターフェースを実装することで、ニーズに最も適したもの (NoSQL データベースやリモート Web サービスを含む) を使用できます。 API プラットフォームは、同じプロジェクトで複数の永続化システムを一緒に使用することもサポートしています。

Using Symfony CLI

Alternatively, the API Platform server component can also be installed directly on a local machine. This method is recommended only for users who want full control over the directory structure and the installed dependencies.

または、API プラットフォーム サーバー コンポーネントをローカル マシンに直接インストールすることもできます。この方法は、ディレクトリ構造とインストールされた依存関係を完全に制御したいユーザーにのみ推奨されます。

For a good introduction, watch how to install API Platform without the distribution on SymfonyCasts.

良い導入として、SymfonyCast にディストリビューションなしで API プラットフォームをインストールする方法をご覧ください。

The rest of this tutorial assumes that you have installed API Platform using the official distribution. Go straight to the next section if it's your case.

このチュートリアルの残りの部分では、公式ディストリビューションを使用して API プラットフォームをインストールしていることを前提としています。あなたの場合は、次のセクションに直行してください。

API Platform has an official Symfony Flex recipe. It means that you can easily install it from any Symfony application using the Symfony binary:

API Platform には公式の Symfony Flex レシピがあります。これは、Symfony バイナリを使用して、任意の Symfony アプリケーションから簡単にインストールできることを意味します。

Create a new Symfony project:

新しい Symfony プロジェクトを作成します。

symfony new bookshop-api

Enter the project directory:

プロジェクト ディレクトリを入力します。

cd bookshop-api

Install the API Platform's server component in this skeleton:

このスケルトンに API プラットフォームのサーバー コンポーネントをインストールします。

symfony composer require api

Then, create the database and its schema:

次に、データベースとそのスキーマを作成します。

symfony console doctrine:database:create
symfony console doctrine:schema:create

And start the built-in PHP server:

組み込みの PHP サーバーを起動します。

symfony serve

All JavaScript components are also available as standalone libraries installable with npm (or any other package manager).

すべての JavaScript コンポーネントは、npm (またはその他のパッケージ マネージャー) でインストール可能なスタンドアロン ライブラリとしても利用できます。

Note: when installing API Platform this way, the API will be exposed as the /api/ path. You need to open http://localhost:8000/api/ to see the API documentation. If you are deploying API Platform directly on an Apache or NGINX webserver and getting a 404 error on opening this link, you will need to enable the rewriting rules for your specific webserver software.

注: この方法で API プラットフォームをインストールすると、API は /api/ パスとして公開されます。 API ドキュメントを表示するには、http://localhost:8000/api/ を開く必要があります。API プラットフォームを Apache または NGINX Web サーバーに直接デプロイし、このリンクを開くと 404 エラーが発生する場合は、書き換えを有効にする必要があります。特定の Web サーバー ソフトウェアのルール。

It's Ready

Open https://localhost in your favorite web browser:

お好みの Web ブラウザーで https://localhost を開きます。

The welcome page

You'll need to add a security exception in your browser to accept the self-signed TLS certificate that has been generated for this container when installing the framework.

フレームワークのインストール時に、このコンテナー用に生成された自己署名 TLS 証明書を受け入れるには、ブラウザーにセキュリティ例外を追加する必要があります。

Later you will probably replace this welcome screen by the homepage of your Next.js application. If you don't plan to create a Progressive Web App, you can remove the pwa/ directory as well as the related lines in docker-compose*.yml and in api/docker/caddy/Caddyfile (don't do it now, we'll use this container later in this tutorial).

後で、このウェルカム画面を Next.js アプリケーションのホームページに置き換えることになるでしょう。プログレッシブ Web アプリを作成する予定がない場合は、pwa/ ディレクトリと、docker-compose*.yml および api/docker/caddy/Caddyfile の関連行を削除できます (今は実行しないでください。このコンテナは、このチュートリアルの後半で使用します)。

Click on the "API" button, or go to https://localhost/docs/:

[API] ボタンをクリックするか、https://localhost/docs/ にアクセスします。

The API

API Platform exposes a description of the API in the OpenAPI format (formerly known as Swagger). It also integrates a customized version of Swagger UI, a nice interface rendering the OpenAPI documentation. Click on an operation to display its details. You can also send requests to the API directly from the UI. Try to create a new Greeting resource using the POST operation, then access it using the GET operation and, finally, delete it by executing the DELETE operation. If you access any API URL with the .html extension appended, API Platform displays the corresponding API request in the UI. Try it yourself by browsing to https://localhost/greetings.html. If no extension is present, API Platform will use the Accept header to select the format to use. By default, a JSON-LD response is sent (configurable behavior).

API プラットフォームは、API の説明を OpenAPI 形式 (以前は Swagger と呼ばれていました) で公開します。また、カスタマイズされたバージョンの Swagger UI を統合します。これは、OpenAPI ドキュメントをレンダリングする優れたインターフェイスです。操作をクリックすると、その詳細が表示されます。また、UI から直接 API にリクエストを送信することもできます。POST オペレーションを使用して新しい Greeting リソースを作成し、GET オペレーションを使用してアクセスし、最後に DELETE オペレーションを実行して削除します。API URL にアクセスする場合.html 拡張子を追加すると、API プラットフォームは対応する API リクエストを UI に表示します。 https://localhost/greetings.html にアクセスして、自分で試してみてください。拡張子が存在しない場合、API プラットフォームは Accept ヘッダーを使用して、使用する形式を選択します。デフォルトでは、JSON-LD 応答が送信されます (構成可能な動作)。

So, if you want to access the raw data, you have two alternatives:

したがって、生データにアクセスする場合は、次の 2 つの方法があります。

  • Add the correct Accept header (or don't set any Accept header at all if you don't care about security) - preferred when writing API clients
    正しい Accept ヘッダーを追加します (または、セキュリティを気にしない場合は、Accept ヘッダーをまったく設定しないでください) - API クライアントを作成する場合に推奨されます
  • Add the format you want as the extension of the resource - for debug purpose only
    リソースの拡張子として必要な形式を追加します - デバッグ目的のみ

For instance, go to https://localhost/greetings.jsonld to retrieve the list of Greeting resources in JSON-LD, or to https://localhost/greetings.json to retrieve data in raw JSON.

たとえば、https://localhost/greetings.jsonld に移動して JSON-LD の Greeting リソースのリストを取得するか、https://localhost/greetings.json に移動して生の JSON でデータを取得します。

Of course, you can also use your favorite HTTP client to query the API. We are fond of Postman. It works perfectly well with API Platform, has native OpenAPI support, allows to easily write functional tests and has good team collaboration features.

もちろん、お気に入りの HTTP クライアントを使用して API をクエリすることもできます。私たちは Postman を愛用しています。 API プラットフォームと完全に連携し、OpenAPI をネイティブにサポートし、機能テストを簡単に記述でき、優れたチーム コラボレーション機能を備えています。

Bringing your Own Model

Your API Platform project is now 100% functional. Let's expose our own data model. Our bookshop API will start simple. It will be composed of a Book resource type and a Review one.

API プラットフォーム プロジェクトが 100% 機能するようになりました。独自のデータ モデルを公開してみましょう。bookshop API は単純なものから始めます。これは Book リソース タイプと Review リソース タイプで構成されます。

Books have an ID, an ISBN, a title, a description, an author, a publication date and are related to a list of reviews. Reviews have an ID, a rating (between 0 and 5), a body, an author, a publication date and are related to one book.

書籍には、ID、ISBN、タイトル、説明、著者、発行日があり、レビューのリストに関連付けられています。レビューには、ID、評価 (0 ~ 5)、本文、著者、発行日と1冊の本に関連しています。

Let's describe this data model as a set of Plain Old PHP Objects (POPO):

このデータ モデルを Plain Old PHP Objects (POPO) のセットとして説明しましょう。

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

use ApiPlatform\Metadata\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;

/** A book. */
#[ApiResource]
class Book
{
    /** The ID of this book. */
    private ?int $id = null;

    /** The ISBN of this book (or null if doesn't have one). */
    public ?string $isbn = null;

    /** The title of this book. */
    public string $title = '';

    /** The description of this book. */
    public string $description = '';

    /** The author of this book. */
    public string $author = '';

    /** The publication date of this book. */
    public ?\DateTimeImmutable $publicationDate = null;

    /** @var Review[] Available reviews for this book. */
    public iterable $reviews;

    public function __construct()
    {
        $this->reviews = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }
}
<?php
// api/src/Entity/Review.php
namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;

/** A review of a book. */
#[ApiResource]
class Review
{
    /** The ID of this review. */
    private ?int $id = null;

    /** The rating of this review (between 0 and 5). */
    public int $rating = 0;

    /** The body of the review. */
    public string $body = '';

    /** The author of the review. */
    public string $author = '';

    /** The date of publication of this review.*/
    public ?\DateTimeImmutable $publicationDate = null;

    /** The book this review is about. */
    public ?Book $book = null;

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

We created two typical PHP objects with the corresponding PHPDoc, both marked with the #[ApiResource] attribute. For convenience, we also used the Doctrine Collection library (that is independent from Doctrine ORM), but it's not mandatory.

対応する PHPDoc を持つ 2 つの典型的な PHP オブジェクトを作成し、両方とも #[ApiResource] 属性でマークしました。便宜上、Doctrine コレクション ライブラリ (Doctrine ORM から独立したもの) も使用しましたが、必須ではありません。

Reload https://localhost/docs/: API Platform used these classes to generate an OpenAPI documentation (a Hydra documentation is also exposed), and registered for us the typical REST routes.

リロード https://localhost/docs/: API プラットフォームはこれらのクラスを使用して OpenAPI ドキュメントを生成し (Hydra ドキュメントも公開されています)、典型的な REST ルートを登録しました。

The bookshop API

Operations available for our 2 resource types appear in the UI. We can also see the awesome Web Debug Toolbar.

2 つのリソース タイプで使用できる操作が UI に表示されます。また、すばらしい Web デバッグ ツールバーも表示されます。

Note that entities' and properties' descriptions in the API documentation, and that API Platform use PHP types to generate the appropriate JSON Schemas.

API ドキュメントのエンティティとプロパティの説明、および API プラットフォームは PHP 型を使用して適切な JSON スキーマを生成することに注意してください。

Bookshop JSON Schemas

The framework also use these metadata to serialize and deserialize data from JSON (and other formats) to PHP objects (back and forth)!

また、フレームワークはこれらのメタデータを使用して、JSON (およびその他の形式) から PHP オブジェクトに (前後に) データをシリアライズおよびデシリアライズします!

For the sake of simplicity, in this example we used public properties (except for the ID, see below). API Platform (as well as Symfony and Doctrine) also supports accessor methods (getters/setters), use them if you want to. We used a private property and a getter for the ID to enforce the fact that it is read only (we will let the DBMS generating it). API Platform also has first-grade support for UUIDs. You should probably use them instead of auto-incremented IDs.

簡単にするために、この例ではパブリック プロパティを使用しました (ID を除く。以下を参照)。 API プラットフォーム (および Symfony と Doctrine) は、アクセサー メソッド (ゲッター/セッター) もサポートしています。必要に応じて使用してください。プライベート プロパティと ID のゲッターを使用して、ID が読み取り専用であることを強制しました (それを生成する DBMS)。 API プラットフォームには、UUID の第 1 級のサポートもあります。おそらく、自動インクリメント ID の代わりにそれらを使用する必要があります。

Because API Platform provides all the infrastructure for us, our API is almost ready!

API プラットフォームがすべてのインフラストラクチャを提供してくれるので、API の準備はほぼ完了しています。

The only remaining task to have a working API is to be able to query and persist data.

API を機能させるために残っている唯一のタスクは、データのクエリと永続化を行うことです。

Plugging the Persistence System

To retrieve and save data, API Platform proposes two main options (and we can mix them):

データを取得して保存するために、API プラットフォームは 2 つの主なオプションを提案します (これらを混在させることもできます)。

  1. Writing our own data providers and data persisters to fetch and save data in any persistence system and trigger our custom business logic. This is what we recommend if you want to separate the public data model exposed by the API from the internal one, and to implement a layered architecture such as Clean Architecture or Hexagonal Architecture;
    任意の永続化システムでデータを取得して保存し、カスタム ビジネス ロジックをトリガーするための独自のデータ プロバイダーとデータ永続化機能を記述します。これは、API によって公開されるパブリック データ モデルを内部モデルから分離し、Clean Architecture や Hexagonal Architecture などのレイヤード アーキテクチャを実装する場合に推奨するものです。
  2. Using one of the various existing data providers and persisters allowing to automatically fetch and persist data using popular persistence libraries. Out of the box, data providers and persisters are provided for Doctrine ORM and Doctrine MongoDB ODM. A data provider (but no persister yet) is also available for Elasticsearch. Pomm and PHP Extended SQL also provides data providers and persisters for API Platform. We recommend this approach for Rapid Application Development.
    さまざまな既存のデータ プロバイダーと永続化機能のいずれかを使用して、一般的な永続化ライブラリを使用してデータを自動的に取得および永続化できます。 Doctrine ORM と Doctrine MongoDB ODM には、すぐに使用できるデータ プロバイダーと永続化プログラムが用意されています。Elasticsearch では、データ プロバイダー (まだ永続化要素はありません) も利用できます。 Pomm と PHP 拡張 SQL は、API プラットフォームのデータ プロバイダーと永続化も提供します。迅速なアプリケーション開発には、このアプローチをお勧めします。

Be sure to read the General Design Considerations document to learn more about the architecture of API Platform and how to choose between these two approaches.

API Platform のアーキテクチャの詳細と、これら 2 つのアプローチの選択方法については、一般的な設計上の考慮事項のドキュメントを必ずお読みください。

Here, we will use the built-in Doctrine ORM data provider in the rest of this tutorial.

ここでは、このチュートリアルの残りの部分で組み込みの Doctrine ORM データ プロバイダーを使用します。

Modify the classes to map them to database tables using the annotations provided by the Doctrine ORM.

Doctrine ORM によって提供される注釈を使用して、クラスを変更してデータベース テーブルにマップします。

Modify these files as described in these patches:

これらのパッチの説明に従って、これらのファイルを変更します。

api/src/Entity/Book.php

api/src/Entity/Book.php

 use ApiPlatform\Metadata\ApiResource;
 use Doctrine\Common\Collections\ArrayCollection;
+use Doctrine\ORM\Mapping as ORM;

 /** A book. */
+#[ORM\Entity]
 #[ApiResource]
 class Book
 {
     /** The ID of this book. */
+    #[ORM\Id, ORM\Column, ORM\GeneratedValue]
     private ?int $id = null;

     /** The ISBN of this book (or null if doesn't have one). */
+    #[ORM\Column(nullable: true)]
     public ?string $isbn = null;

     /** The title of this book. */
+    #[ORM\Column]
     public string $title = '';

     /** The description of this book. */
+    #[ORM\Column(type: 'text')]
     public string $description = '';

     /** The author of this book. */
+    #[ORM\Column]
     public string $author = '';

     /** The publication date of this book. */
+    #[ORM\Column]
     public ?\DateTimeImmutable $publicationDate = null;

     /** @var Review[] Available reviews for this book. */
+    #[ORM\OneToMany(targetEntity: Review::class, mappedBy: 'book', cascade: ['persist', 'remove'])]
     public iterable $reviews;

     public function __construct()

api/src/Entity/Review.php

api/src/Entity/Review.php

 namespace App\Entity;

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

 /** A review of a book. */
+#[ORM\Entity]
 #[ApiResource]
 class Review
 {
     /** The ID of this review. */
+    #[ORM\Id, ORM\Column, ORM\GeneratedValue]
     private ?int $id = null;

     /** The rating of this review (between 0 and 5). */
+    #[ORM\Column(type: 'smallint')]
     public int $rating = 0;

     /** The body of the review. */
+    #[ORM\Column(type: 'text')]
     public string $body = '';

     /** The author of the review. */
+    #[ORM\Column]
     public string $author = '';

     /** The date of publication of this review.*/
+    #[ORM\Column]
     public ?\DateTimeImmutable $publicationDate = null;

     /** The book this review is about. */
+    #[ORM\ManyToOne(inversedBy: 'reviews')]
     public ?Book $book = null;

     public function getId(): ?int

Tip: you can also use Symfony MakerBundle thanks to the --api-resource option:

ヒント: --api-resource オプションのおかげで、Symfony MakerBundle も使用できます。

docker compose exec php \
    bin/console make:entity --api-resource

Doctrine's annotations map these entities to tables in the database. Mapping through attributes is also supported, if you prefer those. Both methods are convenient as they allow grouping the code and the configuration but, if you want to decouple classes from their metadata, you can switch to XML or YAML mappings. They are supported as well.

Doctrine の注釈は、これらのエンティティをデータベース内のテーブルにマップします。必要に応じて、属性を介したマッピングもサポートされます。コードと構成をグループ化できるため、どちらの方法も便利ですが、メタデータからクラスを切り離したい場合は、 XML または YAML マッピングに切り替えます。これらもサポートされています。

Learn more about how to map entities with the Doctrine ORM in the project's official documentation or in Kévin's book "Persistence in PHP with the Doctrine ORM".

Doctrine ORM を使用してエンティティをマッピングする方法については、プロジェクトの公式ドキュメントまたは Kévin の著書「Doctrine ORM を使用した PHP の永続性」を参照してください。

Now, delete the file api/src/Entity/Greeting.php. This demo entity isn't useful anymore. Finally, generate a new database migration using Doctrine Migrations and apply it:

次に、ファイル api/src/Entity/Greeting.php を削除します。このデモ エンティティはもう役に立ちません。最後に、Doctrine Migrations を使用して新しいデータベース マイグレーションを生成し、適用します。

docker compose exec php \
    bin/console doctrine:migrations:diff
docker compose exec php \
    bin/console doctrine:migrations:migrate

The php container is where your API app stands. Prefixing a command by docker compose exec php allows executing the given command in this container. You may want to create an alias to make your life easier.

php コンテナーは、API アプリが存在する場所です。コマンドの前に docker compose exec php を付けると、このコンテナーで指定されたコマンドを実行できます。生活を楽にするために、エイリアスを作成することをお勧めします。

We now have a working API with read and write capabilities!

これで、読み取りおよび書き込み機能を備えた実用的な API ができました。

In Swagger UI, click on the POST operation of the Book resource type, click on "Try it out" and send the following JSON document as request body:

Swagger UI で、Book リソース タイプの POST 操作をクリックし、[Try it out] をクリックして、次の JSON ドキュメントを要求本文として送信します。

{
  "isbn": "9781782164104",
  "title": "Persistence in PHP with the Doctrine ORM",
  "description": "This book is designed for PHP developers and architects who want to modernize their skills through better understanding of Persistence and ORM.",
  "author": "Kévin Dunglas",
  "publicationDate": "2013-12-01"
}

You just saved a new book resource through the bookshop API! API Platform automatically transforms the JSON document to an instance of the corresponding PHP entity class and uses Doctrine ORM to persist it in the database.

bookshop API を介して新しい書籍リソースを保存しました! API プラットフォームは、JSON ドキュメントを対応する PHP エンティティ クラスのインスタンスに自動的に変換し、Doctrine ORM を使用してデータベースに永続化します。

By default, the API supports GET (retrieve, on collections and items), POST (create), PUT (replace), PATCH (partial update) and DELETE (self-explanatory) HTTP methods. Don't forget to disable the ones you don't want!

デフォルトでは、API は GET (取得、コレクションおよびアイテム)、POST (作成)、PUT (置換)、PATCH (部分更新)、および DELETE (自明) HTTP メソッドをサポートします。不要なものを無効にすることを忘れないでください。

Try the GET operation on the collection. The book we added appears. When the collection contains more than 30 items, the pagination will automatically show up, and this is entirely configurable. You may be interested in adding some filters and adding sorts to the collection as well.

コレクションに対して GET 操作を試行します。追加した本が表示されます。コレクションに 30 を超えるアイテムが含まれている場合、ページネーションが自動的に表示されます。これは完全に構成可能です。いくつかのフィルターを追加したり、コレクションに並べ替えを追加したりすることに興味があるかもしれません。

You may have noticed that some keys start with the @ symbol in the generated JSON response (@id, @type, @context...)? API Platform comes with a full support of the JSON-LD format (and its Hydra extension). It allows to build smart clients, with auto-discoverability capabilities such as the API Platform Admin that we will discover in a few lines. It is useful for open data, SEO and interoperability, especially when used with open vocabularies such as Schema.org and allows to give access to Google to your structured data or to query your APIs in SPARQL using Apache Jena).

生成された JSON 応答 (@id、@type、@context...) で、一部のキーが @ 記号で始まることに気付いたかもしれません。API プラットフォームには、JSON-LD 形式 (およびその Hydraextension) が完全にサポートされています。 API Platform Admin などの自動検出機能を備えたスマート クライアントを構築できます。これは、数行で検出できます。オープン データ、SEO、および相互運用性に役立ちます。特に、Schema.organd などのオープンな語彙を使用するとGoogle に構造化データへのアクセスを許可したり、Apache Jena を使用して SPARQL で API をクエリしたりできます)。

We think that JSON-LD is the best default format for a new API. However, API Platform natively supports many other formats including GraphQL (we'll get to it), JSON:API, HAL, raw JSON, XML (experimental) and even YAML and CSV. You can also easily add support for other formats and it's up to you to choose which format to enable and to use by default.

JSON-LD が新しい API の最適なデフォルト形式であると考えています。ただし、API プラットフォームは、GraphQL (後で説明します)、JSON:API、HAL、生の JSON、XML (実験的) など、他の多くの形式をネイティブにサポートしています。 YAML や CSV も含まれます。他の形式のサポートを簡単に追加することもできます。どの形式を有効にしてデフォルトで使用するかは、ユーザー次第です。

Now, add a review for this book using the POST operation for the Review resource:

次に、Review リソースの POST 操作を使用して、この本のレビューを追加します。

{
    "book": "/books/1",
    "rating": 5,
    "body": "Interesting book!",
    "author": "Kévin",
    "publicationDate": "September 21, 2016"
}

Note: If you have installed API Platform in an existing project using composer, the content of the key book must be "/api/books/1"

注: composer を使用して既存のプロジェクトに API Platform をインストールした場合、キーブックのコンテンツは「/api/books/1」である必要があります。

There are two interesting things to mention about this request:

このリクエストについて言及すべき興味深い点が 2 つあります。

First, we learned how to work with relations. In a hypermedia API, every resource is identified by an (unique) IRI. A URL is a valid IRI, and it's what API Platform uses. The @id property of every JSON-LD document contains the IRI identifying it. You can use this IRI to reference this document from other documents. In the previous request, we used the IRI of the book we created earlier to link it with the Review we were creating. API Platform is smart enough to deal with IRIs. By the way, you may want to embed documents instead of referencing them (e.g. to reduce the number of HTTP requests). You can even let the client select only the properties it needs.

まず、リレーションの操作方法を学びました。ハイパーメディア API では、すべてのリソースが (一意の) IRI によって識別されます。URL は有効な IRI であり、API プラットフォームが使用するものです。すべての JSON-LD ドキュメントの @id プロパティには、それを識別する IRI が含まれています。この IRI を使用して、他のドキュメントからこのドキュメントを参照できます。前のリクエストでは、以前に作成した本の IRI を使用して、作成中のレビューにリンクしました。 API Platform は IRI を処理するのに十分スマートです。ちなみに、ドキュメントを参照する代わりに埋め込みたい場合があります (例: HTTP リクエストの数を減らすため)。クライアントに必要なプロパティのみを選択させることもできます。

The other interesting thing is how API Platform handles dates (the publicationDate property). API Platform understands any date format supported by PHP. In production we strongly recommend using the format specified by the RFC 3339, but, as you can see, most common formats including September 21, 2016 can be used.

もう 1 つの興味深い点は、API プラットフォームが日付を処理する方法 (publicationDate プロパティ) です。 API プラットフォームは、PHP でサポートされているすべての日付形式を認識します。本番環境では、RFC 3339 で指定された形式を使用することを強くお勧めしますが、ご覧のとおり、2016 年 9 月 21 日を含むほとんどの一般的な形式を使用できます。

To summarize, if you want to expose any entity you just have to:

要約すると、エンティティを公開したい場合は、次のことを行うだけです。

  1. Put it under the App\Entity\ namespace
    App\Entity\ 名前空間の下に配置します
  2. Write your data providers and persisters, or if you use Doctrine, map it with the database
    データ プロバイダーと永続化プログラムを作成するか、Doctrine を使用している場合はデータベースにマップします
  3. Mark it with the #[ApiPlatform\Metadata\ApiResource] attribute
    #[ApiPlatform\Metadata\ApiResource] 属性でマークします

Could it be any easier?!

もっと簡単にできますか?!

Validating Data

Now try to add another book by issuing a POST request to /books with the following body:

次に、次の本文を含む POST リクエストを /books に発行して、別の本を追加してみます。

{
  "isbn": "2815840053",
  "description": "Hello",
  "author": "Me",
  "publicationDate": "today"
}

The book is successfully created but there is a problem; we did not give it a title. It makes no sense to create a book record without a title so we really should have some validation measures in place to prevent this from being possible.

ブックは正常に作成されましたが、問題があります。タイトルは付けませんでした。タイトルのない書籍レコードを作成しても意味がないので、これを防ぐためにいくつかの検証手段を講じる必要があります。

API Platform comes with a bridge with the Symfony Validator Component. Adding some of its numerous validation constraints (or creating custom ones) to our entities is enough to validate user-submitted data. Let's add some validation rules to our data model.

API プラットフォームには、Symfony Validator コンポーネントとのブリッジが付属しています。多数の検証制約の一部をエンティティに追加する (またはカスタム制約を作成する) だけで、ユーザーが送信したデータを検証できます。データモデルにいくつかの検証ルールを追加しましょう。

Modify the following files as described in these patches:

これらのパッチの説明に従って、次のファイルを変更します。

api/src/Entity/Book.php

api/src/Entity/Book.php

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

     #[ORM\Column(nullable: true)] 
+    #[Assert\Isbn]
     public ?string $isbn = null;     

     #[ORM\Column]
+    #[Assert\NotBlank]
     public string $title = '';

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

     #[ORM\Column] 
+    #[Assert\NotBlank]
     public string $author = '';

     #[ORM\Column]
+    #[Assert\NotNull]
     public ?\DateTimeImmutable $publicationDate = null;

api/src/Entity/Review.php

api/src/Entity/Review.php

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

     #[ORM\Column(type: 'smallint')]   
+    #[Assert\Range(min: 0, max: 5)]
     public int $rating = 0;

     #[ORM\Column(type: 'text')]
+    #[Assert\NotBlank]
     public string $body = '';

     #[ORM\Column]
+    #[Assert\NotBlank]
     public string $author = '';

     #[ORM\Column] 
+    #[Assert\NotNull]
     public ?\DateTimeImmutable $publicationDate = null;

     #[ORM\ManyToOne(inversedBy: 'reviews')] 
+    #[Assert\NotNull]
     public ?Book $book = null;

     public function getId(): ?int

After updating the entities by adding those #[Assert\*] attributes (as with Doctrine, you can also use XML or YAML), try again the previous POST request.

これらの #[Assert\*] 属性を追加してエンティティを更新した後 (Doctrine と同様に、XML または YAML も使用できます)、前の POST 要求を再試行します。

{
  "@context": "/contexts/ConstraintViolationList",
  "@type": "ConstraintViolationList",
  "hydra:title": "An error occurred",
  "hydra:description": "isbn: This value is neither a valid ISBN-10 nor a valid ISBN-13.\ntitle: This value should not be blank.",
  "violations": [
    {
      "propertyPath": "isbn",
      "message": "This value is neither a valid ISBN-10 nor a valid ISBN-13."
    },
    {
      "propertyPath": "title",
      "message": "This value should not be blank."
    }
  ]
}

You now get proper validation error messages, always serialized using the Hydra error format (RFC 7807 is also supported). Those errors are easy to parse client-side. By adding the proper validation constraints, we also noticed that the provided ISBN isn't valid...

Hydra エラー形式 (RFC 7807 もサポートされています) を使用して常にシリアル化された、適切な検証エラー メッセージが表示されるようになりました。これらのエラーは、クライアント側で簡単に解析できます。適切な検証制約を追加することにより、提供されたISBNが有効でないことにも気付きました...

Adding GraphQL Support

Isn't API Platform a REST and GraphQL framework? That's true! GraphQL support isn't enabled by default. To add it we need to install the graphql-php library. Run the following command:

API Platform は REST および GraphQL フレームワークではありませんか?それは本当だ! GraphQL サポートはデフォルトでは有効になっていません。これを追加するには、graphql-php ライブラリをインストールする必要があります。次のコマンドを実行します。

docker compose exec php sh -c '
    composer require webonyx/graphql-php
    bin/console cache:clear
'
````

You now have a GraphQL API! Open `https://localhost/graphql` (or `https://localhost/api/graphql` if you used Symfony Flex to install API Platform) to play with it using the nice [GraphiQL](https://github.com/graphql/graphiql)
UI that is shipped with API Platform:

![GraphQL endpoint](images/api-platform-2.6-graphql.png)

Try it out by creating a greeting:

```graphql
mutation {
  createGreeting(input: {name: "Test2"}) {
    greeting {
      id
      name
    }
  }
}

And by reading out the greeting:

そして、挨拶を読み上げることによって:

{
  greeting(id: "/greetings/1") {
    id
    name
    _id
  }
}

You can also try things a bit more complex:

もう少し複雑なことを試すこともできます。

{
  books {
    totalCount
    edges {
      node {
        id
        title
        reviews {
          totalCount
          edges {
            node {
              author
              rating
            }
          }
        }
      }
    }
  }
}

The GraphQL implementation supports queries, mutations, 100% of the Relay server specification, pagination, filters and access control rules. You can use it with the popular RelayJS and Apollo clients.

GraphQL 実装は、クエリ、ミューテーション、Relay サーバー仕様、ページネーション、フィルター、およびアクセス制御ルールの 100% をサポートします。人気のある RelayJS および Apolloclients で使用できます。

The Admin

Wouldn't it be nice to have an administration backend to manage the data exposed by your API? Wait... You already have one!

API によって公開されたデータを管理するための管理バックエンドがあると便利だと思いませんか?待ってください...もう 1 つあるのです!

Open https://localhost/admin/ in your browser:

ブラウザーで https://localhost/admin/ を開きます。

The admin

This Material Design admin is a Progressive Web App built with API Platform Admin (React Admin inside!). It is powerful and fully customizable. Refer to its documentation to learn more. It leverages the Hydra documentation exposed by the API component to build itself. It's 100% dynamic - no code generation occurs.

このマテリアル デザイン管理者は、API プラットフォーム管理者 (内部の React 管理者) を使用して構築されたプログレッシブ Web アプリです。これは強力で、完全にカスタマイズ可能です。詳細については、そのドキュメントを参照してください。API コンポーネントによって公開された Hydra ドキュメントを利用して、それ自体を構築します。 100% 動的です - コード生成は発生しません。

A Next.js Web App

API Platform also has an awesome client generator able to scaffold fully working Next.js, Nuxt.js, React/Redux, Vue.js, Quasar and Vuetify Progressive Web Apps that you can easily tune and customize. The generator also supports React Native if you prefer to leverage all capabilities of mobile devices.

API プラットフォームには、完全に機能する Next.js、Nuxt.js、React/Redux、Vue.js、Quasar、および Vuetify プログレッシブ Web アプリを簡単に調整およびカスタマイズできるスキャフォールディングが可能な素晴らしいクライアント ジェネレーターもあります。モバイル デバイスのすべての機能を活用したい場合、ジェネレーターは React Native もサポートします。

The distribution comes with a skeleton ready to welcome the Next.js flavor of the generated code. To bootstrap your app, run:

ディストリビューションには、生成されたコードの Next.js フレーバーを受け入れる準備ができているスケルトンが付属しています。アプリをブートストラップするには、次を実行します。

docker compose exec pwa \
    pnpm create @api-platform/client

Open https://localhost/books/ in your browser:

ブラウザーで https://localhost/books/ を開きます。

The Next.js Progressive Web App

You can also choose to generate the code for a specific resource with the --resource argument (example: pnpm create @api-platform/client --resource books).

--resource 引数を使用して、特定のリソースのコードを生成することも選択できます (例: pnpm create @api-platform/client --resource books)。

The generated code contains a list (including pagination), a delete button, a creation and an edition form. It also includes Tailwind CSS classes and ARIA roles to make the app usable by people with disabilities.

生成されたコードには、リスト (ページネーションを含む)、削除ボタン、作成および編集フォームが含まれています。また、Tailwind CSS クラスと ARIA ロールも含まれており、障害を持つユーザーがアプリを使用できるようになっています。

If you prefer to generate a PWA built on top of another frontend stack, read the dedicated documentation.

別のフロントエンド スタックの上に構築された PWA を生成する場合は、専用のドキュメントをお読みください。

Hooking Your Own Business Logic

Now that you learned the basics, be sure to read the general design considerations and how to extend API Platform to understand how API Platform is designed, and how to hook your custom business logic!

基本を学んだので、一般的な設計上の考慮事項と API プラットフォームの拡張方法を必ず読んで、API プラットフォームの設計方法とカスタム ビジネス ロジックをフックする方法を理解してください。

Other Features

First, you may want to learn how to deploy your application in the cloud using the built-in Kubernetes integration.

最初に、組み込みの Kubernetes 統合を使用してクラウドにアプリケーションをデプロイする方法を学びたいと思うかもしれません。

Then, there are many more features to learn! Read the full documentation to discover how to use them and how to extend API Platform to fit your needs. API Platform is incredibly efficient for prototyping and Rapid Application Development (RAD), but the framework is mostly designed to create complex API-driven projects, far beyond simple CRUD apps. It benefits from strong extension points and it is continuously optimized for performance. It powers numerous high traffic websites.

さらに、学ぶべき機能がたくさんあります。完全なドキュメントを読んで、API プラットフォームの使用方法とニーズに合わせて API プラットフォームを拡張する方法を確認してください。シンプルな CRUD アプリ。強力な拡張ポイントの恩恵を受け、継続的にパフォーマンスが最適化されます。多くのトラフィックの多い Web サイトに力を与えています。

API Platform has a built-in HTTP cache invalidation system which allows to make API Platform apps blazing fast using Varnish. Read more in the chapter API Platform Core Library: Enabling the Built-in HTTP Cache Invalidation System.

API Platform には組み込みの HTTP キャッシュ無効化システムがあり、Varnish を使用して API Platform アプリを高速化できます。詳細については、「API プラットフォーム コア ライブラリ: 組み込み HTTP キャッシュ無効化システムの有効化」の章を参照してください。

Keep in mind that you can use your favorite client-side technology: API Platform provides generators for popular JavaScript frameworks, but you can also use your preferred client-side technology including Angular, Ionic and Swift directly. Any language able to send HTTP requests is OK (even COBOL can do that).

お気に入りのクライアント側テクノロジーを使用できることに注意してください。API プラットフォームは、一般的な JavaScript フレームワークのジェネレーターを提供しますが、Angular、Ionic、Swift などの好みのクライアント側テクノロジーを直接使用することもできます。 HTTP リクエストを送信できる言語であれば問題ありません (COBOL でも送信できます)。

To go further, the API Platform team maintains a demo application showing more advanced use cases like leveraging serialization groups, user management or JWT and OAuth authentication. Checkout the demo code source on GitHub and browse it online.

さらに進むために、API プラットフォーム チームは、シリアライゼーション グループ、ユーザー管理、JWT および OAuth 認証の活用など、より高度なユース ケースを示すデモ アプリケーションを維持しています。 GitHub でデモ コード ソースをチェックアウトし、オンラインで参照してください。

Screencasts

SymfonyCasts, API Platform screencasts

The easiest and funniest way to learn how to use API Platform is to watch the more than 60 screencasts available on SymfonyCasts!

API プラットフォームの使い方を学ぶ最も簡単で楽しい方法は、SymfonyCast で利用できる 60 以上のスクリーンキャストを見ることです!