-
-
Notifications
You must be signed in to change notification settings - Fork 891
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(serializer): add ApiProperty::uriTemplate option
This feature gives control over the operation used for *toOne and *toMany relations IRI generation. When defined, API Platform will use the operation declared on the related resource that matches the uriTemplate string. In addition, this will override the value returned to be the IRI string only, not an object in JSONLD formats. For HAL and JSON:API format, the IRI will be used in links properties, and in the objects embedded or in relationship properties.
- Loading branch information
1 parent
b58ec12
commit d7eac24
Showing
31 changed files
with
1,451 additions
and
92 deletions.
There are no files selected for viewing
208 changes: 208 additions & 0 deletions
208
docs/guides/return-the-iri-of-your-resources-relations.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,208 @@ | ||
<?php | ||
// --- | ||
// slug: return-the-iri-of-your-resources-relations | ||
// name: How to return an IRI instead of an object for your resources relations ? | ||
// executable: true | ||
// tags: serialization | ||
// --- | ||
|
||
// This guide shows you how to expose the IRI of a related (sub)ressource relation instead of an object. | ||
|
||
namespace App\ApiResource { | ||
use ApiPlatform\Metadata\ApiProperty; | ||
use ApiPlatform\Metadata\ApiResource; | ||
use ApiPlatform\Metadata\Get; | ||
use ApiPlatform\Metadata\GetCollection; | ||
use ApiPlatform\Metadata\Link; | ||
use ApiPlatform\Metadata\Operation; | ||
use ApiPlatform\State\ProviderInterface; | ||
use Symfony\Component\Serializer\Annotation\Groups; | ||
|
||
#[ApiResource( | ||
operations: [ | ||
new Get(normalizationContext: ['groups' => ['read']], provider: Brand::class), | ||
], | ||
)] | ||
class Brand implements ProviderInterface | ||
{ | ||
public function __construct( | ||
#[ApiProperty(identifier: true)] | ||
public readonly int $id = 1, | ||
|
||
#[Groups('read')] | ||
public readonly string $name = 'Anon', | ||
|
||
// Setting uriTemplate on a relation with a resource collection will try to find the related operation. | ||
// It is based on the uriTemplate set on the operation defined on the Car resource (see below). | ||
/** | ||
* @var array<int, Car> $cars | ||
*/ | ||
#[ApiProperty(uriTemplate: '/brands/{brandId}/cars')] | ||
#[Groups('read')] | ||
private array $cars = [], | ||
|
||
// Setting uriTemplate on a relation with a resource item will try to find the related operation. | ||
// It is based on the uriTemplate set on the operation defined on the Address resource (see below). | ||
#[ApiProperty(uriTemplate: '/brands/{brandId}/addresses/{id}')] | ||
#[Groups('read')] | ||
private ?Address $headQuarters = null | ||
) | ||
{ | ||
} | ||
|
||
/** | ||
* @return array<int, Car> | ||
*/ | ||
public function getCars(): array | ||
{ | ||
return $this->cars; | ||
} | ||
|
||
public function addCar(Car $car): self | ||
{ | ||
$car->setBrand($this); | ||
$this->cars[] = $car; | ||
|
||
return $this; | ||
} | ||
|
||
public function getHeadQuarters(): ?Address | ||
{ | ||
return $this->headQuarters; | ||
} | ||
|
||
public function setHeadQuarters(?Address $headQuarters): self | ||
{ | ||
$headQuarters?->setBrand($this); | ||
$this->headQuarters = $headQuarters; | ||
|
||
return $this; | ||
} | ||
|
||
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null | ||
{ | ||
return (new self(1, 'Ford')) | ||
->setHeadQuarters(new Address(1, 'One American Road near Michigan Avenue, Dearborn, Michigan')) | ||
->addCar(new Car(1, 'Torpedo Roadster')); | ||
} | ||
} | ||
|
||
#[ApiResource( | ||
operations: [ | ||
new Get, | ||
// Without the use of uriTemplate on the property this would be used coming from the Brand resource, but not anymore. | ||
new GetCollection(uriTemplate: '/cars'), | ||
// This operation will be used to create the IRI instead since the uriTemplate matches. | ||
new GetCollection( | ||
uriTemplate: '/brands/{brandId}/cars', | ||
uriVariables: [ | ||
'brandId' => new Link(toProperty: 'brand', fromClass: Brand::class), | ||
] | ||
), | ||
], | ||
)] | ||
class Car | ||
{ | ||
public function __construct( | ||
#[ApiProperty(identifier: true)] | ||
public readonly int $id = 1, | ||
public readonly string $name = 'Anon', | ||
private ?Brand $brand = null | ||
) | ||
{ | ||
} | ||
|
||
public function getBrand(): Brand | ||
{ | ||
return $this->brand; | ||
} | ||
|
||
public function setBrand(Brand $brand): void | ||
{ | ||
$this->brand = $brand; | ||
} | ||
} | ||
|
||
#[ApiResource( | ||
operations: [ | ||
// Without the use of uriTemplate on the property this would be used coming from the Brand resource, but not anymore. | ||
new Get(uriTemplate: '/addresses/{id}'), | ||
// This operation will be used to create the IRI instead since the uriTemplate matches. | ||
new Get( | ||
uriTemplate: '/brands/{brandId}/addresses/{id}', | ||
uriVariables: [ | ||
'brandId' => new Link(toProperty: 'brand', fromClass: Brand::class), | ||
'id' => new Link(fromClass: Address::class), | ||
] | ||
) | ||
], | ||
)] | ||
class Address | ||
{ | ||
public function __construct( | ||
#[ApiProperty(identifier: true)] | ||
public readonly int $id = 1, | ||
#[Groups('read')] | ||
public readonly string $name = 'Anon', | ||
private ?Brand $brand = null | ||
) | ||
{ | ||
} | ||
|
||
public function getBrand(): Brand | ||
{ | ||
return $this->brand; | ||
} | ||
|
||
public function setBrand(Brand $brand): void | ||
{ | ||
$this->brand = $brand; | ||
} | ||
} | ||
} | ||
|
||
// If API Platform does not find any `GetCollection` operation on the target resource, it will result in a `NotFoundException`. | ||
// | ||
// The **OpenAPI** documentation will set the properties as `read-only` of type `string` in the format `iri-reference` for `JSON-LD`, `JSON:API` and `HAL` formats. | ||
// | ||
// The **Hydra** documentation will set the properties as `hydra:Link` with the right domain, with `hydra:readable` to `true` but `hydra:writable` to `false`. | ||
// | ||
// When using JSON:API or HAL formats, the IRI will be used and set links, embedded and relationship. | ||
// | ||
// *Additional Note:* If you are using the default doctrine provider, this will prevent unnecessary sql join and related processing. | ||
|
||
namespace App\Playground { | ||
use Symfony\Component\HttpFoundation\Request; | ||
|
||
function request(): Request | ||
{ | ||
return Request::create('/brands/1.jsonld', 'GET'); | ||
} | ||
} | ||
|
||
|
||
namespace App\Tests { | ||
use ApiPlatform\Playground\Test\TestGuideTrait; | ||
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase; | ||
use App\ApiResource\Brand; | ||
|
||
final class BrandTest extends ApiTestCase | ||
{ | ||
use TestGuideTrait; | ||
|
||
public function testResourceExposeIRI(): void | ||
{ | ||
static::createClient()->request('GET', '/brands/1.jsonld'); | ||
|
||
$this->assertResponseIsSuccessful(); | ||
$this->assertMatchesResourceCollectionJsonSchema(Brand::class, '_api_/brand{._format}_get_item'); | ||
$this->assertJsonContains([ | ||
"@context" => "/contexts/Brand", | ||
"@id" => "/brands/1", | ||
"@type" => "Brand", | ||
"cars" => "/brands/1/cars", | ||
"headQuarters" => "/brands/1/addresses/1" | ||
]); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
@php8 | ||
@v3 | ||
Feature: Exposing a property being a collection of resources | ||
can return an IRI instead of an array | ||
when the uriTemplate is set on the ApiProperty attribute | ||
|
||
@createSchema | ||
Scenario: Retrieve Resource with uriTemplate collection Property | ||
Given there are propertyCollectionIriOnly with relations | ||
When I add "Accept" header equal to "application/hal+json" | ||
And I send a "GET" request to "/property_collection_iri_onlies/1" | ||
Then the response status code should be 200 | ||
And the response should be in JSON | ||
And the JSON should be valid according to the JSON HAL schema | ||
And the header "Content-Type" should be equal to "application/hal+json; charset=utf-8" | ||
And the JSON should be equal to: | ||
""" | ||
{ | ||
"_links": { | ||
"self": { | ||
"href": "/property_collection_iri_onlies/1" | ||
}, | ||
"propertyCollectionIriOnlyRelation": { | ||
"href": "/property-collection-relations" | ||
}, | ||
"iterableIri": { | ||
"href": "/parent/1/another-collection-operations" | ||
}, | ||
"toOneRelation": { | ||
"href": "/parent/1/property-uri-template/one-to-ones/1" | ||
} | ||
}, | ||
"_embedded": { | ||
"propertyCollectionIriOnlyRelation": [ | ||
{ | ||
"_links": { | ||
"self": { | ||
"href": "/property_collection_iri_only_relations/1" | ||
} | ||
}, | ||
"name": "asb" | ||
} | ||
], | ||
"iterableIri": [ | ||
{ | ||
"_links": { | ||
"self": { | ||
"href": "/property_collection_iri_only_relations/9999" | ||
} | ||
}, | ||
"name": "Michel" | ||
} | ||
], | ||
"toOneRelation": { | ||
"_links": { | ||
"self": { | ||
"href": "/parent/1/property-uri-template/one-to-ones/1" | ||
} | ||
}, | ||
"name": "xarguš" | ||
} | ||
} | ||
} | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
@php8 | ||
@v3 | ||
Feature: Exposing a property being a collection of resources | ||
can return an IRI instead of an array | ||
when the uriTemplate is set on the ApiProperty attribute | ||
|
||
Background: | ||
Given I add "Accept" header equal to "application/vnd.api+json" | ||
And I add "Content-Type" header equal to "application/vnd.api+json" | ||
|
||
@createSchema | ||
Scenario: Retrieve Resource with uriTemplate collection Property | ||
Given there are propertyCollectionIriOnly with relations | ||
And I send a "GET" request to "/property_collection_iri_onlies/1" | ||
Then the response status code should be 200 | ||
And the response should be in JSON | ||
And the JSON should be valid according to the JSON HAL schema | ||
And the header "Content-Type" should be equal to "application/vnd.api+json; charset=utf-8" | ||
And the JSON should be equal to: | ||
""" | ||
{ | ||
"links": { | ||
"propertyCollectionIriOnlyRelation": "/property-collection-relations", | ||
"iterableIri": "/parent/1/another-collection-operations", | ||
"toOneRelation": "/parent/1/property-uri-template/one-to-ones/1" | ||
}, | ||
"data": { | ||
"id": "/property_collection_iri_onlies/1", | ||
"type": "PropertyCollectionIriOnly", | ||
"relationships": { | ||
"propertyCollectionIriOnlyRelation": { | ||
"data": [ | ||
{ | ||
"type": "PropertyCollectionIriOnlyRelation", | ||
"id": "/property_collection_iri_only_relations/1" | ||
} | ||
] | ||
}, | ||
"iterableIri": { | ||
"data": [ | ||
{ | ||
"type": "PropertyCollectionIriOnlyRelation", | ||
"id": "/property_collection_iri_only_relations/9999" | ||
} | ||
] | ||
}, | ||
"toOneRelation": { | ||
"data": { | ||
"type": "PropertyUriTemplateOneToOneRelation", | ||
"id": "/parent/1/property-uri-template/one-to-ones/1" | ||
} | ||
} | ||
} | ||
} | ||
} | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.