API Platform 2.5

API Platform 2.5: revamped Admin, new API testing tool, Next.js and Quasar app generators, PATCH and JSON Schema support, improved OpenAPI and GraphQL support

I’m very excited to announce the immediate availability of API Platform 2.5!

API Platform is a set of standalone server and client components for building and consuming REST (JSON-LD, Hydra, JSON:API…) and GraphQL APIs. The server components use PHP and Symfony while the client-side components (which support any Hydra-enabled web API, even the ones not built using API Platform) are written in JS. If you haven’t tried API Platform yet, it only takes a few minutes to create your first project!

API Platform 2.5 is the best version ever of the framework! Let’s discover its most interesting new features.

API Platform Admin 1.0: the power of React Admin and Material UI unleashed!

API Platform comes with a powerful component to create admin interfaces. It is built on top of React Admin and Material-UI.

Pass the URL of any Hydra-enabled API (including, of course, APIs built with API Platform itself) to the HydraAdmin component, and you instantly get a beautiful, fully-featured admin interface for resources exposed by the API including:

  • CRUD pages;
  • widgets based on the type of the properties;
  • filters;
  • sorting;
  • client-side validation…

The admin interface is dynamically built client-side, by parsing the Hydra metadata of the API. To do so, only a single LLOC is necessary:

import React from "react";
import { HydraAdmin } from "@api-platform/admin";

export default () => <HydraAdmin entrypoint="https://demo.api-platform.com"/>

And you get this (live demo):

demo-admin.api-platform.com

In previous versions, customizing the UI wasn’t straightforward nor idiomatic: you had to post-process the JS object containing the parsed API documentation.

Luckily, the Marmelab (creator of React Admin) and Les-Tilleuls.coop (creator of API Platform) teams got together several times during the summer to create a new version which dramatically improves the DX. Thus API Platform Admin 1.0 was born! While keeping the simplicity of previous versions, it now allows to leverage the power of JSX to customize every part of the UI using React Admin components, Material-UI components, or your custom React components:

import React from "react";
import {
  HydraAdmin,
  ResourceGuesser,
  CreateGuesser,
  InputGuesser
} from "@api-platform/admin";
import { ReferenceInput, AutocompleteInput } from "react-admin";

const ReviewsCreate = props => (
  <CreateGuesser {...props}>
    <InputGuesser source="author" />
    <ReferenceInput
      source="book"
      reference="books"
      label="Books"
      filterToQuery={searchText => ({ title: searchText })}
    >
      <AutocompleteInput optionText="title" />
    </ReferenceInput>

    <InputGuesser source="rating" />
    <InputGuesser source="body" />
  </CreateGuesser>
);

export default () => (
  <HydraAdmin entrypoint="https://demo.api-platform.com">
    <ResourceGuesser
      name="reviews"
      create={ReviewsCreate}
    />
  </HydraAdmin>
);

In the previous example, we add an autocomplete input for a relation by using the dedicated React Admin component while letting API Platform Admin guess which inputs to use for the other properties based on the API docs.

Check out the updated and improved documentation to learn more about these new customization capabilities!

This feature has been contributed by Morgan Auchede, Florian Ferbach, Gildas Garcia, Alexis Janvier, Jean-François Thuillier, François Zaninotto and myself.

Next.js and Quasar support in the Client Generator

API Platform also provides an app generator supporting React, Vue and React Native. And in version 2.5, it is also able to generate high quality Next.js and Quasar apps!

API Platform Client Generator is very similar to Symfony’s MakerBundle and to Rails’ scaffolding, but instead of generating server-side code, it generates a client-side app which uses the API to fetch and persist data. To do so, like the admin component, the generator uses the Hydra specification exposed by the API (built with API Platform or otherwise; support for OpenAPI and GraphQL is in progress).

Next.js is the most popular framework for React, with automatic Server-Side Rendering support, routing, code splitting, CSS-in-JS, static exporting… The Next.js generator, created by Grégory Copin, leverages the 0-config TypeScript support introduced in Next 9: all generated code is written in TS!

To generate a Next app from any API exposing a Hydra specification, run the following commands:

$ npm install next --save # Install next
$ npx @api-platform/client-generator https://demo.api-platform.com src/ --generator next # Scaffold the app

And you get high quality code you can customize to fit your needs:

List screenshot

Refer to the dedicated documentation to learn about all the capabilities of this generator.

Quasar is a framework built on top of Vue.js allowing to write SPAs with Server-Side Rendering support, mobile apps and Electron apps in one go. Its comes with a nice Material Design interface.

To use it, run the following commands:

$ npm install -g @quasar/cli
$ quasar create my-app
$ npx @api-platform/client-generator https://demo.api-platform.com src/ --generator quasar my-app/src # Scaffold the app

A big thanks to Paul Apostol for contributing this generator!

A brand new test client and dedicated API assertions

Currently, there is a lack of satisfactory solutions to write functional tests for web APIs built in PHP (API Platform and Symfony included):

  • Behat+Behatch+Mink is BDD-oriented (which is completely fine, but doesn’t fit with all projects/teams), is a bit complex to set up, has a high barrier to entry and is still not fully compatible with Symfony 4 (you need to rely on a dev version of Behat). It also lacks some utilities, for database testing for instance.
  • BrowserKit/WebTestCase is dedicated to webpage testing through web scraping (DOM Crawler, CSS selectors, simulation of browser actions such as clicking or reloading a page…). Its API doesn’t fit well with API testing. However, it benefits from the large ecosystem of PHPUnit, and gives access to numerous functional testing helpers provided by Symfony.
  • External solutions which don’t manipulate the Symfony Kernel (but are true HTTP clients) such as Postman or Blackfire Player require setting up a web server for the testing environment and don’t provide access to the service container (for instance, to test if the database has been updated, or if a mail has been sent).

It’s time to say hi to ApiTestCase, Test\Client and a bunch of new assertions dedicated to API testing (matching a JSON document or a subset of it, checking the status code and headers of HTTP responses, validating against a  JSON Schema…)! This new set of API testing utilities is built on top of Symfony’s KernelTestCase class, and the Test\Client implements the exact same interface as the brand new Symfony HttpClient component.

This new testing tool also plays very well with Alice (a test fixture generator having an official Symfony/API Platform recipe), which has also gained new powers in the process!

Let’s see how it looks:

namespace App\Tests;

use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;
use App\Entity\Book;
use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;

class BooksTest extends ApiTestCase
{
    // This trait provided by HautelookAliceBundle will take care of refreshing the database content to a known state before each test
    use RefreshDatabaseTrait;
    
    public function testCreateBook(): void
    {
        $response = static::createClient()->request('POST', '/books', ['json' => [
            'isbn' => '0099740915',
            'title' => 'The Handmaid\'s Tale',
            'description' => 'Brilliantly conceived and executed, this powerful evocation of twenty-first century America gives full rein to Margaret Atwood\'s devastating irony, wit and astute perception.',
            'author' => 'Margaret Atwood',
            'publicationDate' => '1985-07-31T00:00:00+00:00',
        ]]);

        $this->assertResponseStatusCodeSame(201);
        $this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
        $this->assertJsonContains([
            '@context' => '/contexts/Book',
            '@type' => 'Book',
            'isbn' => '0099740915',
            'title' => 'The Handmaid\'s Tale',
            'description' => 'Brilliantly conceived and executed, this powerful evocation of twenty-first century America gives full rein to Margaret Atwood\'s devastating irony, wit and astute perception.',
            'author' => 'Margaret Atwood',
            'publicationDate' => '1985-07-31T00:00:00+00:00',
            'reviews' => [],
        ]);
        $this->assertRegExp('~^/books/\d+$~', $response->toArray()['@id']);

        // This new assertions checks that the returned JSON document matches the JSON Schema generated by API Platform for this resource (also included in the OpenAPI file) 
        $this->assertMatchesResourceItemJsonSchema(Book::class);
    }

    public function testUpdateBook(): void
    {
        $client = static::createClient();
        // findIriBy allows to retrieve the IRI of an item by searching for some of its properties.
        // ISBN 9786644879585 has been generated by Alice when loading test fixtures.
        // Because Alice use a seeded pseudo-random number generator, we're sure that this ISBN will always be generated.
        $iri = static::findIriBy(Book::class, ['isbn' => '9781344037075']);

        $client->request('PUT', $iri, ['json' => [
            'title' => 'updated title',
        ]]);

        $this->assertResponseIsSuccessful();
        $this->assertJsonContains([
            '@id' => $iri,
            'isbn' => '9781344037075',
            'title' => 'updated title',
        ]);
    }

    public function testDeleteBook(): void
    {
        $client = static::createClient();
        $iri = static::findIriBy(Book::class, ['isbn' => '9781344037075']);

        $client->request('DELETE', $iri);

        $this->assertResponseStatusCodeSame(204);
        $this->assertNull(
            // Through the container, you can access all your services from the tests, including the ORM, the mailer, remote API clients...
            static::$container->get('doctrine')->getRepository(Book::class)->findOneBy(['isbn' => '9781344037075'])
        );
    }
}

Check out the full documentation, or the screencast which has been published on SymfonyCasts on this topic.

Improved GraphQL support

The GraphQL subsystem has been dramatically improved in version 2.5. Kudos to Alan Poulain who has done an awesome job maintaining and improving this part, and to Lukas Lücke and Mahmood Bazdar for their great contributions.

The main features of this new version are the customization of queries, mutations and types.

Whenever you need to add your own logic in your schema, you can now add custom properties in your resource’s annotations to do it. For instance to add a custom query:

/**
 * @ApiResource(graphql={
 *     "myShinyQuery"={
 *         "item_query"=MyQueryItemResolver::class,
 *         "args"={
 *             "id"={"type"="ID"},
 *             "isShiny"={"type"="Boolean!"}
 *         }
 *     }
 * })
 */

You only need to define the corresponding resolver and it’s done!

<?php

namespace App\Resolver;

use ApiPlatform\Core\GraphQl\Resolver\QueryItemResolverInterface;

final class MyQueryItemResolver implements QueryItemResolverInterface
{
    public function __invoke($item, array $context)
    {
        // Do what you want!

        return $item;
    }
}

Please refer to the documentation for customizing the mutations and the types.

The new version also comes with:

  • a better pagination mechanism (including backwards pagination)
  • a new “stage” mechanism allowing to easily customize the built-in resolvers, and an easier way to customize behaviors using decoration
  • support for GraphQL Playground, in addition to GraphiQL
  • a new command to export the GraphQL schema automatically generated by API Platform
  • support for file uploads
  • support for name converters
  • improved overall performance

All these new features have been documented, check it out!

JSON Merge Patch Support

Until now, API Platform had only supported using the PUT HTTP method for replacing a resource. Supporting proper partial updates through the PATCH method is known to be hard.

In version 2.5, a large refactoring work has been done to properly support the PATCH method, and support for JSON Merge Patch (RFC 7386) has been added (to do so, we’ve contributed the required low-level brick to the Symfony Serializer component). The new infrastructure is designed to support other PATCH formats as well. In the future, other formats such as JSON Patch (RFC 6902) may be added.
The JSON:API PATCH format, which was already supported, is of course still working.

Read the dedicated documentation entry to learn more about API Platform’s PATCH support (including how to enable it for existing projects).

JSON Schema Support

JSON Schema is a popular vocabulary to describe the shape of JSON documents. A variant of JSON Schema is also used in OpenAPI specifications. As of API Platform 2.5, JSON Schema is a first-class citizen. A new infrastructure has been created to be able to generate JSON Schemas for any resource, represented in any format (including JSON-LD). A command has also been added to export these schemas:

$ bin/console api:json-schema:generate 'App\Entity\Review'

The generated schema can be used with libraries such as react-json-schema-form to build forms for the documented resources, or to be used for validation.

To generate JSON Schemas programmatically, use the new api_platform.json_schema.schema_factory service.

Improved OpenAPI support

Thanks to the improvements made in the OpenAPI v3 specification, and to the new JSON Schema infrastructure in API Platform, the generated OpenAPI documentation is now better. It generates a specific JSON Schema per supported format:

JSON-LD specific keys such as @id and @context are now documented.

Grégoire Hebert added the ability to configure the versions of OpenAPI to support, while also  allowing to specify the default version being used:

api_platform:
    swagger:
        versions: [3, 2] # OpenAPI v3 is now the default

Frédéric Barthelet and Ryan Weaver improved the OpenAPI documentation of the built-in order and property filters. Thank you!

Screencasts and improved docs

We are very proud to announce an official partnership between API Platform and SymfonyCasts! SymfonyCasts has published more than 7 hours of high quality and funny video tutorials on API Platform (and counting!). The screencasts are now available directly from the main menu of the website, and referenced in the appropriate documentation entries.

Also, for version 2.5, API Platform’s docs have been dramatically improved. All new features presented in this post (and more) are now documented; many parts of the docs have been fixed, improved and modernized; sections have been reordered to provide a better learning experience; and a new “extending API Platform” entry has been added to centralize how to hook your custom logic in a way which is compatible with both the REST and GraphQL subsystems. But there is still a lot to do, and your help is very welcome!

Community milestones and Hacktoberfest

The main strength of API Platform is its vibrant and diverse community! Recently, the project reached great milestones thanks to the many contributors, evangelists and users improving and promoting the framework: the Slack channel reached 2 000 users a few days ago; the core package of the framework has been downloaded more than 2 000 000 times; and workshops, meetups and talks about the project are being organized all over the world (next big events with API Platform talks: Forum PHP Paris and SymfonyCon Amsterdam)!

The framework is close to reaching 5 000 stars on GitHub! It will be the next big milestone, and we’ll organize a big party to celebrate! If you have not starred API Platform yet, please do! It will help us reach a wider audience. If you love the project, tell your friends about it!

Speaking about community, free software and contribution, Hacktoberfest is about to begin! Hacktoberfest is an event helping free software projects by encouraging contributions (code but also docs and marketing materials). As thanks for your contribution, Digital Ocean offers a limited-edition t-shirt, and nice stickers. This year, Les-Tilleuls.coop will also send you some surprise gifts if you contribute at least 3 Pull Requests on the API Platform repositories. Thanks Les-Tilleuls!

Hacktoberfest is a very good opportunity to start contributing to free software, and to API Platform in particular. To help you get started, we’ve marked some code and docs issues with a specific “Hacktoberfest” label:

If you need help working on this, don’t hesitate to ask us directly on GitHub, or in the API Platform Slack channel!

https://lh3.googleusercontent.com/-6RjHzvBuxFo/XZH8jV3YDtI/AAAAAAAADWE/kMKfpexyNWMGC3JMgv0Gp4XfDZxghfe-ACK8BGAsYHg/s0/Image%2Bfrom%2BiOS%2B%252812%2529.jpg

Upcoming conferences: AFUP Day, Web2Day, API Platform Meetup and more!

During the spring I’ll speak at several tech events about my projects Mercure (Go), API Platform (PHP, server-side and JS, client-side) and Symfony Panther (PHP/WebDriver):

AFUP Day, May 17th in Lille

Discover Symfony Panther, a brand new end-to-end testing tool using real web browsers for Symfony and PHP.

API Platform pre-Web2day meetup, June 3th in Nantes

Topic to be announced!

Web2Day, May 6th in Nantes

Mercure: UIs always synchronized with data in database

My company Les-Tilleuls.coop will have a booth during every of these events. Come, and let’s have a chat!
Also, I’ll announce my participation to some more events soon, stay tuned!

Symfony and API Platform get “push” and real-time capabilities (Mercure protocol)

Mercure.rocks is a brand new protocol allowing to push data updates to web browsers and other HTTP clients in a convenient, fast, reliable and battery-efficient way. It is especially useful to publish real-time updates of resources served through web APIs, to reactive web and mobile apps.

Both Symfony and API Platform now have an official support for this protocol!

From the ground, Mercure has been designed to work with technologies not able to maintain persistent connections. It’s especially relevant in serverless environments, but is also convenient when using PHP or FastCGI scripts.

Mercure is basically a higher-level replacement for WebSocket. Unlike WebSocket, it is compatible with HTTP/2 and HTTP/3.
It has been designed with hypermedia APIs in mind, is auto-discoverable through the Web Linking RFC and is also compatible with GraphQL.
It natively supports authorization, reconnection in case of network issue (with refetching of missed events), subscribing to several topics, topics patterns (using templated URIs)…

Because it is built on top of Server-sent Events and plain old HTTP requests, it is already compatible with all modern browsers, and requires 0 client-side dependencies.

The protocol is open (available as an Internet Draft), and a reference open source implementation of the server written in Go is available.—

Upcoming conferences and workshops

I’ll speak at several conferences until the end of 2018.

The topics will be varied: Panther, modern JavaScript, HTTP/2 and a brand new project to be announced (teasing: it’s written in Go, and it will be very helpful for serverless architectures!).

See you at:

I’ll also be available to chat, and I’ll carry a lot of API Platform goodies. Don’t hesitate to get in touch!

Introducing Symfony Panther: a Browser Testing and Web Scraping Library for PHP

Today, an introduction blog post to Panther was published on the Symfony blog! Panther is a new browser testing and web scraping library I contributed to the Symfony project,
In the blog post, I showcase how to use Symfony, API Platform and VueJS together to create a small but modern app, and how to test it on Panther:

Mastering the Symfony Serializer (PHP Tour slides)

The Symfony Serializer Component exists since the very beginning of Symfony 2. Years after years, it gained a lot of new features useful to transform various data formats to PHP structures and the opposite. It is also a foundation block of API Platform and a first-class citizen in FOSRest.

Let’s dive into this component. We will cover the basic concepts behind the serialization process: normalization, denormalization, encoding and decoding.

Then we will discover all the little known features of the component: JSON, XML and CSV support, file handling with “data:” URIs, serialization groups, attributes names conversion, trees support, updating existing objects, dealing with circular references.

Finally we will learn how to create custom normalizers and encoders; and how to modify the behavior of the builtin ones using composition.

Be paid to improve API Platform during the Rails Girls Summer of Code

(french translation below)

API Platform (the API-driven Open Source framework I created) has been selected for the Rails Girls Summer of Code program!

The goal of the RCSOC is to improve the diversity in Open Source development. It allows groups of 2 women students to work full-time on a FOSS project (such as API Platform) during the summer. Students are paid and mentored.

Rails Girls Summer of Code is a global fellowship program for women and non-binary coders. Students receive a three-month scholarship to work on existing Open Source projects and expand their skill set.

Our worker cooperative, Les-Tilleuls.coop, will also support the program by providing money, coaches (including me) and desktops (in Lille, France):

In our company, we attempt as much as possible to support associations engaged in the fight against social inequalities, or involved in a better access to culture and respect of the environment. Since our foundation in 2011, we have always upheld diversity in Open Source. Thus, it’s no surprise that we support Rails Girls’s Summer of Code program.

If you’re interested in working 3 months with us to improve cutting-edge Open Source projects, don’t by shy, apply!


API Platform, le framework API-driven que nous développons, compte parmi les projets sélectionnés pour le Rails Girls Summer of Code de cette année !

Ce programme vise à favoriser la diversité dans le mode du logiciel libre. Il permet à des groupes de 2 étudiantes d’être payées durant l’été pour travailler (en binôme) sur des projets Open Source.

Notre SCOP Les-Tilleuls.coop participe également au programme en tant que sponsor, et va fournir des bureaux (à Euratechnologies, Lille) et des “coachs” afin d’accompagner les participantes :

Chez Les-Tilleuls.coop, nous tentons autant que possible d’accompagner des associations ou des entités engagées dans la lutte contre les inégalités sociales, l’accès à la culture, la formation, ou encore le respect de l’environnement.  Notre coopérative s’implique aussi dans une meilleure diversité dans le numérique et c’est donc avec une certaine évidence que nous apportons notre soutien au programme “Summer of Code 2018” organisé par l’association Rails Girls (RGSoC).

Si vous êtes intéressées pour travailler 3 mois sur des projets Open Source innovants, ne soyez pas timides, postulez !

API Platform 2.2: GraphQL, JSON API, React admin and PWA, Kubernetes instant deployment and many more new features


I’m glad to announce the immediate availability of API Platform 2.2 beta 1. This is a huge release that comes with a lot of exciting features including (but not limited too):

  • GraphQL and JSON API support
  • Symfony 4 / Flex integration
  • API Platform Admin integration (built with ReactJS and Admin On Rest)
  • ReactJS and Vue.js Progressive Web App generators integration (a React Native app generator is also available)
  • Revamped Docker containers for both PHP and JavaScript components, including out of the box support for HTTP2, HTTPS and a built-in invalidation-based cache mechanism using Varnish
  • The ability to deploy in seconds in any Kubernetes cluster
  • A new, super-easy, way to register filters through annotations
  • And literally dozens of developer experience, performance and quality improvements

V2.2 will definitely be the best version of API Platform, and is probably the most advanced “full-stack” solution to create API-driven projects. The paradigm shift introduced by this new version has been detailed in my talk during the SymfonyCon 2017.

It took 6 months and 483 commits from more than 60 contributors to craft this version. The documentation has also been dramatically improved, even if some work is still to do (upgrading the getting started guide and migrating all articles to the new Flex directory structure, finish to document some new features).

Thank you very much to all contributors of the project! You rock!

Let’s see more in depth all of these new features:

The New Distribution

The easiest way to get started with API Platform has always been to use the provided Docker setup. In version 2.2, the Docker configuration has been totally redesigned to fit with the new features provided by Symfony Flex and to integrate our JavaScript components.

To get started:

You get:

– An API skeleton following the Flex directory structure. Just add classes representing your public data model (see the example below) to get a working hypermedia and/or GraphQL web API.

The API is available in HTTP/2 and HTTPS thanks to the provided development proxy. It also automatically benefits from the API Platform’s built-in cache mechanism (the Varnish container is also provided). CORS headers are automatically configured. As you can see, the nice documentation is – of course – still available if you open the entrypoint in a browser.

– A ReactJS Progressive Web App skeleton with a fancy welcome page designed by Laury Sorriaux:

Execute docker-compose exec client generate-api-platform-client to bootstrap a nice and fully-featured Progressive Web App (that can even work offline) using React, Redux and Bootstrap 4 and respecting accessibility recommendations.

To generate the PWA, the tool parses the API hypermedia description automatically generated in the Hydra format by the API component. This generator can work with any server exposing a Hydra documentation (done with API Platform or not).

The tool also has Vue.js, React Native and TypeScript skeletons thanks to the great contributions of Alain Hippolyte, Piotr Synowiec and Antoine Bluchet.

Read the full documentation of the API Platform Client Generator.

– Last but not least, a dynamically generated admin for the API is also automatically available:

Like the client generator, the API Platform Admin component also leverages the Hydra documentation to automatically guess the structure of the data exposed by the API.

Because it is built on top of React and Admin On Rest (aka React Admin), the UI is fully customizable.

Morgan Auchedé is the new maintainer of this component, and has greatly improved it since its initial release.

– In this version of API Platform, the MySQL container has been replaced by a Postgres one.

Instant Kubernetes Deployment

Kubernetes has become the most popular way to deploy, run and manage containers in production. Both Google Cloud Platform, Microsoft Azure and Amazon Web Services provide managed Kubernetes environment.

API Platform 2.2 contains a built-in Helm (the k8s package manager) chart to deploy with ease:

helm upgrade --install ./api/helm/api \
    --set php.repository=gcr.io/test-api-platform/php \
    --set nginx.repository=gcr.io/test-api-platform/nginx \
    --set secret=MyAppSecretKey \
    --set postgresql.postgresPassword=MyPgPassword \
    --set postgresql.persistence.enabled=true \
    --set corsAllowUrl='^https?://[a-z\]*\.mywebsite.com$'

Your app is now up and running in a managed cluster! Read the related documentation to learn more about the Kubernetes support.

GraphQL Support

GraphQL is a query language for APIs designed by Facebook that is becoming a very popular alternative to the REST pattern. GraphQL support has been the most wanted feature for a while, it is now fully implemented!

The new GraphQL subsystem of API Platform now supports:

To enable the GraphQL support, you just have to install the GraphQL PHP library:

docker-compose exec php composer req webonyx/graphql-php

Then, create an API Platform entity, as usual:

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * An organization.
 *
 * @ApiResource
 * @ORM\Entity
 */
class Organization
{
    /**
     * @ORM\Id
     * @ORM\Column(type="guid")
     * @Assert\NotBlank
     */
    public $id;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank
     */
    public $name;
}

Yes, both GraphQL and REST formats can be used for the same entity! Thanks to API Platform’s hypermedia support, you can even run a GraphQL request, then apply REST operations to the retrieved resources using their IRIs! The best of both worlds.

Your GraphQL API is ready! Browse https://localhost:8443/graphql :

There is a lot to say about the GraphQL support, how to use it in collaboration with REST and how to apply fine-grained configurations. I’ll write a follow-up post dedicated to it, stay tuned!

The GraphQL support is an important team work of Raoul Clais, Alan Poulain, Baptiste Meyer and myself.

JSON API Support

JSON API is a rising, well designed, hypermedia format. Unlike JSON-LD (the default format exposed by API Platform), it’s not a web standard; and it has less features but it is also simpler to learn and understand.

With API Platform 2.2, you don’t have to choose, you can have both! And even more because API Platform supports out of the box JSON-LD/Hydra, HAL, JSON API, YAML, XML, raw JSON and as we’ve seen just before, GraphQL.

To enable JSON API, add the following config:

# config/packages/api_platform.yaml
api_platform:
    # ...
    formats:
        # ...
        jsonapi: ['application/vnd.api+json']
    error_formats:
        # ...
        jsonapi: ['application/vnd.api+json']

Easy enough?

The JSON API support has been contributed by Hamza Amrouche, Hector Hurtarte and Baptiste Meyer.

Declaring API Filters Using Annotations

The API Platform filtering system is very powerful. It contains a lot of built-in filters and can easily be extended. However, until now, it wasn’t really easy to configure: it was requiring to declare services manually.

Because Symfony Flex is all about service autowiring and autoconfiguration, simplifying the filters configuration was a top priority task.

Hopefully, Antoine Bluchet created a nice way to do it using annotations:

<?php
// api/src/Entity/Organization.php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;

/**
 * ...
 */
class Organization
{
    // ...

    /**
     * @ApiFilter(SearchFilter::class)
     * ...
     */
    public $name;
}

Nothing more! You can now filter the collection of organizations by the name  property, both with REST and GraphQL!

In addition to these main features, a lot of other configuration options and various improvements have been introduced. Read the full changelogs for more information:

Help Us: Test, Star, Spread the Word!

If you have some existing API Platform projects, or if you want to give a try to the framework, please test this new version and report any problem on our GitHub issue tracker!

If you like API Platform, please tell the world and give us a star on GitHub.

Since API Platform 2.2, the Symfony Thanks command is also shipped with API Platform. Thanks to this tool, you can send a star to all the PHP libraries you use in your project (including API Platform) by simply running: docker-compose exec php composer thanks

If you want to learn API Platform, come to one of the workshops organized during these upcoming tech conferences:

HTTP/2, PHP and Symfony: a brief history of the protocol powering the web, and how to use it

Here are the slides I presented yesterday during the Paris Symfony Meetup.

On the menu: a brief history of HTTP, how to use it with PHP (server and client-side) and how to push with Symfony 4.

Learn more about Symfony’s HTTP/2 support in my in-depth presentation of the WebLink Component.

Symfony 4 Run-through (Forum PHP 2017)

Symfony is a framework broadly recognized for its quality, reliability and ability to drive large enterprise projects. But for the last few years, Symfony has also gained many features to develop faster, and to refactor more easily. Symfony 4 offers major improvements in this area that will deeply change the way we build applications.

Let’s talk about:

  • Symfony 4 main concepts and new features: micro-framework by default, 12-factor app, new components …
  • Flex, the new and powerful Symfony installer that can also automatically install and configure libraries and bundles
  • Symfony 4’s new simplified (and “bundle-less”) directory structure
  • The autowiring (now enabled by default), which allows the automatic injection of dependencies without having to write any configuration (no more YAML and XML)
  • The revamped controllers mechanism
  • Webpack Encore, the first Symfony component ever written in JavaScript, designed to easily integrate JavaScript and CSS tools in a PHP project
  • The official integrations of the Doctrine (ORM), API Platform (API) and EasyAdmin libraries (admin generator)
  • How to easily use Symfony 4 with Docker from dev to cloud deployment with a dedicated skeleton

You’ll learn how to leverage Symfony for large projects, prototypes, small applications and even your “weekend projects”, and how to migrate from smallest to the largest.

Recordings: