API Platform 2.1 Feature Walkthrough: Create Blazing Fast Hypermedia APIs, Generate JS Apps

The new UI of API Platform 2.1

API Platform is a framework designed to make the creation of API-based information systems easier. It provides server-side tooling to create modern hypermedia and Linked Data APIs in just a few minutes. This new version introduces client-side tools to bootstrap Single-Page Applications using ReactJS by consuming the autogenerated documentation of the API.

Six months after the release of API Platform 2, I’m very excited to announce the immediate availability of the first beta of API Platform 2.1!

The changelog is huge, more than 200 commits by dozens of developers have been merged. I think we can say that this release will be great!

Let’s review the most interesting new features. If you just want to try it, the demo has been upgraded to use this new version and you can download it on GitHub.

A ReactJS-based Admin System

API Platform automatically exposes API documentations respecting the Hydra (W3C) and Swagger/Open API open standards. We created a dynamic administration system built on top of the awesome Admin On Rest library that takes advantage of the Hydra format.

Just with this line of code <HydraAdmin entrypoint="https://demo.api-platform.com"/>, you will get the following result:

Replace https://demo.api-platform.com by the URL of any API documented with Hydra and you will get a beautiful material design admin for it with:

  • list, create, show, edit screens as well as a delete button
  • suitable inputs and fields according to the API doc (e.g. number HTML input for numbers, checkbox for booleans, selectbox for relationships…)
  • suitable inputs and fields according to Schema.org types if available (e.g. email field for http://schema.org/email)
  • relationships
  • pagination
  • client-side validation for mandatory fields
  • server-side errors displaying (e.g. advanced validation)

It means that any API Platform API can now have an admin for free! The admin is fully customizable, a follow up post will come.

A React/Redux Webapp Generator

The admin is dynamic, no code generation happens. But sometimes it’s interesting to be able to generate some code to bootstrap a project. It’s exactly what the new api-platform-generate-crud tool does. It parses the Hydra documentation and generates a basic ReactJS webapp with the following features:

  • generation of high-quality ES6 components and files built with React, Redux, React Router and Redux Form including:
    • a list view
    • a show view
    • a creation form
    • an edition form
    • a deletion button
  • generation of the suitable HTML5 input type (number, date…) according to the type of the API property
  • display of the server-side validation errors under the related input (if using API Platform Core)
  • client-side validation (required attributes)
  • the generated HTML is compatible with Bootstrap and includes mandatory classes
  • the generated HTML code is accessible to people with disabilities (ARIA support)
  • the Redux and the React Router configuration is also generated

Thanks to Piotr Synowiec for his contributions and fixes to those frontend tools!

Builtin HTTP Cache Invalidation System

Exposing a hypermedia API has many advantages. One of them is the ability to know exactly which resources are included in HTTP responses created by the API. We used this specificity to make API Platform apps blazing fast.

When the new cache mechanism is enabled, API Platform collects identifiers of every resources included in a given HTTP response (including lists, embedded documents and subresources) and returns them in a special HTTP header called Cache-Tags.

cache reverse proxy supporting cache tags (Varnish, CloudFlare, Fastly…) must be put in front of the web server and store all responses returned by the API with a high TTL. When a resource is modified, API Platform takes care of purging all responses containing it in the proxy’s cache. It means that after the first request, all subsequent requests will not touch the web server, and will be served instantly from the cache. It also means that the content served will always be fresh, because the cache is purged in real time.

The support for most specific cases such as the invalidation of collections when a document is added or removed or for relationships and inverse relations is built-in.

We also included Varnish in the Docker setup provided with the distribution of API Platform, so this new feature works out of the box.

Integration with Varnish and the Doctrine ORM is shipped with the core library. You can easily implement the support for any other proxy or persistence system.

A big thanks to Jérémy DerusséTeoh Han HuiFabien Bourigault, Antoine Bluchet and all other involved contributors for their in-depth reviews and good advices.

A detailed blogpost about this feature will follow.

Per Resource Authorization Mechanism

Thanks to the API Platform’s events and the extension system, it was already easy to configure basic authorization rules. In the version 2.1, we introduced an easy way to configure fine grained authorization rules directly from resource classes.

In the following example, only the logged in admins can access all operations related to the SecuredResource. However, regular users owning a specific resource can also access it:

Under the hood, this new feature uses Symfony’s access control expressions. The object variable value is the current resource (or collection of resources) while the user variable contains an instance of the Symfony’s user currently logged in.

Subresources Support

Having the ability to expose subresources was one of the most requested features. It was already possible to use such URL patterns thanks to custom operations, but it was a bit complicated to do.

Fortunately Antoine Bluchet rolled up this sleeves and did an excellent job! As of API Platform 2.1, subresources are a first class citizen:

The previous snippet is enough to expose through http://example.com/products/1/reviews  the list of RelatedDummies resources related to the Dummy #1.

The documentations will also reflect the availability of this new URL.

New Filters

API Platform comes with 3 new useful filters that you will love.

property_filter

Baptiste Meyer contributed 2 of them. The first one, api_platform.serializer.property_filter, lets the client specify which properties the API must return.

When a resource is configured to use it, you can use the URL  /products/1?properties[]=price&properties[]=currency to only serialize the properties “foo” and “bar” of this entity (all other properties will be ignored).

It’s also possible to list the properties of embedded resources with the following format:  /products/1?properties[]=price&properties[brand][]=name.

group_filter

The second one, api_platform.serializer.group_filter is similar, but instead of choosing properties one by one, you can pass a list of serialization groups to apply using a URL like:  /products/1?groups[]=detailed.

Those two filters allow to easily reduce the size of the returned resources to only include relevant data.

exists_filter

The last new filter, api_platform.doctrine.orm.exists_filter, was contributed by Teoh Han Hui. It allows to filter a collection on the existence of a specified value:  /products?brand[exists]=0.

A Revamped API Doc UI

API Platform has a nice UI built with Swagger UI that is available for every URL of the API when requesting it from a browser (or any client sending a Accept: text/html HTTP header). In API Platform 2.1, we upgraded Swagger UI to its new major version (3.0), a full rewrite in ReactJS (API Platform + React = ❤️) including a bunch of UX improvements.

Laury Sorriaux took this opportunity to propose a great custom stylesheet improving the overall user experience and respecting our color scheme. It also contains an animation featuring our cute spider (he will get a name soon, stay tuned)!

Last but not least, Daniel Kiesel contributed to improve the integration with OAuth (and FOSOAuthBundle): it’s now possible to login with OAuth from the UI by just adding a few lines of config.

Brand New Docker Setup

One of the coolest features of API Platform 2 was the ability to run the app locally by just typing  docker-compose up  and to deploy apps in a breath with Kubernetes or Docker Swarm.

In API Platform 2.1, we dramatically improved the Docker support:

  • All images are now using Alpine Linux (reduce the size, improve the security)
  • Nginx and PHP-FPM are now used instead of Apache and mod_php
  • Varnish has been added (see the section about the cache invalidation mechanism)
  • The Docker Compose file has been upgraded to the format v3
  • Many compatibility problems with Windows have been fixed
  • The performance when using Docker for Mac or Docker for Windows has been dramatically improved

This Docker setup supports any Symfony-based application. Just copy/paste it in your Symfony project.

Improving the Docker configuration was a hard and collaborative work. I want to especially thanks Jacques LefebvreTeoh Han Hui and Antoine Bluchet for the large numbers of hours they spent to make this possible.

Integration in Symfony Flex

You can’t have missed it, Symfony 4 will come with an exciting tool to install and manage your projects: Symfony Flex. API Platform is already officially supported by Flex and can’t be easier to install: just type  composer req api

Fabien Potencier (the creator of Symfony) recorded a screencast showing how API Platform and Flex fit well together:

Impressive isn’t it? Flex only works with API Platform 2.1+. Older versions aren’t supported.

Of course, many other new features, fixes and improvements (especially regarding performance) have been merged, you can read the full changelog to learn more.

Next steps before the stable release:

  • Testing, testing and testing again. Please try the new features, upgrade your existing projects and run your tests suites against this new version! Report any problem on GitHub. It’s very very helpful to us!
  • Update the documentation and write new articles for the new features. They are already many pull requests opened, reviewing and improving them is much appreciated.

A last and big thanks to all the API Platform Core Team and especially to Teoh Han HuiAntoine Bluchet, Baptiste Meyer and Hamza Amrouche for their detailed work reviewing all contributions and getting this beta out!

P.S.: Spread the word, please give us a star on GitHub or tweet about the release of this new version!

API Platform 2.1: when Symfony meets ReactJS (Symfony Live 2017)

Slides and videos of my talk during the Symfony Live Paris 2017. Rate this talk on joind.in!

Learn how to use API Platform and Symfony to create super easily rich web and mobile applications relying on React (JS) for their presentational layer.

In just a few minutes, we will create a hypermedia API thanks to API Platform, Symfony and Doctrine. We will do it step by step, and the API will be 100% functional with support for pagination, validation, filters, resources embedding. The API will be automatically documented using Swagger and Hydra and beautiful user interface for developers will be available. HTTP cache, authorization and authentication can then be added in a breath.

Then, we will introduce all new client-side tools for API Platform:

  • A fully featured JavaScript (Single Page App) administration system with a modern user interface (Material Design) ; built on top of Admin On Rest (React and Redux). This admin is builded dynamically thanks to the API discoverability (Hydra).
  • A raw React, Redux and React Router code generator to bootstrap fully-featured Single Page Applications and native mobile apps thanks to the API documentation exposed by API Platform (client-side and server-side validation, on fields error, Twitter Bootstrap compatibility, a11y support…)

DunglasTodoMVCBundle compatible with Symfony 2.4

I’m pleased to announce the release of DunglasTodoMVCBundle 1.1.0.

Screenshot Symfony Todomvc

DunglasTodoMVCBundle is an implementation of TodoMVC, the popular site providing the same todo app implemented in a ton of different JavaScript frameworks.

This bundle provides a REST / JSON API built with Symfony and Doctrine, and an API client built with Chaplin.js and Backbone.js.

In this new release:

Enjoy!

DunglasAngularCsrfBundle: protect your Symfony / AngularJS apps against CSRF attacks

I create and I see more and more web applications sharing the same powerful architecture:

 These components share the same philosophy (built on top of dependency injection and MVC-like patterns, designed to be intensively tested) and play very well together.

This stack allows to create awesome blazing-fast web applications. Better, the client part and the server part of the app are loosely coupled, can evolve separately and can even be maintained by different teams.

However, this kind of apps often suffer of security problems, and especially Cross-site Request Forgery (CSRF or XSRF) vulnerabilities.

Both Symfony and AngularJS provide their own CSRF protection mechanisms, but by default they are not interoperable and not enabled. Thanks to a recent refactoring of the Symfony’s security component, it’s now possible and clean to make both systems working together, and I’ve just released an open source bundle to do that: DunglasAngularCsrfBundle.

This bundle provides out of the box CSRF protection for AngularJS apps interacting with a Symfony-backed app.

Despite it’s name, it does not depend of AngularJS and can also be used with Chaplin.js / Backbone.js, jQuery or even raw JavaScript. To do so, install and configure the bundle, then just add to XHR requests a HTTP header called X-XSRF-TOKEN containing the value of the token set by a cookie on the first HTTP request. The bundle will automatically check the validity of the provided token. If it is not valid, an Access Denied error (HTTP 401) will be thrown.

The bundle is fully tested with phpspec and obtain a platinum medal on the brand new (awesome) SensioLabs Insight quality monitoring system.

Internals documentation and installation instructions are provided on the GitHub page of the bundle. Check it, test it, star it and tell me what you think of it!

Download DunglasAngularCsrfBundle on GitHub. 

jquery.confirmExit : où comment ne plus perdre les données d’un formulaire complété

Je viens de publier un petit plugin jQuery sous license MIT qui affiche une demande de confirmation lorsqu’un l’utilisateur quitte une page web après avoir rempli un formulaire sans l’avoir envoyé.

Perdre toutes les données que l’on vient de saisir en cliquant sur un lien ou en fermant la fenêtre sans avoir appuyer sur “Envoyer”, c’est le genre de détails qui font rager contre les applications web mal finies.

Plus d’excuse avec jquery.confirmExit. Cerise sur le gâteau, le plugin supporte tous les nouveaux champs de formulaires introduits avec HTML5.

Télécharger le plugin sur GitHub

Ajax Syntax Highlighter 1.0 beta 1 released

Yeah, it’s the first public release of the new syntax highlighter announced in my previous post !

Ajax Syntax Highlighter is a small Javascript utility designed to highlight code embed in a web page in a semantic and standard compliant way.
It automatically looks for source code in the page, send it to a server-side highlighter and display the highlighted code. It also has a “view as plain text” feature and internationalization (French translation available).

Ajax Syntax Highlighter is built with Yahoo! UI and uses JSON for serialization.
It currently includes GeSHi as server-side (PHP required) highlighter but it can be easily used with others such as Pygments.

As you can see, the current graphics come from SyntaxHighlighter and are not so good. If you have some webdesign skills and can help me to enhance it, please contact me !