Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. Symfony: The Fast Track
  4. Ukrainian
  5. Створення API за допомогою API Platform

Створення API за допомогою API Platform

Ми завершили розробку веб-сайту гостьової книги. Тепер, щоб дозволити більш гнучко використовувати дані, як щодо розробки API? API може використовуватися мобільним застосунком, щоб відображати всі конференції, їх коментарі й, можливо, дозволить учасникам відправляти коментарі.

На цьому кроці ми реалізуємо API, що доступний лише для читання.

Встановлення API Platform

Можна створити API написавши деякий код, але якщо ми хочемо використовувати стандарти, нам краще використовувати рішення, яке вже бере на себе копітку роботу. Таке рішення, як API Platform:

1
$ symfony composer req api

Створення API для конференцій

Кілька атрибутів у класі Conference — це все, що нам потрібно для налаштування API:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
--- a/src/Entity/Conference.php
+++ b/src/Entity/Conference.php
@@ -2,35 +2,48 @@

 namespace App\Entity;

+use ApiPlatform\Core\Annotation\ApiResource;
 use App\Repository\ConferenceRepository;
 use Doctrine\Common\Collections\ArrayCollection;
 use Doctrine\Common\Collections\Collection;
 use Doctrine\ORM\Mapping as ORM;
 use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
+use Symfony\Component\Serializer\Annotation\Groups;
 use Symfony\Component\String\Slugger\SluggerInterface;

 #[ORM\Entity(repositoryClass: ConferenceRepository::class)]
 #[UniqueEntity('slug')]
+#[ApiResource(
+    collectionOperations: ['get' => ['normalization_context' => ['groups' => 'conference:list']]],
+    itemOperations: ['get' => ['normalization_context' => ['groups' => 'conference:item']]],
+    order: ['year' => 'DESC', 'city' => 'ASC'],
+    paginationEnabled: false,
+)]
 class Conference
 {
     #[ORM\Id]
     #[ORM\GeneratedValue]
     #[ORM\Column(type: 'integer')]
+    #[Groups(['conference:list', 'conference:item'])]
     private $id;

     #[ORM\Column(type: 'string', length: 255)]
+    #[Groups(['conference:list', 'conference:item'])]
     private $city;

     #[ORM\Column(type: 'string', length: 4)]
+    #[Groups(['conference:list', 'conference:item'])]
     private $year;

     #[ORM\Column(type: 'boolean')]
+    #[Groups(['conference:list', 'conference:item'])]
     private $isInternational;

     #[ORM\OneToMany(mappedBy: 'conference', targetEntity: Comment::class, orphanRemoval: true)]
     private $comments;

     #[ORM\Column(type: 'string', length: 255, unique: true)]
+    #[Groups(['conference:list', 'conference:item'])]
     private $slug;

     public function __construct()

Основний атрибут ApiResource налаштовує API для конференцій. Він обмежує можливі операції методу get і налаштовує різні речі: наприклад, які поля відображати та в якому порядку.

За замовчуванням основною точкою входу для API є /api, завдяки конфігурації з config/routes/api_platform.yaml, що була додана рецептом пакета.

Веб-інтерфейс дозволяє взаємодіяти з API:

/api

Використовуйте його, щоб перевірити різні можливості:

/api

Уявіть собі, скільки часу буде потрібно, щоб реалізувати все це з нуля!

Створення API для коментарів

Зробіть те саме для коментарів:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
--- a/src/Entity/Comment.php
+++ b/src/Entity/Comment.php
@@ -2,40 +2,58 @@

 namespace App\Entity;

+use ApiPlatform\Core\Annotation\ApiFilter;
+use ApiPlatform\Core\Annotation\ApiResource;
+use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
 use App\Repository\CommentRepository;
 use Doctrine\ORM\Mapping as ORM;
+use Symfony\Component\Serializer\Annotation\Groups;
 use Symfony\Component\Validator\Constraints as Assert;

 #[ORM\Entity(repositoryClass: CommentRepository::class)]
 #[ORM\HasLifecycleCallbacks]
+#[ApiResource(
+    collectionOperations: ['get' => ['normalization_context' => ['groups' => 'comment:list']]],
+    itemOperations: ['get' => ['normalization_context' => ['groups' => 'comment:item']]],
+    order: ['createdAt' => 'DESC'],
+    paginationEnabled: false,
+)]
+#[ApiFilter(SearchFilter::class, properties: ['conference' => 'exact'])]
 class Comment
 {
     #[ORM\Id]
     #[ORM\GeneratedValue]
     #[ORM\Column(type: 'integer')]
+    #[Groups(['comment:list', 'comment:item'])]
     private $id;

     #[ORM\Column(type: 'string', length: 255)]
     #[Assert\NotBlank]
+    #[Groups(['comment:list', 'comment:item'])]
     private $author;

     #[ORM\Column(type: 'text')]
     #[Assert\NotBlank]
+    #[Groups(['comment:list', 'comment:item'])]
     private $text;

     #[ORM\Column(type: 'string', length: 255)]
     #[Assert\NotBlank]
     #[Assert\Email]
+    #[Groups(['comment:list', 'comment:item'])]
     private $email;

     #[ORM\Column(type: 'datetime_immutable')]
+    #[Groups(['comment:list', 'comment:item'])]
     private $createdAt;

     #[ORM\ManyToOne(targetEntity: Conference::class, inversedBy: 'comments')]
     #[ORM\JoinColumn(nullable: false)]
+    #[Groups(['comment:list', 'comment:item'])]
     private $conference;

     #[ORM\Column(type: 'string', length: 255, nullable: true)]
+    #[Groups(['comment:list', 'comment:item'])]
     private $photoFilename;

     #[ORM\Column(type: 'string', length: 255, options: ["default" => "submitted"])]

Для налаштування класу використовуються ті самі атрибути.

Обмеження коментарів, що надаються API

За замовчуванням API Platform надає доступ до всіх записів з бази даних. Але для коментарів тільки опубліковані мають бути частиною API.

Якщо вам потрібно обмежити елементи, що повертаються API, створіть сервіс, який реалізує QueryCollectionExtensionInterface, щоб керувати запитом Doctrine, яка використовується для колекцій, та/або QueryItemExtensionInterface, щоб керувати елементами:

src/Api/FilterPublishedCommentQueryExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
namespace App\Api;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use App\Entity\Comment;
use Doctrine\ORM\QueryBuilder;

class FilterPublishedCommentQueryExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
{
    public function applyToCollection(QueryBuilder $qb, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
    {
        if (Comment::class === $resourceClass) {
            $qb->andWhere(sprintf("%s.state = 'published'", $qb->getRootAliases()[0]));
        }
    }

    public function applyToItem(QueryBuilder $qb, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = [])
    {
        if (Comment::class === $resourceClass) {
            $qb->andWhere(sprintf("%s.state = 'published'", $qb->getRootAliases()[0]));
        }
    }
}

Клас розширення запиту застосовує свою логіку тільки до ресурсу Comment і змінює конструктор запитів Doctrine, щоб враховувати коментарі тільки в стані published.

Налаштування CORS

За замовчуванням політика безпеки того ж походження сучасних HTTP-клієнтів робить виклик API з іншого домену забороненим. Бандл CORS, що встановлений як частина composer req api, відправляє заголовки спільного використання ресурсів з різних джерел на основі змінної середовища CORS_ALLOW_ORIGIN.

За замовчуванням його значення, що визначено у .env, дозволяє HTTP-запити від localhost і 127.0.0.1 на будь-який порт. Це саме те, що нам потрібно для наступного кроку, оскільки ми створимо ОЗ у якого буде свій власний веб-сервер, що буде викликати API.

Йдемо далі

  • Навчальний посібник SymfonyCasts: API Platform;
  • Щоб увімкнути підтримку GraphQL, виконайте команду composer require webonyx/graphql-php, а потім перейдіть за посиланням /api/graphql.
Previous page Сповіщення всілякими засобами
Next page Створення ОЗ
This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.
TOC
    Version

    Symfony 5.4 is backed by

    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Show your Symfony expertise

    Show your Symfony expertise

    Version:
    Locale:
    ebook

    This book is backed by:

    see all backers

    Symfony footer

    Avatar of botbotbot, a Symfony contributor

    Thanks botbotbot for being a Symfony contributor

    1 commit • 10 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • What is Symfony?
      • Symfony at a Glance
      • Symfony Components
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • Symfony Community
      • SymfonyConnect
      • Events & Meetups
      • Projects using Symfony
      • Contributors
      • Symfony Jobs
      • Backers
      • Code of Conduct
      • Downloads Stats
      • Support
    • Blog

      • All Blog Posts
      • A Week of Symfony
      • Case Studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Living on the edge
      • Releases
      • Security Advisories
      • Symfony Insight
      • Twig
      • SensioLabs Blog
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Powered by

    Follow Symfony