API Platform is a framework for API-first projects, built on top of Symfony components. Let's see how to create a minimal and lightweight starter project in just 5 minutes!
The only requirements are Docker Desktop, Visual Studio Code with the Dev Containers extension installed.
Setup
Download Symfony Sail (disclaimer, I'm the author π) which provides a ready-to-go developement environment for Symfony.
- Extract the zip in a directory
api-platform-playground
- Create an empty
.env.local
in that folder - Start Visual Studio Code, type F1 and choose Dev Containers: Reopen in Container
From now on, every command must be run inside Visual Studio Code built-in terminal, that is inside the container itself.
Let's download and install Symfony skeleton:
curl -O https://raw.githubusercontent.com/symfony/skeleton/6.2/composer.json
composer install
We need to add two required libraries in order to be able to navigate API Platform documentation:
composer require symfony/asset symfony/twig-pack
And finally the API Platform package:
composer require api-platform/core
Your API documentation is available at http://localhost/api/docs πππ
Your first resource
Time to add the first resource! We want to validate the input data and persist our resource. And being lazy, we take the advantage of MakerBundle also:
Do not execute the Docker recipe as we already have Docker configuration!
composer require symfony/validator symfony/orm-pack symfony/maker-bundle
Wait a moment, what about the database? Thanks to Symfony Sail, we already have a running database instance as db:3306
. Let's set the DATABASE_URL
in the .env.local
file:
DATABASE_URL="mysql://root:@db:3306/db_name?serverVersion=10.11.2-MariaDB&charset=utf8mb4"
Now we can finally generate our first resource named BlogPost
:
php bin/console make:entity BlogPost --api-resource
Using the wizard, add a required title
property of 64
character length, then modify App\Entity\BlogPost
as follows:
<?php
namespace App\Entity;
// ...
use Symfony\Component\Validator\Constraints as Assert;
// ...
class BlogPost
{
// ...
// ...
#[Assert\NotBlank]
#[Assert\Length(max: 64)]
private ?string $title = null;
}
Almost done! Generate a migration and execute it:
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate -n
Finish! π
Test a simple POST request using the API Platform page at http://localhost/api/docs, with a simple payload like { title: "My first blog post!" }
.
Bonus: static analysis with PHPStan and formatting upon saving using PHP_CodeSniffer? π€
Easy:
Do install the recipes of these libraries.
composer require --dev phpstan/phpstan squizlabs/php_codesniffer
Top comments (0)