Step 26: Exposing an API with API Platform

Exposing an API with API Platform

We have finished the implementation of the Guestbook website. To allow more usage of the data, what about exposing an API now? An API could be used by a mobile application to display all conferences, their comments, and maybe let attendees submit comments.

In this step, we are going to implement a read-only API.

Installing API Platform

Exposing an API by writing some code is possible, but if we want to use standards, we’d better use a solution that already takes care of the heavy lifting. A solution like API Platform:

  1. $ symfony composer req api

Exposing an API for Conferences

A few annotations on the Conference class is all we need to configure the API:

patch_file

  1. --- a/src/Entity/Conference.php
  2. +++ b/src/Entity/Conference.php
  3. @@ -2,16 +2,25 @@
  4. namespace App\Entity;
  5. +use ApiPlatform\Core\Annotation\ApiResource;
  6. use App\Repository\ConferenceRepository;
  7. use Doctrine\Common\Collections\ArrayCollection;
  8. use Doctrine\Common\Collections\Collection;
  9. use Doctrine\ORM\Mapping as ORM;
  10. use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
  11. +use Symfony\Component\Serializer\Annotation\Groups;
  12. use Symfony\Component\String\Slugger\SluggerInterface;
  13. /**
  14. * @ORM\Entity(repositoryClass=ConferenceRepository::class)
  15. * @UniqueEntity("slug")
  16. + *
  17. + * @ApiResource(
  18. + * collectionOperations={"get"={"normalization_context"={"groups"="conference:list"}}},
  19. + * itemOperations={"get"={"normalization_context"={"groups"="conference:item"}}},
  20. + * order={"year"="DESC", "city"="ASC"},
  21. + * paginationEnabled=false
  22. + * )
  23. */
  24. class Conference
  25. {
  26. @@ -20,21 +29,25 @@ class Conference
  27. * @ORM\GeneratedValue
  28. * @ORM\Column(type="integer")
  29. */
  30. + #[Groups(['conference:list', 'conference:item'])]
  31. private $id;
  32. /**
  33. * @ORM\Column(type="string", length=255)
  34. */
  35. + #[Groups(['conference:list', 'conference:item'])]
  36. private $city;
  37. /**
  38. * @ORM\Column(type="string", length=4)
  39. */
  40. + #[Groups(['conference:list', 'conference:item'])]
  41. private $year;
  42. /**
  43. * @ORM\Column(type="boolean")
  44. */
  45. + #[Groups(['conference:list', 'conference:item'])]
  46. private $isInternational;
  47. /**
  48. @@ -45,6 +58,7 @@ class Conference
  49. /**
  50. * @ORM\Column(type="string", length=255, unique=true)
  51. */
  52. + #[Groups(['conference:list', 'conference:item'])]
  53. private $slug;
  54. public function __construct()

The main @ApiResource annotation configures the API for conferences. It restricts possible operations to get and configures various things: like which fields to display and how to order the conferences.

By default, the main entry point for the API is /api thanks to configuration from config/routes/api_platform.yaml that was added by the package’s recipe.

A web interface allows you to interact with the API:

Step 26: Exposing an API with API Platform - 图1

Use it to test the various possibilities:

Step 26: Exposing an API with API Platform - 图2

Imagine the time it would take to implement all of this from scratch!

Exposing an API for Comments

Do the same for comments:

patch_file

  1. --- a/src/Entity/Comment.php
  2. +++ b/src/Entity/Comment.php
  3. @@ -2,13 +2,26 @@
  4. namespace App\Entity;
  5. +use ApiPlatform\Core\Annotation\ApiFilter;
  6. +use ApiPlatform\Core\Annotation\ApiResource;
  7. +use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
  8. use App\Repository\CommentRepository;
  9. use Doctrine\ORM\Mapping as ORM;
  10. +use Symfony\Component\Serializer\Annotation\Groups;
  11. use Symfony\Component\Validator\Constraints as Assert;
  12. /**
  13. * @ORM\Entity(repositoryClass=CommentRepository::class)
  14. * @ORM\HasLifecycleCallbacks()
  15. + *
  16. + * @ApiResource(
  17. + * collectionOperations={"get"={"normalization_context"={"groups"="comment:list"}}},
  18. + * itemOperations={"get"={"normalization_context"={"groups"="comment:item"}}},
  19. + * order={"createdAt"="DESC"},
  20. + * paginationEnabled=false
  21. + * )
  22. + *
  23. + * @ApiFilter(SearchFilter::class, properties={"conference": "exact"})
  24. */
  25. class Comment
  26. {
  27. @@ -17,18 +30,21 @@ class Comment
  28. * @ORM\GeneratedValue
  29. * @ORM\Column(type="integer")
  30. */
  31. + #[Groups(['comment:list', 'comment:item'])]
  32. private $id;
  33. /**
  34. * @ORM\Column(type="string", length=255)
  35. */
  36. #[Assert\NotBlank]
  37. + #[Groups(['comment:list', 'comment:item'])]
  38. private $author;
  39. /**
  40. * @ORM\Column(type="text")
  41. */
  42. #[Assert\NotBlank]
  43. + #[Groups(['comment:list', 'comment:item'])]
  44. private $text;
  45. /**
  46. @@ -36,22 +52,26 @@ class Comment
  47. */
  48. #[Assert\NotBlank]
  49. #[Assert\Email]
  50. + #[Groups(['comment:list', 'comment:item'])]
  51. private $email;
  52. /**
  53. * @ORM\Column(type="datetime")
  54. */
  55. + #[Groups(['comment:list', 'comment:item'])]
  56. private $createdAt;
  57. /**
  58. * @ORM\ManyToOne(targetEntity=Conference::class, inversedBy="comments")
  59. * @ORM\JoinColumn(nullable=false)
  60. */
  61. + #[Groups(['comment:list', 'comment:item'])]
  62. private $conference;
  63. /**
  64. * @ORM\Column(type="string", length=255, nullable=true)
  65. */
  66. + #[Groups(['comment:list', 'comment:item'])]
  67. private $photoFilename;
  68. /**

The same kind of annotations are used to configure the class.

Restricting Comments exposed by the API

By default, API Platform exposes all entries from the database. But for comments, only the published ones should be part of the API.

When you need to restrict the items returned by the API, create a service that implements QueryCollectionExtensionInterface to control the Doctrine query used for collections and/or QueryItemExtensionInterface to control items:

src/Api/FilterPublishedCommentQueryExtension.php

  1. namespace App\Api;
  2. use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
  3. use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryItemExtensionInterface;
  4. use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
  5. use App\Entity\Comment;
  6. use Doctrine\ORM\QueryBuilder;
  7. class FilterPublishedCommentQueryExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
  8. {
  9. public function applyToCollection(QueryBuilder $qb, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
  10. {
  11. if (Comment::class === $resourceClass) {
  12. $qb->andWhere(sprintf("%s.state = 'published'", $qb->getRootAliases()[0]));
  13. }
  14. }
  15. public function applyToItem(QueryBuilder $qb, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = [])
  16. {
  17. if (Comment::class === $resourceClass) {
  18. $qb->andWhere(sprintf("%s.state = 'published'", $qb->getRootAliases()[0]));
  19. }
  20. }
  21. }

The query extension class applies its logic only for the Comment resource and modify the Doctrine query builder to only consider comments in the published state.

Configuring CORS

By default, the same-origin security policy of modern HTTP clients make calling the API from another domain forbidden. The CORS bundle, installed as part of composer req api, sends Cross-Origin Resource Sharing headers based on the CORS_ALLOW_ORIGIN environment variable.

By default, its value, defined in .env, allows HTTP requests from localhost and 127.0.0.1 on any port. That’s exactly what we need as for the next step as we will create an SPA that will have its own web server that will call the API.

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.