The version 0.2 of the API Platform‘s admin component has just been released!
This nice tool allows to automatically and dynamically build a fully featured administration interface (CRUD, pagination, relations…) for any API supporting the Hydra hypermedia vocabulary (more formats supported soon, see at the end of this article). 0 line of code required!
API Platform Admin is built with React on top of the famous Admin On Rest library as a Progressive Web App.
Let’s discover the bunch of new features that this version brings.
Getting Started
Assuming that you have an API exposing a Hydra documentation, you just have to initialize the following React component to get your admin:
import React from 'react'; import { HydraAdmin } from '@api-platform/admin'; export default () => <HydraAdmin entrypoint="https://api.example.com"/>;
For instance, create a new app with Facebook’s create-react-app, replace the content of src/App.js
with the previous snippet and run yarn add @api-platform/admin
. You’re done!
If you get an error related to multiple versions of React being loaded, just remove the react
and react-dom
packages from your project’s package.json
and run yarn install
again.
If you don’t have a JSON-LD / Hydra API yet, here is the code of the one I’ll use in the following examples. This API has been created using the API Platform’s distribution:
<?php namespace App\Entity; use ApiPlatform\Core\Annotation\ApiProperty; use ApiPlatform\Core\Annotation\ApiResource; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ApiResource */ class Person { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column * @ApiProperty(iri="http://schema.org/name") */ public $name; /** * @var Greeting[] * * @ORM\OneToMany(targetEntity="Greeting", mappedBy="person", cascade={"persist"}) */ public $greetings; public function __construct() { $this->greetings = new ArrayCollection(); } public function getId() { return $this->id; } public function addGreeting(Greeting $greeting) { $greeting->person = $this; $this->greetings->add($greeting); } public function removeGreeting(Greeting $greeting) { $greeting->person = null; $this->greetings->removeElement($greeting); } }
<?php namespace App\Entity; use ApiPlatform\Core\Annotation\ApiProperty; use ApiPlatform\Core\Annotation\ApiResource; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ApiResource * @ORM\Entity */ class Greeting { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column * @Assert\NotBlank * @ApiProperty(iri="http://schema.org/name") */ public $name = ''; /** * @ORM\ManyToOne(targetEntity="Person", inversedBy="greetings") */ public $person; public function getId(): ?int { return $this->id; } }
Yes, you just need those two tiny PHP classes to get a hypermedia API. Learn more about the API component by reading the getting started guide. But, really, any API with a Hydra documentation will do the job regardless of the server-side programming language.
Native Support for to-Many Relations
API Platform Admin supports to-one relations since its very first release. However it was mandatory to customize the component used for to-many relations. This isn’t the case anymore. Our API documentation parser gained support for cardinalities and can now extract them if the API documentation includes OWL’s maxCardinality properties.
If no cardinality is provided, the admin will use a to-many widget by default.
Thanks to this new feature, here is how the edition screen of the Person resource looks like this:
The admin is able to guess that the Person resource is related to many Greeting ones and use the appropriate Admin On Rest component.
Detection of More Schema.org’s Types (name, url and email)
API Platform Admin is able to guess the widget to use depending of the type of a resource’s property. It supports:
- Numbers (
http://www.w3.org/2001/XMLSchema#float
andhttp://www.w3.org/2001/XMLSchema#integer
ranges) - Dates (
http://www.w3.org/2001/XMLSchema#date
andhttp://www.w3.org/2001/XMLSchema#dateTime
ranges) - Booleans (
http://www.w3.org/2001/XMLSchema#boolean
range) - And of course text fields
In this new release, Admin also supports some types of the popular Schema.org vocabulary:
- As shown in the previous screenshots (e.g. Greetings select box), if a property has the type
http://schema.org/name
, this property will be used instead of the ID when displaying this relation - If a property has the type
http://schema.org/url
, the URL will be clickable when displayed in the admin - If a property has the type
http://schema.org/email
, the HTML input will be of typeemail
and a basic validation will occur (this was already working in v0.1)
Support for Read-only Resources
The version 0.1 wasn’t able to deal with read-only resource (no POST
nor PUT
operation). We have improved the API doc parser to support owl:equivalentClass
properties. Now, if the API documentation provide those properties, the admin will be builded even if the resource is read-only (of course in this case you will only be able to browse resources, and not to edit them).
Easier and Deeper Customization
Morgan Auchedé did an excellent work to make the Admin fully and easily customizable. You can now override any generated React component by a custom one, or one from Admin On Rest, or from MUI React. You can just replace (or ad, or remove) a specific input or field. But you can also replace a whole list, a show view, a creation or edition form or a remove button.
Here is an example of full customization, courtesy of Morgan:
import parseHydraDocumentation from '@api-platform/api-doc-parser/lib/hydra/parseHydraDocumentation'; import { Datagrid, EditButton, ImageField, List, ShowButton, TextField } from 'admin-on-rest'; import React from 'react'; import SingleImageInput from '../components/inputs/single-image-input'; export default entrypoint => parseHydraDocumentation(entrypoint) .then( ({ api }) => { // Customize "Gallery" resource const gallery = api.resources.find(({ name }) => 'galleries' === name); gallery.list = (props) => ( <List {...props}> <Datagrid> <TextField source="id"/> {props.options.fieldFactory(props.options.resource.fields.find(({ name }) => name === 'name'))} {props.options.fieldFactory(props.options.resource.fields.find(({ name }) => name === 'mainImage'))} {props.hasShow && <ShowButton />} {props.hasEdit && <EditButton />} </Datagrid> </List> ); // Customize "images" field const images = gallery.fields.find(({ name }) => 'images' === name); images.field = props => ( <ImageField {...props} src="contentUrl"/> ); images.input = props => ( <SingleImageInput {...props} accept="image/*" multiple={true}> <ImageField source="contentUrl"/> </SingleImageInput> ); images.input.defaultProps = { addField: true, addLabel: true, }; // Customize "mainImage" field const mainImage = gallery.fields.find(({ name }) => 'mainImage' === name); mainImage.field = props => ( <ImageField {...props} source={`${props.source}.contentUrl`}/> ); mainImage.input = props => ( <SingleImageInput {...props} accept="image/*" multiple={false}> <ImageField source="contentUrl"/> </SingleImageInput> ); mainImage.input.defaultProps = { addField: true, addLabel: true, }; mainImage.input.defaultProps = { addField: true, addLabel: true, }; return { api }; }, );
Ability to Support Other Formats Such as GraphQL
The parser has been designed to be able to be parse other formats such as a GraphQL schema or Swagger/Open API. The api-doc-parser
library provides an intermediate representation that is populated by the specific format parser. It’s this representation that is used by the parser as well as by our React and Vue.js Progressive Web App generator.
It means that when converters from other formats than Hydra to this intermediate representation will be available (Pull Requests welcome), both tools we’ll support those formats. As you may know, the server part of API Platform now supports GraphQL. You can guess which format we’ll implement next in the api-doc-parser
!
#GraphQL support just landed in @ApiPlatform⚡️💫🎇! Create a class: done. https://t.co/2QaEzgAb9p Contributed by Raoul Clais and @_alanpoulain pic.twitter.com/asaA62UVTw
— Kévin Dunglas (@dunglas) October 6, 2017
1 thought on “API Platform Admin 0.2: an admin in 1 minute for your API (React Progressive Web App)”