Api Platform conference
Register now
Guides
Guide

Provide the Resource State

design state
Our model is the same then in the previous guide (Declare a Resource. API Platform will declare CRUD operations if we don’t declare them.
// src/App/ApiResource.php namespace App\ApiResource; use ApiPlatform\Metadata\ApiResource; use App\State\BookProvider;
We use a BookProvider as the ApiResource::provider option.
#[ApiResource(provider: BookProvider::class)] class Book {  public string $id; }  // src/App/State.php namespace App\State; use ApiPlatform\Metadata\CollectionOperationInterface; use ApiPlatform\Metadata\Operation; use ApiPlatform\State\ProviderInterface; use App\ApiResource\Book;
The BookProvider is where we retrieve the data in our persistence layer. In this provider we choose to handle the retrieval of a single Book but also a list of Books.
final class BookProvider implements ProviderInterface {  public function provide(Operation $operation, array $uriVariables = [], array $context = []): iterable|object|null  {  if ($operation instanceof CollectionOperationInterface) {  $book = new Book();  $book->id = '1';  /* $book2 = new Book();  * $book2->id = '2'; */
As an exercise you can edit the code and add a second book in the collection.
 return [$book/* $book2 */];  }  $book = new Book();
The value at $uriVariables['id'] is the one that matches the {id} variable of the URI template.
 $book->id = $uriVariables['id'];  return $book;  } }  // src/App/Playground.php namespace App\Playground; use Symfony\Component\HttpFoundation\Request; function request(): Request {  return Request::create('/books.jsonld', 'GET'); }

You can also help us improve this guide.

Made with love by

Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.

Learn more

Copyright © 2023 Kévin Dunglas

Sponsored by Les-Tilleuls.coop