|
| 1 | +# JSON:API |
| 2 | + |
| 3 | +API Platform supports the [JSON:API](https://jsonapi.org) format. When a client |
| 4 | +sends a request with an `Accept: application/vnd.api+json` header, API Platform |
| 5 | +serializes responses following the JSON:API specification. |
| 6 | + |
| 7 | +For details on enabling formats, see |
| 8 | +[content negotiation](content-negotiation.md). |
| 9 | + |
| 10 | +## Entity Identifiers as Resource IDs |
| 11 | + |
| 12 | +We recommend configuring API Platform to use entity identifiers as the `id` |
| 13 | +field of JSON:API resource objects. This will become the default in 5.x: |
| 14 | + |
| 15 | +```yaml |
| 16 | +# config/packages/api_platform.yaml |
| 17 | +api_platform: |
| 18 | + jsonapi: |
| 19 | + use_iri_as_id: false |
| 20 | +``` |
| 21 | +
|
| 22 | +With this configuration, the JSON:API `id` field contains the entity identifier |
| 23 | +(e.g., `"10"`) instead of the full IRI (e.g., `"/dummies/10"`). A `links.self` |
| 24 | +field is added to each resource object for navigation: |
| 25 | + |
| 26 | +```json |
| 27 | +{ |
| 28 | + "data": { |
| 29 | + "id": "10", |
| 30 | + "type": "Dummy", |
| 31 | + "links": { |
| 32 | + "self": "/dummies/10" |
| 33 | + }, |
| 34 | + "attributes": { |
| 35 | + "name": "Dummy #10" |
| 36 | + }, |
| 37 | + "relationships": { |
| 38 | + "relatedDummy": { |
| 39 | + "data": { |
| 40 | + "id": "1", |
| 41 | + "type": "RelatedDummy" |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +Relationships reference related resources by entity identifier and `type`. |
| 50 | + |
| 51 | +### Composite Identifiers |
| 52 | + |
| 53 | +Resources with composite identifiers use a semicolon-separated string as the `id` |
| 54 | +value (e.g., `"field1=val1;field2=val2"`). |
| 55 | + |
| 56 | +### Resources Without a Standalone Item Endpoint |
| 57 | + |
| 58 | +API Platform must resolve the IRI for any resource that appears in a |
| 59 | +relationship. If a resource has no standalone `GET` item endpoint (for example, |
| 60 | +it is only exposed as a subresource), IRI resolution fails. |
| 61 | + |
| 62 | +Use the `NotExposed` operation to register a URI template for internal IRI |
| 63 | +resolution without exposing a public endpoint. A `NotExposed` operation registers |
| 64 | +the route internally but returns a `404` response when accessed directly: |
| 65 | + |
| 66 | +```php |
| 67 | +<?php |
| 68 | +
|
| 69 | +namespace App\Entity; |
| 70 | +
|
| 71 | +use ApiPlatform\Metadata\NotExposed; |
| 72 | +
|
| 73 | +#[NotExposed(uriTemplate: '/tags/{id}')] |
| 74 | +class Tag |
| 75 | +{ |
| 76 | + public int $id; |
| 77 | + public string $label; |
| 78 | +} |
| 79 | +``` |
| 80 | + |
| 81 | +This allows a parent resource to reference `Tag` objects in its relationships |
| 82 | +while `Tag` itself has no public item endpoint. The `NotExposed` operation |
| 83 | +requires a `uriTemplate` with a single URI variable. |
0 commit comments