DEV Community

Aymeric Ratinaud
Aymeric Ratinaud

Posted on

Api-platform3 Boilerplate

I made a boilerplate available at this address which includes

  • symfony
  • api-platform
  • doctrine (of course)
  • fixtures and factory
  • codeception for functionnals tests

There is one entity Todo

<?php

namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use App\Repository\TodoRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: TodoRepository::class)]
#[ApiResource]
class Todo
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(type: Types::TEXT)]
    private ?string $description = null;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): static
    {
        $this->description = $description;

        return $this;
    }
}
Enter fullscreen mode Exit fullscreen mode

How tests the GET of the collection :

<?php


namespace App\tests\Api\todos;

use App\Factory\TodoFactory;
use App\Tests\Support\ApiTester;
use App\Tests\Support\Step\Api\Anonymous;

class getTodosCest
{
    public function _before(ApiTester $I)
    {
    }

    /**
     * @param Anonymous $I
     * @return void
     */
    public function tryToGetAllTodosAsAnonymous(Anonymous $I)
    {
        TodoFactory::createMany(30);

        $I->am('an anonymous user');
        $I->wantTo('list all todos');

        $I->haveHttpHeader("accept", "application/ld+json");
        $I->haveHttpHeader("Content-Type", "application/json");
        $I->sendGet('todos');

        $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
        $I->seeResponseIsJson();
        $I->seeResponseContainsJson([
            "@context" => "/api/contexts/Todo",
            "@type" => "hydra:Collection",
            "hydra:totalItems" => 30
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)