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!

[slides] APIDays: Creating hypermedia APIs in a few minutes using the API Platform framework

My talk at APIDays:

API Platform is new open source PHP framework dedicated to the creation of modern web APIs.

It allows to bootstrap a fully featured API (pagination, validation, filtering, sorting, automatically generated documentation, HTTP cache, OAuth and JWT auth…) in just a few minutes.

It exposes out of the box popular API formats including Swagger, JSON-LD, Hydra, HAL, JSONAPI and Schema.org.
It is extensible and can be specialized with ease. Because it is built on top of the industry-leading Symfony framework, it already counts hundreds of available extensions (bundles).

In this talk, I’ll show how to create a hypermedia API in just a few lines of codes, then take a look to the main features of the framework.

Download the PPT (“download” button) to see screencasts!

API Platform 2.0 released: creating powerful web APIs has never been so easy

api-platform-demo

After 1 year of development and more than 700 commits authored by a hundred contributors across the world, the new major release of API Platform is immediately available for download.

API Platform is a PHP 7 framework dedicated to the creation of modern and powerful web APIs. It is especially adapted to build API-centric information systems relying on hypermediaLinked Data; and consumed by Single-Page Applications (using Javascript libraries such as React or Angular) and mobile apps.

API Platform 2 has been built with 3 strong opinions in mind:

  • Creating an API must be an easy and quick process: any web developper should be able to create a REST API in just a few minutes including CRUD support, data validation, filtering and sorting, autogenerated documentation, OAuth and JWT authentication, CORS and other security HTTP headers, caching
  • Modern open formats must be supported out of the box, without requiring any extra work for the developper: Swagger/OpenAPI, JSON-LD, Hydra, HAL, API Problem (RFC 7807) and Schema.org are supported out of the box, the powerful abstraction layer of the framework easily allows adding support for other emerging API formats (JSONAPI and GraphQL support is in progress)
  • Every feature of the framework must be extensible, overridable and modular

API Platform v2 is a massive rewrite of the framework, with tons of new features and bug fixes. The whole design has been rethinked, but let’s take a tour of the major new features and changes:

Revamped Config and Metadata: Exposing an API is a Matter of Seconds

Thanks to the new configuration system and the new metadata component, to create a high grade hypermedia API you just have to modelize your data model as a set of PHP classes then to add some annotations. Example:

This single class is enough to get a working API with the following features:

  • basic CRUD operations
  • data validation and error serialization
  • JSON-LD, Swagger, Hydra support (a lot of other formats can easily be added, see below)
  • pagination
  • an awesome UI and an extensive human-readable documentation reusing PHPDoc’s data and PHP metadata like types (see below)

Checkout our demo to play with a more advanced example (source code, only 2 classes)!

Hypermedia relations are handled out of the box. Leveraging any other feature of API Platform is just a matter of adding a few lines of configuration. Learn more in our getting started guide.

If you don’t like annotations, you can use XML or YAML configuration files instead. If you don’t like the Doctrine ORM (or doesn’t want to tight the exposed data model to the internal model of the database); or if you don’t want to use the Symfony validator, you can create adapters to hook your custom code and use your preferred libraries. API Platform is designed to be fully extensible.

Docker Integration

API Platform’s official distribution is shipped with a Docker setup adapted to API devlopment. It includes a Apache + PHP 7 and a MySQL image. To get an API Platform app up and running on your computer, type the following commands in the main directory:

The app is up and running, browse http://localhost to get started.

API Platform’s images can be deployed easily in production using Docker Swarm (Amazon Web Services, Azure…) or Google Container Engine (with Kubernetes).

A Data Model Generator on Steroid

Instead of crafting your own data model, why not reusing an open vocabulary like the very popular Schema.org and feel the power of Linked Data and Semantic Web? Yes, just like Google but for free.

Since its first release, API Platform comes with a handy code generator allowing to bootstrap a whole PHP data model including classes, properties, getters and setters, full PHPDoc, Doctrine mappings, API Platform’s external vocabulary mappings and validation annotations.

This generator has been updated to match the new configuration format of API Platform 2 and to allow generating custom classes and properties.

The following config file contains a selection of Schema.org’s types and properties. When using the generator to create the corresponding data model, a working API is created without writing a single line of PHP:

Learn more about the generator in the docs and the demo application.

Content Negotiation and Built-in Support for JSON-LD, Hydra, HAL, YAML, CSV and XML

API Platform now natively supports content negotiation (only JSON-LD and Hydra was previously supported) as well as most popular API formats. To be able to retrieve or send resources in a specifc format, you enable them in the configuration file:

This config enable all built-in formats (Symfony 3.2, actually in RC stage, is required for YAML and CSV support). Then, you can request the format you want through the UI using the proper Accept HTTP header, or by adding the format name as extension of any URL of the API (example: https://demo.api-platform.com/books.jsonld).

Support for formats not supported by default can be added by writing custom adapters.

Learn more about content negotiation in API Platform.

A Powerful UI and Automatic Swagger 2 Docs

API Platform 2 generates an extensive Swagger 2/OpenAPI documentation. All URLs and types are automatically described thanks to our powerful metadata extraction system.

A web interface built on top of Swagger UI is also automatically available. Request any API’s URL using a web browser and (thanks to the Accept header sent by the browser), API Platform will display the request sent to the API and the received response in a nice web interface. It will also display a human-readable documentation of the current operation.

api-platform-ui

Browse the homepage to see the documentation of all available operations, including the description of resources and properties extracted from PHP metadata. Use the sandbox to play with your API.

New Filters and Extension Mechanism

Several new built-in filters have been added. In addition to the existing search, date and range filters, the following are now available:

  • boolean: filter by a boolean property
  • numeric: search numeric fields

The filters are now available directly from the UI and documented in both Swagger and Hydra formats.

Learn how to add filters to your API collections.

Filters are now implemented using the brand new extension system. This system allows to hook to the database query generation process and to customize them. It’s particularly useful to implement security features.

Learn how to leverage the extension mechanism to filter the result of an entrypoint depending of the role of the connected user in the documentation.

Secure by default, tested against OWASP’s recommendations for REST APIs

API Platform 2 follows OWASP’s security recommendations for all its built-in features. We created a test suite to ensure that all recommendations applying to API Platform are followed and documented.

Checkout what API Platform 2 do to secure your API.

Improved performance

We are continuously improving the performance of API Platform and Symfony components it uses (like the Serializer or the PropertyAccess component). This new version is faster than v1 and automatically optimizes SQL queries regarding current serialization groups.

API Platform 2 is also compatible with PHP PM. When using it, API response times are divided by 10.

Availability as Standalone Components, Decoupled from Symfony and Doctrine

API Platform is designed as a set of standalone PHP components: the metadata system; JSON-LD, Hydra, Swagger, HAL serializers, Doctrine and Symfony components bridges…

All those components can be used separately to create your own APIs. For now, the Core library must be downloaded, but a subtree split to allow specific component installation will be available for the 2.1 version. Specific classes can already be used separately of the standard distribution, and without Symfony.

We also moved the code generic enough directly to Symfony. For instance the new Symfony’s PropertyInfo component has been extracted from API Platform.  Some new bug fixes and new features and like the MaxDepth as well as YAML and CSV support for the Symfony Serializer has been done while working on API Platform.

Doctrine has never been mandatory to use API Platform, but the set of interfaces to implement to use another persistence system has been rethought and is now documented.

Quality and QA improvements

We dramatically improved the quality of the API Platform code base for this v2. API Platform v1 was already well tested through Behat. In v2 we added a lot of unit tests to prevent bugs and prove that every class respect SOLID principles. The code coverage is now of 96%. Our test suite is automatically run both on Linux (using Travis) and Windows (using AppVeyor).

We also used Scrutinizr and SensioLabs Insight to detect bad practices and improve the overall quality of our code base. API Platform is rated 8.7/10 on Scrutinizr and has the Platinum medal (best rating) on Insight.

Documentation Rewrite and New Website

The documentation has been improved, almost all new features documented and the Getting Started guide fully rewrote. A new website built with React and Redux has also been created. It supports universal rendering and provides a powerful search engine thanks to Algolia’s DocSearch.

A Growing Community

API Platform it’s more than 100 contributors, an awesome core team (Amrouche HamzaAntoine BluchetSamuel ROZETeoh Han HuiThéo FIDRYVincent CHALAMON and myself), workshops and conferences talks across the world (don’t miss the workshop at the Berlin’s Symfony Con next week).

API Platform has been in the top GitHub trending PHP repositories several times during past months (and 1st one time) beside great projects like Laravel, Symfony and WordPress and has now more than 1k stars.

It’s amazing! Thanks to everybody having worked on the code base, contributed to the documentation or evangelized about the solution, you rock!

Training, development, professional services and workshops are also provided worldwide by Les-Tilleuls.coop, API Platform’s creators.

What’s next

The release of API Platform v2 is just the first step! We’re already working on new features and some of them are already ready to be merged in the 2.1 branch including:

More to come! Stay tuned!

If you haven’t already done it, it’s time to give a try to API Platform!

[Slides] Take Off Conf 2016: Creating a hypermedia API in 5 minutes with API Platform

This morning I was speaking about the API Platform framework at the Take Off Conf in my hometown of Lille. Take a look at my slides, and learn how to create a fully featured hypermedia API in a few minutes!

Vidéo : construire des applications API-centric avec API Platform et Symfony

Voici la vidéo de la présentation que j’ai donné lors du Symfony Live 2015 à propos de API Platform, une solution pour construire des applications web modernes reposant sur une API REST hypermedia et auto-découvrable.

Introducing API Platform (beta): the next generation PHP web framework

API Platform

API Platform

Update: API Platform now has a dedicated website with an up to date version of the following tutorial.

PHP celebrates its 20 years this week. In 20 years, the web changed dramatically and is now evolving faster than ever:

PHP.net, Symfony, Facebook and many others have worked hard to improve and professionalize the PHP ecosystem. The PHP world has closed the gap with most backend solutions and is often more innovative than them.

But in critical area I’ve described previously, many things can be improved. Almost all existing solutions are still designed and documented to create websites the old way: a server generate then send plain-old HTML documents to browsers.

What a better gift for the PHP birthday than a brand new set of tools to kickstart modern web projects? Here comes Dunglas’s API platform, a framework for API-first projects built on top of Symfony! Like other modern frameworks such as Zend Framework and Symfony, it’s both a full-stack all-in-one framework and a set of independent PHP components and bundles that can be used separately.

The architecture promoted by the framework will distrust many of you but read until the end and you will see how API Platform make modern development easy and fun again:

  • Start by creating a hypermedia REST API exposing structured data that can be understood by any compliant client such your apps but also as search engines (JSON-LD with Schema.org vocabulary). This API is the central and unique entry point to access and modify data. It also encapsulates the whole business logic.
  • Then create as many clients as you want using frontend technologies you love: an HTML5/Javascript webapp querying the API in AJAX (of course) but also a native iOS or Android app, or even a desktop application. Clients only display data and forms.

Let’s see how to do that. In this tutorial, we will create a typical blog application with API Platform.

If you are in a hurry, a demo is available online and all sources created during this tutorial are available on GitHub:

blog-api-platform

To create the API-side of our project we will:

  • Bootstrap a fully featured and working data model including ORM mapping, validation rules and semantic metadata with the generator provided by API platform (of course you can also handcraft your data model or modify the generated one to fit your needs).
  • Expose this data model trough a read/write (CRUD) API following JSON-LD and Hydra Core Vocabulary open standards, having Schema.org metadata and with a ton of features out of the box: pagination, validation, error serialization, filters and a lot of other awesome features (here too, everything is extensible thanks to a powerful event system and strong OOP).

Then we will develop a tiny AngularJS webapp to illustrate how to create and consume data from the API. Keep in mind that you can use your preferred client-side technology (tested and approved with Angular, React, Ionic, Swift but can work with any language able to send HTTP requests).

Prerequisites

Only PHP 5.5+ must be installed to run Dunglas’s API Platform. A built-in web server is shipped with the framework for the development environment.

To follow this tutorial a database must be installed (but its not a strong dependency of the framework). I recommend MySQL or MariaDB but other major DBMS are supported including SQLite, PostgreSQL, Oracle and SQL server are supported trough Doctrine.

Installing the framework

Let’s start our new blog API project. The easiest way to create a new project is to use Composer (you need to have it installed on your box):

Composer creates the skeleton of the new blog API then retrieve the framework and all its dependencies.

At the end of the installation, you will be prompted for some configuration parameters including database credentials. All configuration parameters can be changed later by editing the app/config/parameters.yml file.

Dunglas’s API Platform is preconfigured to use the popular Doctrine ORM. It is supported natively by all API Platform components. However the Doctrine ORM is fully optional: you can replace it by your favorite ORM, no ORM at all and even no database.

The installer will ask for:

  • mail server credentials (to send mails)
  • the locale of the application
  • the URL of your default web client application to automatically set appropriate CORS headers, set it to http://locahost:9000  (the default URL of the built-in Grunt server) to follow this tutorial
  • a name and a description of the API that will be used in the generated documentation
  • a secret token (choose a long one) for cryptographic features

Take a look at the content of the generated directory. You should recognize a Symfony application directory structure. It’s fine and intended: the generated skeleton is a perfectly valid Symfony full-stack application that follows Symfony Best Practices. It means that you can:

The skeleton comes with a demonstration bookstore API. Remove it:

  • empty  app/config/schema.yml and  app/config/services.yml
  • delete all files in the src/AppBundle/Entity/ directory

Generating the data model

The first incredibly useful tool provided by Dunglas’s API platform is it’s data model generator also know as PHP Schema. This API Platform component can also be used standalone to bootstrap any PHP data model.

To kickstart our blog data model we browse Schema.org and find an existing schema that describe perfectly what we want: https://schema.org/BlogPosting

The  schema command line tool will instantly generate a PHP data model from the Schema.org vocabulary:

Browse Schema.org, choose the types and properties you need (there is a bunch of schemas available), run our code generator. You’re done! You get a fully featured PHP data model including:

  • A set of PHP entities with properties, constants (enum values), getters, setters, adders and removers. The class hierarchy provided by Schema.org will be translated to a PHP class hierarchy with parents as abstract classes. The generated code complies with PSR coding standards.
  • Full high-quality PHPDoc for classes, properties, constants and methods extracted from Schema.org.
  • Doctrine ORM annotation mapping including database columns with type guessing, relations with cardinality guessing, class inheritance (through the @AbstractSuperclass annotation).
  • Data validation through Symfony Validator annotations including data type validation, enum support (choices) and check for required properties.
  • Interfaces and Doctrine ResolveTargetEntityListener support.
  • List of values provided by Schema.org with PHP Enum classes.

Reusing an existing semantic schema has many advantages:

Don’t Reinvent The Wheel

Data models provided by Schema.org are popular and have been proved efficient. They cover a broad spectrum of topics including creative work, e-commerce, event, medicine, social networking, people, postal address, organization, place or review. Schema.org has its root in a ton of preexisting well designed vocabularies and is successfully used by more and more website and applications.

Pick up schemas applicable to your application, generate your PHP model, then customize and specialize it to fit your needs.

Improve SEO and user experience

Adding Schema.org markup to websites and apps increase their ranking in search engines results and enable awesome features such as Google Rich Snippets and Gmail markup.

Mapping your app data model to Schema.org structures can be a tedious task. Using the generator, your data model will be a derived from Schema.org. Serializing your data as JSON-LD will not require specific mapping nor adaptation. It’s a matter of minutes.

Be ready for the future

Schema.org improves the interoperability of your applications. Used with hypermedia technologies such as Hydra it’s a big step towards the semantic and machine readable web. It opens the way to generic web API clients able to extract and process data from any website or app using such technologies.
To generate our data model form Schema.org types, we must create a YAML configuration file for PHP schema:

Then execute the generator:

Take a look at the content of the src/AppBundle/Entity/ directory. PHP Schema generated for us a set of Plain-Old-PHP entities representing our data model. As promised our entities include:

  • type documentation from Schema.org and converted it to PHPDoc
  • Doctrine ORM mapping annotations (including for relations)
  • Symfony validation annotations
  • Schema.org IRI mapping (the @Iri annotations), we will see later that the API bundle use them to expose structured semantic data
  • and they follow the PSR-2 coding style

The data model is fully functional. You can hack it (modify entities, properties, indexes, validation rules…), or use it as is!

Ask Doctrine to create the database of the project:

Then generate database tables related to the generated entities:

PHP Schema provides a lot of configuration options. Take a look at its dedicated documentation. Keep in mind that PHP Schema is also available as a standalone tool (and a PHAR will be available soon) and can be used to bootstrap any PHP project (works fine with raw PHP, API Platform and Symfony but has an extension mechanism allowing to use it with other technologies such as Zend Framework and Laravel).

Sometimes we will have to make a data model with very specific business types, not available in Schema.org. Sometimes we will find Schema.org types that partially matches what we want but needs to be adapted.

Keep in mind that you can always create your very own data model from scratch. It’s perfectly OK and you can still use API Platform without PHP Schema.

Anyway, PHP Schema is a tool intended to bootstrap the data model. You can and you will edit manually generated PHP entities. When you start to edit manually the generated files, be careful to not run the generator again, it will overwrite your changes (this behavior will be enhanced in future versions). When you do such things, the best to do is to remove dunglas/php-schema  from  your composer.json  file.

Exposing the API

We have a working data model backed by a database. Now we will create a hypermedia REST API thanks to another component of Dunglas’s API Platform: DunglasApiBundle.

As PHP Schema, it is already preinstalled and properly configured. We just need to declare resources we want to expose.

Exposing a resource collection basically consist to register a new Symfony service. For our blog app we will expose trough the API the two entity classes generated by PHP Schema: BlogPosting (blog post) and Person  (author of the post):

And our API is already finished! How would it be easier?

Start the integrated development web server:  app/console server:start

Then open http://localhost:8000/doc with a web browser:

API Platform doc

Thanks to NelmioApiDocBundle support of DunglasApiBundle and its integration with API Platform, you get for a free an automatically generated human-readable documentation of the API (Swagger-like). The doc also includes a sandbox to try the API.

You can also use your favorite HTTP client to query the API. I strongly recommend Postman. It is lower level than the sandbox and will allow to inspect forge and inspect JSON requests and responses easily.

Open  http://localhost:8000 with Postman. This URL is the entry point of the API. It gives to access to all exposed resources. As you can see, the API returns minified JSON-LD. For better readability, JSON snippets have been prettified in this document.

Trying the API

Add a person named Kévin by issuing a POST request on  http://localhost:8000/users  with the following JSON document as raw body:

The data is inserted in database. The server replies with a JSON-LD representation of the freshly created resource. Thanks to PHP Schema, the  @type  property of the JSON-LD document is referencing a Schema.org type:

The JSON-LD spec is fully supported by the bundle. Want a proof? Browse http://localhost:8000/contexts/Person .

By default, the API allows GET (retrieve, on collections and items), POST (create), PUT (update) and DELETE (self-explaining) HTTP methods. You can add and remove any other operation you want. Try it!

Now, browse http://localhost:8000/people :

Pagination is also supported (and enabled) out of the box.

It’s time to post our first article. Run a POST request on http://locahost:8000/blog_posting with the following JSON document as body:

Oops… the isFamilyFriendly  property is a boolean. Our JSON contains an incorrect string. Fortunately the bundle is smart enough to detect the error: it uses Symfony validation annotations generated by PHP Schema previously. It returns a detailed error message in the Hydra error serialization format:

Correct the body and send the request again:

We fixed it! By the way you learned how to to work with relations. In a hypermedia API, every resource is identified with an unique IRI (an URL is a an IRI). They are in the @id  property of every JSON-LD document generated by the API and you can use it as reference to set relations like we done in the previous snippet for the author property.

Dunglas’s API Platform is smart enough to understand any date format supported by PHP date functions. In production we recommend the format specified by the RFC 3339.

We already have a powerful hypermedia REST API (always without writing a single line of PHP), but there is more.

Our API is auto-discoverable. Open http://localhost:8000/vocab and take a look at the content. Capabilities of the API are fully described in a machine-readable format: available resources, properties and operations, description of elements, readable and writable properties, types returned and expected…

As for errors, the whole API is described using the Hydra Core Vocabulary, an open web standard for describing hypermedia REST APIs in JSON-LD. Any Hydra-compliant client or library is able to interact with the API without knowing anything about it! The most popular Hydra client is Hydra Console. Open an URL of the API with it you’ll get a nice management interface.

API Platform Hydra console

You can also give a try to the brand new hydra-core Javascript library.

DunglasApiBundle offers a lot of other features including:

Read its dedicated documentation to see how to leverage them and how to hook your own code everywhere into it.

Specifying and testing the API

Behat (a Behavior-driven development framework) is preconfigured with contexts useful to spec and test REST API and JSON documents.

With Behat, you can write the API specification (as user stories) in natural language then execute scenarios against the application to validate its behavior.

Create a Gherkin feature file containing the scenarios we run manually in the previous chapter:

The API Platform flavor of Behat also comes with a temporary SQLite database dedicated to tests. It works out of the box.

Just run bin/behat . Everything should be green:

Then you get a powerful hypermedia API exposing structured data, specified and tested thanks to Behat. And still without a line of PHP!

It’s incredibly useful for prototyping and Rapid Application Development (RAD). But the framework is designed to run in prod. It benefits from strong extension points and is has been optimized for very high-traffic websites (API Platform powers the new version of a major world-wide media site).

Other features

Dunglas’s API Platform has a lot of other features and can extended with PHP libraries and Symfony bundles. Stay tuned, more documentation and cookbooks are coming!

Here is a non exhaustive list of what you can do with API Platform:

The Angular client

Prequistes: Node.js and NPM must be installed.

Dunglas’s API Platform is agnostic of the client-side technology. You can use whatever platform, language or framework you want. As an illustration of doors opened by an API-first architecture and the ease of development of SPA, we will create a tiny AngularJS client.

Keep in mind that this is not an AngularJS tutorial and it doesn’t pretend to follow AngularJS best practices. It’s just an example of how simple application development become when all the business logic is encapsulated in an API. The unique responsibility of our AngularJS blog client is to display informations retrieved by the API (presentation layer).

The AngularJS application is fully independent of the API. It’s a HTML/JS/CSS app querying an API trough AJAX. It leaves in its own Git repository and is hosted on its own web server. As it only contains assets, it can even be hosted directly on a CDN such as Amazon CloudFront or Akamai.

To scaffold our AngularJS app we will use the official Angular generator of Yeoman. Install the generator then generate a client skeleton:

Yeoman will ask some questions. We want to keep the app minimal:

  • don’t install Sass support
  • install Twitter Bootstrap (it’s optional but the app will look better)
  • uncheck all suggested angular modules

However, we will install Restangular, an awesome REST client for Angular that fit well with API Platform:

The Angular generator comes with the Grunt build tool. It compiles assets (minification, compression) and can serve the web app with an integrated development web server. Start it:

DunglasApiBundle provides a Restangular integration guide in its documentation. Once configured, Restangular will work with the JSON-LD/Hydra API like with any other standard REST API.

Then edit app/app.js file to register Restangular and configure it properly:

Be sure to change the base URL with the one of your API in production (protip: use grunt-ng-constant).

And here is the controller retrieving the posts list and allowing to create a new one:

As you can see, querying the API with Restangular is easy and very intuitive. The library automatically issues HTTP requests to the server and hydrates “magic” JavaScript objects corresponding to JSON responses that can be manipulated to modify remote resources (trough PUT , POST  and DELETE requests).

We also leverage the server side error handling to display beautiful messages when submitted data are invalid or when something goes wrong.

And the corresponding view looping over posts and displaying the form and errors:

It’s the end of this tutorial. Our blog client is ready and working! Remember of the old way of doing synchrone web apps? What do you think of this new approach? Easier and very much powerful isn’t it?

Of course there are some tasks to have a finished client including routing, pagination support and injecting raw JSON-LD in the generated HTML for search engines (use the response extractor hook provided by Restangular). As it’s only Angular tasks, it’s out of scope of this introduction to API Platform. But it’s a good exercise to add such features to the client. Feel free to share your snippets in comments.

Convinced of the facility of development and of the power of API Platform? Let us know your feedback in comments!

Roadmap

The first beta is ready and there is some task to do before the first stable release:

  • The code is almost ready and already used awesome compagnies including Les-Tilleuls.coop, Smile, the Trip Advisor group and ExaqtWorld. But API Platform still need to bullet proof. The first task before the release is: testing and hunting bugs.
  • The documentation must be enhanced. This tutorial will be the base of the brand new doc being written. A dedicated website is also in progress.
  • We also need more integration (doc or libraries) with popular frontend technologies!

I hope to release the first stable version in July. You can help by contributing (bug reports, docs, code). Everything is hosted on GitHub and Pull Requests are very welcome.

Thanks

Special thanks to Samuel Roze (formerly Les-Tilleuls.coop and now Inviqa), Théo Fidry and Fabien Gasser (Smile), Maxime Steinhausser and Jérémy Derussé (SensioLabs) and Michaël Labrut (La Fourchette) for contributing code, docs and ton of good ideas.

API Platform would never have emerged without the great technologies and libraries it uses as foundation, especially Symfony, Doctrine JSON-LD, Hydra and Schema.org. A big thanks to all their contributors.

Commercial support

Feared of trying this new framework? Commercial support is already available:

  • Contact me for application design and architecture consulting.
  • Les-Tilleuls.coop can develop your softwares based on API Platform (and Symfony) and its team of great engineers do training and consulting.

Mes slides du Symfony Live 2015 : à la découverte de API Platform

Voici les slides concernant le développement d’API hypermerdia diffusés tout à l’heure lors du Symfony Live de Paris.

Les liens vers les différents outils présentés tout à l’heure :

Les slides en plein écran.

Symfony Live 2015 : Construire des applications API-centric avec Symfony

Symfony Live 2015

Je donnerai une conférence de 40 minutes au Symfony Live 2015 qui se déroulera le 9 avril à la Cité Internationale Universitaire de Paris.

J’y parlerai de la conception et du développement d’applications construites autour d’une API REST :

Au cours de ce talk, je présenterai une architecture moderne qui permet de construire des applications performantes, évolutives et interopérables :

Le talk sera didactique et accessible aux développeurs Symfony de tous niveaux. La construction d’une micro-application suivant cette architecture sera présentée pas à pas.

 17 autres conférences atuour de Symfony auront lieu lors du même évènement. Les billets sont en vente sur le site du Symfony Live.

 

Slides à propos des Linked Data et des API REST Hypermedia avec Symfony

Hier j’ai présenté certains de mes travaux autour des Linked Data et de Symfony au sfPot de Lille. Voici la présentation que j’ai projetée : voir les slides en plein écran.

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.