winzik/docs/ide/api-platform.md

99 lines
8 KiB
Markdown

# API Platform
The **API Platform** window (bottom tool bar; Search Everywhere: *API Platform: …*) appears in a project whose `composer.json` requires
`api-platform/core` (or another `api-platform/*` package). It reads the API from the sources, without running anything: the
`#[ApiResource]` attributes of the classes of the PSR-4 folders (entities and DTOs, promoted constructor properties too), their
operations, `#[Groups]`, `#[ApiProperty]` and `#[ApiFilter]`. Five tabs; the window can take the whole screen (its ⤢ button, Escape gives
it back). In the Doctrine window, the entity editor and the diagram's menu have an **API Platform…** entry that opens a class here.
**API Platform not installed yet?** Ticking *API Platform resource (#[ApiResource])* in the **New entity** dialog shows a notice
(*API Platform is not installed in this project*) with an **Install API Platform** button; so does *New… > Install API Platform…*.
It shows the command (`composer require api`, the Symfony Flex pack, for Symfony 6.4+ with Flex; `api-platform/symfony` without Flex;
`api-platform/core:^3.2` / `^2.7` for older Symfony, read from `composer.lock`), runs it through the Composer window's runner with its
output shown live, and the API Platform window appears without restarting the IDE. Declined: the attribute is still written, with a warning
that the class is undefined until the package is installed. Any other undefined class (`Undefined class 'X\Y'`) has the quick fix
**Install the missing package…** (candidates: a built-in map of common namespaces, then Packagist).
![A resource's options and operations](images/api-platform-resource.png)
Every change is **computed here and shown as a diff first**; nothing is written before *Apply*. Only the touched arguments change: the
attribute is edited argument by argument (`php-parser` positions), everything else keeps its exact bytes, the style of the list (one line
or one argument per line) is followed, and the `use` lines are added. A value the code holds as an expression (`security: self::RULE`,
`'groups' => [Book::READ]`) is shown as such and never rewritten.
![The diff before a change is written](images/api-platform-diff.png)
## Resources
The list on the left holds the project's entities and DTOs (`API` badge when the class has `#[ApiResource]`; filter by class or short
name). For the chosen class:
- **#[ApiResource] on / off**: *Expose it with #[ApiResource]* adds the attribute (with its `use`), *Remove #[ApiResource]* takes it away.
A class with several `#[ApiResource]` (a **subresource** has its own `uriTemplate` + `uriVariables`) shows one chip per attribute;
**Subresource** adds another one.
- **General**: short name, URI template, **URI variables** (`new Link(fromClass:, fromProperty:, toProperty:)`).
- **Serialization and validation**: the *normalization*, *denormalization* and *validation* groups (chips; the other keys of the context,
`enable_max_depth`... stay).
- **Security**: `security`, `securityPostDenormalize`, `securityMessage`.
- **Pagination**: enabled (default / yes / no), items per page, the client's control (on / off, items per page), the most items per page.
- **Formats and order**: `jsonld`, `json`, `jsonapi`, `hal`, `xml`, `csv`, `html`; the default order (`['title' => 'ASC']`).
- **State**: `provider`, `processor`, `input`, `output` (a class, or `false`).
- **Operations**: `Get`, `GetCollection`, `Post`, `Put`, `Patch`, `Delete`, each with its route (method and path) and its own options
(name, `uriTemplate`, `controller`, security, groups, pagination, provider / processor / input / output): add, remove, change the type,
fold / unfold. When the code lists none, API Platform's defaults are shown (Get, GetCollection, Post, Patch, Delete; Put too before
API Platform 4); *Make them explicit to edit them* writes the list.
## Properties
![The property grid](images/api-platform-groups.png)
A grid, one row per property (a key marks the identifier; the Doctrine type or relation is shown). **Group columns**: the serialization
groups of the resource's contexts and of the properties; each cell is the `#[Groups([...])]` attribute (created, changed or removed). In
the header, **R** and **W** tell whether the group is a *read* group (the resource's `normalizationContext`) and / or a *write* group
(`denormalizationContext`); toggling them edits the resource in the same diff, and **+ Group** adds a column. Then: **Readable**,
**Writable**, **Identifier**, **Description**, **Example** (`#[ApiProperty]`, removed when it has no argument left) and **Filters**:
`SearchFilter` (strategy `exact`, `partial`, `start`, `end`, `word_start`), `OrderFilter`, `RangeFilter`, `DateFilter`, `BooleanFilter`,
`ExistsFilter`, `NumericFilter` as `#[ApiFilter(...)]` attributes (a filter already there keeps its other arguments). Filters declared on
the class are listed below the grid.
## State
The classes implementing `ProviderInterface` / `ProcessorInterface`, with where they are used. **New provider…** / **New processor…**
write a class from a template (`src/State/`), optionally **decorating Doctrine's own** (the collection / item providers, the persist
processor, injected with `#[Autowire]`), and wire it to the resource in the same diff (`processor: BookProcessor::class`). **Wire…**
connects an existing one.
## Routes
Every route, worked out from the code (method, path with the prefix of `config/routes/api_platform.yaml`, resource, operation, security,
name); a click opens the resource. **Compare with debug:router** runs `debug:router` through the Console window's runner and marks each
route ✓ / ✗, and lists the API routes the console has that the code does not explain. **OpenAPI export** shows `api:openapi:export`.
## Requests
![The state of every request file](images/api-platform-requests.png)
![The generated collection in the HTTP Client](images/api-platform-http-client.png)
**Generate for all resources** (or for one) makes, for each resource, an [HTTP Client](http-client.md) collection `http-requests/<Resource>/`:
- one `.http` file per operation (`list`, `get`, `create`, `replace`, `update`, `delete`, `<custom>`; subresources in a `sub-…` folder):
URL under `{{baseUrl}}`, the method, `Accept` and `Content-Type` (`application/ld+json`, or the first of `formats`;
`application/merge-patch+json` for `PATCH`), an **example body** built from the properties the operation writes (the denormalization
groups, `#[ApiProperty(writable: false)]` out, the `input` class when there is one) with example values by type (`#[ApiProperty(example:)]`,
the first case of an enum, an IRI for a relation), the **filters as commented query parameters** (`# ?title=…`, `# ?order[title]=asc`,
`# ?pages[gte]=1`, `# ?page=2`), a status test, and a script saving the new id (`{{bookId}}` used by the other requests);
- a new collection gets the environment (`baseUrl`, the ids, the login) and, with `lexik/jwt-authentication-bundle`, a **JWT login**
request (read from `security.yaml`) the collection's auth uses.
**Regeneration** follows the class, with one rule: a request someone edited is never overwritten. The collection's `.apiplatform.json`
keeps the hash of what the tool wrote. A file still equal to it is rewritten (or deleted when the operation is gone); a file that differs,
or that the tool never wrote, stays as it is and the new version goes beside it as `name.theirs.http` (only when there is something new
to say). The window shows the state of every file (new, will be refreshed, up to date, yours kept, deleted) and the diff before writing.
## Tests
`ide/tests/ApiPlatformTest.php`: the attributes read from several shapes, the exact text of every change (`tests/fixtures/api-platform-expected/`),
the property grid, State classes, the requests and the regeneration rules. `games/ide/tools/api-platform-check.sh <a copy of a Symfony project
with api-platform/core>` is the real check: an entity made through the Doctrine window's backend, `#[ApiResource]` edited, `debug:router`, and the
generated requests run by the HTTP Client against `php -S`. `games/ide/tools/ui-api-platform-check.sh` takes the screenshots of this page.