Step 26: Exposing an API with API Platform

Exposing an API with API Platform

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

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:

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

patch_file

The main 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.

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!

Do the same for comments:

patch_file

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 to control items:

src/Api/FilterPublishedCommentQueryExtension.php

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.

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 , 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.

  • ;
  • To enable the GraphQL support, run composer require webonyx/graphql-php, then browse to /api/graphql.

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