Skip to content

Kévin Dunglas

Founder of Les-Tilleuls.coop (worker-owned cooperative). Creator of API Platform, FrankenPHP, Mercure.rocks, Vulcain.rocks and of some Symfony components.

Menu
  • Talks
  • Resume
  • Sponsor me
  • Contact
Menu

API Platform Admin 0.2: an admin in 1 minute for your API (React Progressive Web App)

Posted on November 3, 2017November 3, 2017 by Kévin Dunglas

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 and http://www.w3.org/2001/XMLSchema#integer ranges)
  • Dates (http://www.w3.org/2001/XMLSchema#date and http://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 type email 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

Related posts:

  1. API Platform 2.2: GraphQL, JSON API, React admin and PWA, Kubernetes instant deployment and many more new features
  2. API Platform 2.1: when Symfony meets ReactJS (Symfony Live)
  3. 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
  4. API Platform and Symfony: a Framework for API-driven Projects (SymfonyCon)

1 thought on “API Platform Admin 0.2: an admin in 1 minute for your API (React Progressive Web App)”

  1. Pingback: API Platform 2.2: GraphQL, JSON API, admin and PWA, Kubernetes instant deployment and many more new features - software architect and Symfony expert

Leave a ReplyCancel reply

Social

  • Bluesky
  • GitHub
  • LinkedIn
  • Mastodon
  • X
  • YouTube

Links

  • API Platform
  • FrankenPHP
  • Les-Tilleuls.coop
  • Mercure.rocks
  • Vulcain.rocks

Subscribe to this blog

Top Posts & Pages

  • FrankenPHP’s New Features: Thread Autoscaling, Mostly Static Binaries, deb and RPM Packages, Caddy 2.10…
  • FrankenPHP: The Modern Php App Server, written in Go
  • JSON Columns and Doctrine DBAL 3 Upgrade
  • Develop Faster With FrankenPHP
  • FrankenPHP 1.3: Massive Performance Improvements, Watcher Mode, Dedicated Prometheus Metrics, and More
  • FrankenPHP Is Now Officially Supported by The PHP Foundation
  • How to debug Xdebug... or any other weird bug in PHP
  • PHP and Symfony Apps As Standalone Binaries
  • Symfony's New Native Docker Support (Symfony World)
  • Webperf: Boost Your PHP Apps With 103 Early Hints

Tags

Apache API API Platform Buzz Caddy Docker Doctrine FrankenPHP Go Google GraphQL HTTP/2 Hydra hypermedia Hébergement Javascript JSON-LD Kubernetes La Coopérative des Tilleuls Les-Tilleuls.coop Lille Linux Mac Mercure Messagerie Instantanée MySQL performance PHP Punk Rock Python React REST Rock'n'Roll Schema.org Security SEO SEO Symfony Symfony Live Sécurité Ubuntu Web 2.0 webperf XHTML XML

Archives

Categories

  • DevOps (85)
    • Ubuntu (68)
  • Go (19)
  • JavaScript (46)
  • Mercure (7)
  • Opinions (91)
  • PHP (172)
    • API Platform (77)
    • FrankenPHP (11)
    • Laravel (1)
    • Symfony (97)
    • Wordpress (6)
  • Python (14)
  • Security (15)
  • SEO (25)
  • Talks (46)
© 2025 Kévin Dunglas | Powered by Minimalist Blog WordPress Theme