### Create React App and Install API Platform Admin (Bash)
Source: https://api-platform.com/docs/v2.7/admin/getting-started
This snippet shows how to create a new React application using Create React App and then install the @api-platform/admin library. It requires Node.js and npm to be installed.
```bash
npm init react-app my-admin
cd my-admin
npm install @api-platform/admin
```
--------------------------------
### Install Schema Generator (Composer)
Source: https://api-platform.com/docs/v2.7/schema-generator/getting-started
Installs the Schema Generator as a development dependency in an existing project using Composer. This is an alternative to the Docker-based installation.
```bash
composer require --dev api-platform/schema-generator
```
--------------------------------
### Install React App and Dependencies
Source: https://api-platform.com/docs/v2.7/create-client/react
This snippet shows how to bootstrap a new React application using Create React App with TypeScript, install necessary routing and form handling libraries, and optionally add styling libraries like Bootstrap and Font Awesome. Finally, it starts the development server.
```bash
npm init react-app --template typescript my-app
cd my-app
npm install react-router-dom react-hook-form
npm install bootstrap font-awesome
npm run start
```
--------------------------------
### Install Schema Generator (Docker)
Source: https://api-platform.com/docs/v2.7/schema-generator/getting-started
Installs the Schema Generator as a development dependency for the API Platform distribution using Docker. This command executes the generator within the PHP container.
```bash
docker compose exec php \
vendor/bin/schema
```
--------------------------------
### Install Google Cloud SDK
Source: https://api-platform.com/docs/v2.7/deployment/kubernetes
Installs the Google Cloud SDK, which is necessary for interacting with Google Cloud services like the Container Registry. This command downloads and executes the installation script.
```bash
curl https://sdk.cloud.google.com | bash
```
--------------------------------
### ApiProperty Metadata Update Example (PHP)
Source: https://api-platform.com/docs/v2.7/core/upgrade-guide
Demonstrates the change in `ApiPlatformMetadataApiProperty` usage in API Platform 2.7 compared to older versions. It highlights the shift from `iri` to `types` and `type` to `builtinTypes`, explaining how PHP types are automatically inferred.
```php
(
);
```
--------------------------------
### Start Development Server
Source: https://api-platform.com/docs/v2.7/create-client/nextjs
Commands to launch the Next.js development server.
```bash
# using pnpm
pnpm dev
# or using npm
npm run dev
# or using yarn
yarn dev
```
--------------------------------
### Run Schema Generator (API Platform Distribution)
Source: https://api-platform.com/docs/v2.7/schema-generator/getting-started
Runs the Schema Generator within the API Platform Distribution environment using Docker Compose. This command generates PHP classes in the 'src/' directory based on the 'config/schema.yaml' configuration.
```bash
docker compose exec php \
vendor/bin/schema generate src/ config/schema.yaml -vv
```
--------------------------------
### Install Bootstrap and Font Awesome (Optional)
Source: https://api-platform.com/docs/v2.7/create-client/vuejs
Installs Bootstrap for UI styling and Font Awesome for icon support. These are optional but recommended for a visually appealing application.
```bash
npm install add bootstrap font-awesome
```
--------------------------------
### GraphQL Mutation Example (GraphQL)
Source: https://api-platform.com/docs/v2.7/core/graphql
Demonstrates how to call custom GraphQL mutations defined in API Platform. This includes examples for a basic custom mutation, a mutation with custom arguments, and a mutation where specific stages are disabled.
```graphql
{
mutation {
mutationBook(input: {id: "/books/18", title: "The Fitz and the Fool"}) {
book {
title
}
}
}
mutation {
withCustomArgsMutationBook(input: {sendMail: true, clientMutationId: "myId"}) {
book {
title
}
clientMutationId
}
}
mutation {
disabledStagesMutationBook(input: {id: "/books/18", title: "The Fitz and the Fool"}) {
book {
title
}
clientMutationId
}
}
}
```
--------------------------------
### Install Required Dependencies
Source: https://api-platform.com/docs/v2.7/create-client/nextjs
Installs necessary packages for the API Platform Next.js integration, including isomorphic-unfetch, formik, and react-query.
```bash
# using pnpm
pnpm install isomorphic-unfetch formik react-query
# or using npm
npm install isomorphic-unfetch formik react-query
# or using yarn
yarn add isomorphic-unfetch formik react-query
```
--------------------------------
### Install Testing Client Dependencies (Bash)
Source: https://api-platform.com/docs/v2.7/core/testing
Installs the necessary `symfony/browser-kit` and `symfony/http-client` packages using Composer within a Docker environment. These are required to enable the API Platform test client.
```bash
docker compose exec php \
composer require symfony/browser-kit symfony/http-client
```
--------------------------------
### Install VichUploaderBundle with Composer
Source: https://api-platform.com/docs/v2.7/core/file-upload
Installs the VichUploaderBundle using Composer within a Dockerized PHP environment. This is the initial step to enable file upload capabilities.
```bash
docker compose exec php \
composer require vich/uploader-bundle
```
--------------------------------
### Page-based Pagination Query Example (GraphQL)
Source: https://api-platform.com/docs/v2.7/core/graphql
Shows an example GraphQL query utilizing page-based pagination. It demonstrates how to request specific pages and items per page, and how to retrieve pagination details like 'itemsPerPage', 'lastPage', and 'totalCount'. This query is used after enabling page-based pagination for a resource.
```graphql
{
offers(page: 3, itemsPerPage: 15) {
collection {
id
}
paginationInfo {
itemsPerPage
lastPage
totalCount
}
}
}
```
--------------------------------
### API Platform v2.7 Serializer Component Setup
Source: https://api-platform.com/docs/v2.7/core/bootstrap
Configures the core Symfony Serializer component with necessary normalizers and encoders for API Platform. It includes setup for JSON encoding and handling various data types.
```php
$doctrineAnnotationReader = new AnnotationReader();
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader($doctrineAnnotationReader));
$serializer = new Serializer(
[
new UnwrappingDenormalizer(),
new ProblemNormalizer(),
new ConstraintViolationListNormalizer(),
new DateTimeZoneNormalizer(),
new DateIntervalNormalizer(),
new DateTimeNormalizer(),
new JsonSerializableNormalizer(),
new DataUriNormalizer(),
new ObjectNormalizer(
null,
null,
null,
new MetadataAwareNameConverter($classMetadataFactory)
),
new ArrayDenormalizer(),
],
[
new JsonLdEncoder(),
new JsonEncoder()
]
);
```
--------------------------------
### DataProvider Implementation (PHP)
Source: https://api-platform.com/docs/v2.7/core/bootstrap
Implements data provider interfaces for fetching collections and individual items of a resource. The example shows a basic implementation for a 'Book' resource, returning mock data. It supports collection retrieval, item retrieval by identifiers, and indicates support for any resource class and operation.
```php
class DataProvider implements DenormalizedIdentifiersAwareItemDataProviderInterface, RestrictedDataProviderInterface, ContextAwareCollectionDataProviderInterface
{
public function getCollection(string $resourceClass, string $operationName = null, array $context = [])
{
$book = new Book();
$book->id = '1';
return [$book];
}
public function getItem(string $resourceClass, $identifiers, string $operationName = null, array $context = []) {
$book = new Book();
$book->id = $identifiers['id'];
return $book;
}
public function supports(string $resourceClass, string $operationName = null, array $context = []): bool {
return true;
}
}
$dataProvider = new DataProvider();
```
--------------------------------
### Schema Generator Configuration (Enum Generation)
Source: https://api-platform.com/docs/v2.7/schema-generator/getting-started
A YAML configuration example for generating an enumeration class. The generator automatically detects subclasses of 'Enumeration' and creates a corresponding PHP Enum class.
```yaml
types:
OfferItemCondition: # The generator will automatically guess that OfferItemCondition is subclass of Enum
properties: {} # Remove all properties of the parent class
```
--------------------------------
### Declare API Resource with New Metadata Namespace (PHP)
Source: https://api-platform.com/docs/v2.7/core/upgrade-guide
Example demonstrating the updated `ApiPlatformMetadataApiResource` annotation in PHP for API Platform 2.7. It shows how to define resource types and operations using the new `operations` array with specific operation objects like `Get` and `Post`.
```php
openApiFactory = $openApiFactory;
}
public function __invoke(Request $request): DocumentationInterface
{
$context = ['base_url' => $request->getBaseUrl(), 'spec_version' => 3];
if ($request->query->getBoolean('api_gateway')) {
// Implementation logic
}
}
}
```
--------------------------------
### Setting Sunset Header for a Specific Operation
Source: https://api-platform.com/docs/v2.7/core/deprecations
This example shows how to apply the `Sunset` HTTP header to a single, specific operation (e.g., a GET request) for a resource.
```APIDOC
## Setting the `Sunset` HTTP Header for a Specific Operation
### Description
This configuration sets the `Sunset` HTTP header specifically for the GET operation on the `Parchment` resource, indicating that this particular operation will be removed on '01/01/2020'.
### Method
GET
### Endpoint
N/A (Applies to a specific operation within a resource)
### Parameters
#### Operation Attribute
- **sunset** (string) - Required - The date string compatible with `\DateTime` constructor, indicating when the operation will be removed.
- **deprecationReason** (string) - Optional - A reason for the deprecation.
### Request Example
```php
insert($problemConstraintViolationListNormalizer, -780);
$list->insert($objectNormalizer, -1000);
$encoders = [new JsonEncoder(), $jsonLdEncoder];
$serializer = new Serializer(iterator_to_array($list), $encoders);
```
--------------------------------
### Schema Generator Configuration (Model Scaffolding)
Source: https://api-platform.com/docs/v2.7/schema-generator/getting-started
A sample YAML configuration file for the Schema Generator to scaffold data models. It defines types like 'Thing', 'Person', and 'PostalAddress', specifying their properties and inheritance.
```yaml
# api/config/schema.yaml
# The list of types and properties we want to use
types:
# Parent class of Person
Thing:
properties:
name: ~
Person:
# Enable the generation of the class hierarchy (not enabled by default)
parent: ~
properties:
familyName: ~
givenName: ~
additionalName: ~
address: ~
PostalAddress:
properties:
# Force the type of the addressCountry property to text
addressCountry: { range: "Text" }
addressLocality: ~
addressRegion: ~
postOfficeBoxNumber: ~
postalCode: ~
streetAddress: ~
```
--------------------------------
### Load Data Fixtures
Source: https://api-platform.com/docs/v2.7/distribution/testing
Executes the console command to populate the database with the defined fixture datasets.
```bash
docker compose exec php \
bin/console hautelook:fixtures:load
```
--------------------------------
### Clear Cache for Symfony/API Platform (Bash)
Source: https://api-platform.com/docs/v2.7/admin/getting-started
This command clears the application cache for a Symfony project using Docker Compose. It's necessary after making changes to configuration files, such as CORS settings, to ensure they are applied.
```bash
docker compose exec php \
bin/console cache:clear --env=prod
```
--------------------------------
### Deprecate Operation in PHP
Source: https://api-platform.com/docs/v2.7/core/deprecations
Deprecates a specific operation (e.g., a GET request) on a resource using the `deprecationReason` attribute. This allows for finer-grained control over deprecation within a resource, guiding clients to use alternative operations.
```php
add('api_doc', new Route('/docs.{_format}', ['_controller' => $documentationAction, '_format' => null, '_api_respond' => true]));
$entryPointAction = new EntrypointAction($resourceNameCollectionFactory);
$routes->add('api_entrypoint', new Route('/{index}.{_format}', ['_controller' => $entryPointAction, '_format' => null, '_api_respond' => true, 'index' => 'index'], ['index' => 'index']));
$contextAction = new ContextAction($jsonLdContextBuilder, $resourceNameCollectionFactory, $resourceMetadataFactory);
$routes->add('api_jsonld_context', new Route('/contexts/{shortName}.{_format}', ['_controller' => $contextAction, '_format' => 'jsonld', '_api_respond' => true], ['shortName' => '.+']));
$controllerResolver = new ControllerResolver();
$argumentResolver = new ArgumentResolver();
$kernel = new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
```
--------------------------------
### Default API Resource Declaration (PHP)
Source: https://api-platform.com/docs/v2.7/core/upgrade-guide
Illustrates the default `#[ApiResource]` attribute in API Platform 2.7, which implicitly defines standard CRUD operations. This is equivalent to explicitly listing `Get`, `Put`, `Patch`, `Delete`, `GetCollection`, and `Post` operations.
```php
#[ApiResource]
```
--------------------------------
### Configure CORS for API Platform (YAML)
Source: https://api-platform.com/docs/v2.7/admin/getting-started
This YAML configuration snippet is for NelmioCorsBundle in a Symfony project. It sets up CORS headers for the '/api/' path, allowing specific origins, methods, headers, and exposing the 'Link' header. This is crucial for the admin interface to access the API.
```yaml
# config/packages/nelmio_cors.yaml
nelmio_cors:
paths:
'^/api/':
origin_regex: true
allow_origin: ['^http://localhost:[0-9]+'] # You probably want to change this regex to match your real domain
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
expose_headers: ['Link']
max_age: 3600
```
--------------------------------
### Start Production Services with Docker Compose
Source: https://api-platform.com/docs/v2.7/deployment/docker-compose
Deploys the application in production mode by setting necessary environment variables and running the production-specific Docker Compose configuration.
```bash
SERVER_NAME=your-domain-name.example.com \
APP_SECRET=ChangeMe \
POSTGRES_PASSWORD=ChangeMe \
CADDY_MERCURE_JWT_SECRET=ChangeMe \
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
```
--------------------------------
### Explicit CRUD Operations for API Resource (PHP)
Source: https://api-platform.com/docs/v2.7/core/upgrade-guide
Shows the explicit declaration of all default CRUD operations for an `ApiResource` in API Platform 2.7. This includes `Get`, `Put`, `Patch`, `Delete` for single items, and `GetCollection`, `Post` for collections, using the `operations` array.
```php
#[ApiResource(operations: [
new Get(),
new Put(),
new Patch(),
new Delete(),
new GetCollection(),
new Post(),
])]
```
--------------------------------
### Declare API Resource with Old Metadata Namespace (PHP)
Source: https://api-platform.com/docs/v2.7/core/upgrade-guide
Example showing the `ApiPlatformCoreAnnotationApiResource` annotation used in API Platform 2.6. This illustrates the older way of defining resources, including IRI, item operations, and specific operation configurations like `post_publication`.
```php
[
'method' => 'POST',
'path' => '/books/{id}/publication',
]
])
]
class Book
{
// ...
}
```
--------------------------------
### Execute GraphQL Queries
Source: https://api-platform.com/docs/v2.7/core/graphql
Example GraphQL queries demonstrating how to call custom operations defined in the API Platform resource configuration.
```graphql
{
retrievedQueryBook(id: "/books/56") { title }
notRetrievedQueryBook { title }
withDefaultArgsNotRetrievedQueryBook(id: "/books/56") { title }
withCustomArgsQueryBook(id: "/books/23", log: true, logDate: "2019-12-20") { title }
collectionQueryBooks { edges { node { title } } }
}
```
--------------------------------
### Define API Platform Resources in YAML and XML
Source: https://api-platform.com/docs/v2.7/core/getting-started
Demonstrates how to map entities to API resources using YAML and XML formats. These configurations allow for setting metadata like descriptions, types, and pagination settings for specific entities.
```yaml
resources:
App\Entity\Product: ~
App\Entity\Offer:
shortName: 'Offer'
description: 'An offer from my shop'
types: ['https://schema.org/Offer']
paginationItemsPerPage: 25
```
```xml
https://schema.org/Offer
```
--------------------------------
### Configure Providers and Processors with Doctrine
Source: https://api-platform.com/docs/v2.7/core/upgrade-guide
This PHP code snippet demonstrates how to configure Providers and Processors for different HTTP operations (GET, GETCollection, POST, PUT, DELETE) using Doctrine's state management classes. It specifies the processor and provider for each operation directly within the `#[ApiResource]` metadata.
```php
h(App),
}).$mount('#app');
```
--------------------------------
### Subresource Example: Retrieving Related Questions for an Answer
Source: https://api-platform.com/docs/v2.7/core/subresources
This example shows how to configure a subresource to retrieve a collection of 'relatedQuestions' associated with a specific 'Answer' entity.
```APIDOC
## GET /answers/{id}/related_questions.{_format}
### Description
Retrieves a collection of 'relatedQuestions' associated with a specific 'Answer' identified by its ID.
### Method
GET
### Endpoint
`/answers/{id}/related_questions.{_format}`
### Parameters
#### Path Parameters
- **id** (integer) - Required - The ID of the 'Answer' resource.
- **_format** (string) - Optional - The desired response format (e.g., json, xml).
### Request Example
(No request body for GET requests)
### Response
#### Success Response (200)
- An array of 'Question' objects representing the related questions.
#### Response Example
```json
[
{
"id": 101,
"content": "What is the meaning of life?"
},
{
"id": 102,
"content": "Is there intelligent life elsewhere in the universe?"
}
]
```
```
--------------------------------
### API Platform v2.7 Route Loading (PHP)
Source: https://api-platform.com/docs/v2.7/core/bootstrap
Demonstrates the process of loading API routes within API Platform v2.7. It iterates through discovered resource classes, retrieves their metadata, and adds routes for collection and item operations based on the configuration. Includes error handling for resources without a short name.
```php
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$identifiersExtractor = new IdentifiersExtractor($propertyNameCollectionFactory, $propertyMetadataFactory, $propertyAccessor);
$pathSegmentNameGenerator = new UnderscorePathSegmentNameGenerator();
$operationPathResolver = new OperationPathResolver($pathSegmentNameGenerator);
$subresourceOperationFactory = new SubresourceOperationFactory($resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, $pathSegmentNameGenerator);
class ApiLoader {
private $resourceNameCollectionFactory;
private $resourceMetadataFactory;
private $identifiersExtractor;
private $operationPathResolver;
public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, IdentifiersExtractorInterface $identifiersExtractor, OperationPathResolverInterface $operationPathResolver)
{
$this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->identifiersExtractor = $identifiersExtractor;
$this->operationPathResolver = $operationPathResolver;
}
public function load(): RouteCollection
{
$routeCollection = new RouteCollection();
foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$resourceShortName = $resourceMetadata->getShortName();
if (null === $resourceShortName) {
throw new InvalidResourceException(sprintf('Resource %s has no short name defined.', $resourceClass));
}
if (null !== $collectionOperations = $resourceMetadata->getCollectionOperations()) {
foreach ($collectionOperations as $operationName => $operation) {
$this->addRoute($routeCollection, $resourceClass, $operationName, $operation, $resourceMetadata, OperationType::COLLECTION);
}
}
if (null !== $itemOperations = $resourceMetadata->getItemOperations()) {
foreach ($itemOperations as $operationName => $operation) {
```
--------------------------------
### Start React Native Application
Source: https://api-platform.com/docs/v2.7/create-client/react-native
Starts the React Native development server using Expo CLI, allowing you to run the application on simulators or devices.
```bash
expo start
```