API Platform 2.1: when Symfony meets ReactJS (Symfony Live 2017)
-
Upload
les-tilleulscoop -
Category
Internet
-
view
3.696 -
download
2
Transcript of API Platform 2.1: when Symfony meets ReactJS (Symfony Live 2017)
API PLATFORM 2.1When Symfony meets React
Kévin DunglasFounder of Les-Tilleuls.coop
Symfony Core Team
API Platform creator
@dunglas
Les-Tilleuls.coopSelf-managed company since 2011
100% owned by employees
19 people, 97% growth in 2016
Hiring in Lille, London and Amiens: [email protected]
The Web of 2017
APIs: the Heart of the New Web
Central point to access data
Encapsulate the business logic
Same features available for all channels:webapps, native mobile apps, IoT, enterprise, customers and providers information systems
APIs are the foundations of this new web
SPA: Rich and Fast Webapps
Downloaded and executed only 1 time (first page load)
Use asynchronous HTTP requests to retrieve and modify the raw data (usually JSON) using an API
Huge ecosystem: React/Redux, Angular, Vue, Ember… and probably a new one while I’m speaking
Holds the presentation logic (good-bye Twig)
Standalone apps built using JavaScript, HTML and CSS
Modernized stack: ES2015/16/17, Babel, Webpack, Yarn, Flow, TypeScript…
Native Mobile Apps
Use HTTP requests to retrieve and modify the raw data (usually JSON) using an API but can also work offline
Can be developed using the JS stack: React Native, NativeScript (Angular) - good-bye Cordova
Downloaded from stores (App Store, Google Play)
Look’n’Feel consistent with the platform (iOS or Android)
API Platform:a Framework for 2017
Goals of the Framework
Support modern open API formats
Create a rock-solid API-first system in minutes
Batteries included: everything to create and consume the API
Be able to override, extend and customize everything
Features of API Platform 2.0
They Already Use API Platform
Getting Started
Install
Get DockerIf you don’t already have it…
Install
Provided Docker images - PHP, Nginx, MySQL and Varnish (optional) optimized for Symfony:
Create the database:
Download and extract the ZIP from api-platform.com
Browse http://localhost
$ docker-compose up
$ docker-compose exec php bin/console doctrine:schema:create
A working APIwith just 1 PHP class
Your Turn!
Create your Own Data Model
Write some PHPDoc (optional)
Add the @ApiResource annotation
Map its properties using theDoctrine ORM (optional)
Update the database schema
$ docker-compose run web bin/console doctrine:schema:update --force
Create a Plain Old PHP Object
Your API is Ready!
Out of the Box Features
JSON-LD + Hydra encoding (HAL, XML, YAML, CSV and raw JSON can be enabled through config and you can add yours)
Swagger documentation
Fully featured JavaScript UI using Swagger UI (now built with React) available for all URLs of the API
Create (POST), Retrieve (GET item and lists), Update (PUT) and Delete (DELETE) operations
Pagination for lists (30 items per page), fully configurable
What’s this Format?JSON-LD and Hydra
Credit: Martin Fowlerhttp://martinfowler.com/articles/richardsonMaturityModel.html
JSON-LDStandardized hypermedia format: W3C recommandation (2014)
Easy to use: a standard JSON document with some specials keys (starting with @) and mapped with a context
Backed by Google, BBC, Microsoft, US & UK govs...
Compliant with technologies of the semantic web: RDF, SPARQL, triple store...
JSON for Linked Data
Hydra
Make the API auto-discoverable by clients: all available resources, properties, types and operations are described
Provide a standard format for common structures: collections, paginations, filters, errors…
Documentation of the REST API in JSON-LD
Draft W3C
Data Validation
Addvalidation rules
Many validation constraints available
Ability to create custom constraints
Use the Symfony Validatorcomponent
Relations
Add a Relation
Embedding Relations
Embedded Relations
How does it Work?
REST
Wikipedia
Lexicon
Operation: action on an item or on a collection, usually through HTTP. Internally a Symfony route.
DELETE /books/22
Resource: data exposed by the API, identified by an URL. Internally a PHP object (an entity), externally a document (JSON, HTML, XML…).
item: /books/22 collection: /books
Property: property of a resource. Internally, a class’ property. Externally a document field (e.g. a JSON property). Typed.
It’s Symfony…
Configured with the most popular librariesfor APIsCompatible with all existing bundles
Use Doctrine ORM by default (but you canuse the persistence system you want)
Symfony full stack application
…with something more
Properties’ types and relations are guessed using the Symfony PropertyInfo component
The Metadata component guesses the API’s data structure (resources and properties) form PHP classes marked with @ApiResource
The structure is stored in an intermediate representation used to serialize data and generate API docs (Hydra, Swagger…)
And Even More…Symfony routes are automatically registered for all operations on collections and items. By default:
item: GET, PUT, DELETEcollection: GET, POST
Data is normalized and denormalized using hypermedia normalizers (JSON-LD, Hydra, HAL…) for the Symfony Serializer Component
Event-Driven Architecture
Client-Side Tooling
Foundation of the most popular JS ecosystem out there
A JavaScript library for building user interfacesCreated by Facebook
JSX: write markup inside code
Just like Composer, but for JavaScript.
$ curl -o- -L https://yarnpkg.com/install.sh | bash
$ brew install yarn Mac users:
Create React App
Babel: a JavaScript compiler (ES2015+, JSX, Flow…)
An app skeleton generator
All tools and configs to get started:
Webpack: a module bundler (compile and package your JS, CSS…)
$ yarn global add create-react-app $ create-react-app my-app $ cd my-app $ yarn start
ESLint: identify and report bugs and bad patterns in the code
Integrated web server, live reloading, development and debugging tools
A Basic React Component
Adding some Properties
Adding some Properties
Configuring CORS headers
Loading Some Fixtures
Loading some Fixtures
$ docker-compose exec php bin/console hautelook:fixtures:load
The Admin Generator
API Platform AdminLike Sonata or EasyAdminBundle but as a React SPA
Built on top of Admin On Rest (by Marmelab)
$ yarn add api-platform-admin
Material Design UI
Consume the API using AJAX
Automatically generate the admin by parsing the Hydra API doc
API Platform Admin
Customizing the Admin
The CRUD Generator
API Platform Generate CRUDLike Sensio Generator Bundle, but 100% client-side
Rock solid stack
$ yarn global add api-platform-generate-crud
Twitter Bootstrap support + accessibility (ARIA roles)
Consume the API using ES2015’s fetch()
Automatically generate files by parsing the Hydra API doc
The StackReact, ES2015+, JSX
React Router: client-side routing library
Redux: an extensible container to manage the states of the app
Redux Form: manage form states
Redux Thunk: asynchronous actions (AJAX requests)
Optional: Twitter Bootstrap
Register the Generated code
The API Client
Actions and Creators
Reducers
Components…
…Components Wiring
The Form
React Native Generator
Coming Soon!
Thanks!Any questions?
api-platform/api-platform @ApiPlatform
https://api-platform.com
Extra: More Features!
New in API Platform 2.1
An API as fast as a static website: builtin invalidation-based HTTP cache (Varnish and CloudFlare support)
Client-side tools to consume the API built with React and Redux: an app generator and an admin
Advanced, per-operation authorization rules
Native sub-resources support (e.g. GET /users/1/comments)
A ton of Developer eXperience improvements and better docs
FiltersRegister the filter service (built-in or custom):
Map the filter to the resource
Filters
Content Negotiation
Adding a new format is as simple as creating a new Symfony Normalizer for it
Built-in formats: JSON-LD, HAL, XML, YAML, CSV, JSON, HTML (UI)
To retrieve a resource in a given format: add an Accept HTTP header or use the format name as file extension
Content Negotiation
Content Negotiation: HAL
Content Negotiation: XML
Events
The Schema GeneratorPick an existing data model from (resources and properties) from schema.org:
$ docker-compose exec php vendor/bin/schema generate-types src/ schema.yml
The Schema Generator
The Schema Generator
PHP classes, properties, getters and setters (PSR compliant)Doctrine ORM mapping (including relations and mapped superclasses)Validation constraintsFull PHPDoc extracted from schema human-readable descriptionsMapping with schema.org's IRIs
The generator uses schema.org data to automatically bootstrap:
Relations between classes (supported by the API system too)
Rate this talk:Follow me: @dunglas
joind.in/talk/7abdc