Pure PHP implementation of GraphQL Server – Symfony Bundle

Related tags

API GraphQLBundle
Overview

Symfony GraphQl Bundle

This is a bundle based on the pure PHP GraphQL Server implementation

This bundle provides you with:

  • Full compatibility with the RFC Specification for GraphQL
  • Agile object oriented structure to architect your GraphQL Schema
  • Intuitive Type system that allows you to build your project much faster and stay consistent
  • Built-in validation for the GraphQL Schema you develop
  • Well documented classes with a lot of examples
  • Automatically created endpoint /graphql to handle requests

There are simple demo application to demonstrate how we build our API, see GraphQLDemoApp.

Table of Contents

Installation

We assume you have composer, if you're not – install it from the official website.
If you need any help installing Symfony framework – here's the link http://symfony.com/doc/current/book/installation.html.

Shortcut to install Symfony: composer create-project symfony/framework-standard-edition my_project_name

Once you have your composer up and running – you're ready to install the GraphQL Bundle.
Go to your project folder and run:

composer require youshido/graphql-bundle

Then enable bundle in your app/AppKernel.php

new Youshido\GraphQLBundle\GraphQLBundle(),

Add the routing reference to the app/config/routing.yml:

graphql:
    resource: "@GraphQLBundle/Controller/"

or

graphql:
    resource: "@GraphQLBundle/Resources/config/route.xml"

If you don't have a web server configured you can use a bundled version, simply run php bin/console server:run.

Let's check if you've done everything right so far – try to access url localhost:8000/graphql.
You should get a JSON response with the following error:

{"errors":[{"message":"Schema class does not exist"}]}

That's because there was no GraphQL Schema specified for the processor yet. You need to create a GraphQL Schema class and set it inside your app/config/config.yml file.

There is a way where you can use inline approach and do not create a Schema class, in order to do that you have to define your own GraphQL controller and use a ->setSchema method of the processor to set the Schema.

The fastest way to create a Schema class is to use a generator shipped with this bundle:

php bin/console graphql:configure AppBundle

Here AppBundle is a name of the bundle where the class will be generated in.
You will be requested for a confirmation to create a class.

After you've added parameters to the config file, try to access the following link in the browser – http://localhost:8000/graphql?query={hello(name:World)}

Alternatively, you can execute the same request using CURL client in your console
curl http://localhost:8000/graphql --data "query={ hello(name: \"World\") }"

Successful response from a test Schema will be displayed:

{"data":{"hello":"world!"}}

That means you have GraphQL Bundle for the Symfony Framework configured and now can architect your GraphQL Schema:

Next step would be to link assets for GraphiQL Explorer by executing:

php bin/console assets:install --symlink

Now you can access it at http://localhost:8000/graphql/explorer

Symfony features

Class AbstractContainerAwareField:

AbstractContainerAwareField class used for auto passing container to field, add ability to use container in resolve function:

class RootDirField extends AbstractContainerAwareField
{

    /**
     * @inheritdoc
     */
    public function getType()
    {
        return new StringType();
    }

    /**
     * @inheritdoc
     */
    public function resolve($value, array $args, ResolveInfo $info)
    {
        return $this->container->getParameter('kernel.root_dir');
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'rootDir';
    }

Service method as callable:

Ability to pass service method as resolve callable:

$config->addField(new Field([
    'name'    => 'cacheDir',
    'type'    => new StringType(),
    'resolve' => ['@resolve_service', 'getCacheDir']
]))

Events:

You can use the Symfony Event Dispatcher to get control over specific events which happen when resolving graphql queries.

namespace ...\...\..;

use Youshido\GraphQL\Event\ResolveEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MyGraphQLResolveEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            'graphql.pre_resolve'  => 'onPreResolve',
            'graphql.post_resolve' => 'onPostResolve'
        ];
    }

    public function onPreResolve(ResolveEvent $event)
    {
		//$event->getFields / $event->getAstFields()..
    }

    public function onPostResolve(ResolveEvent $event)
    {
		//$event->getFields / $event->getAstFields()..
    }
}

Configuration

Now configure you subscriber so events will be caught. This can be done in Symfony by either XML, Yaml or PHP.

<service id="my_own_bundle.event_subscriber.my_graphql_resolve_event_subscriber" class="...\...\...\MyGraphQLResolveEventSubscriber">
	<tag name="graphql.event_subscriber" />
</service>

Security:

Bundle provides two ways to guard your application: using black/white operation list or using security voter.

Black/white list

Used to guard some root operations. To enable it you need to write following in your config.yml file:

graphql:

  #...

  security:
    black_list: ['hello'] # or white_list: ['hello']

Using security voter:

Used to guard any field resolve and support two types of guards: root operation and any other field resolving (including internal fields, scalar type fields, root operations). To guard root operation with your specified logic you need to enable it in configuration and use SecurityManagerInterface::RESOLVE_ROOT_OPERATION_ATTRIBUTE attribute. The same things need to do to enable field guard, but in this case use SecurityManagerInterface::RESOLVE_FIELD_ATTRIBUTE attribute. Official documentation about voters.

Note: Enabling field security lead to a significant reduction in performance

Config example:

graphql:
    security:
        guard:
            field: true # for any field security
            operation: true # for root level security

Voter example (add in to your services.yml file with tag security.voter):

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQLBundle\Security\Manager\SecurityManagerInterface;

class GraphQLVoter extends Voter
{

    /**
     * @inheritdoc
     */
    protected function supports($attribute, $subject)
    {
        return in_array($attribute, [SecurityManagerInterface::RESOLVE_FIELD_ATTRIBUTE, SecurityManagerInterface::RESOLVE_ROOT_OPERATION_ATTRIBUTE]);
    }

    /**
     * @inheritdoc
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        // your own validation logic here

        if (SecurityManagerInterface::RESOLVE_FIELD_ATTRIBUTE == $attribute) {
            /** @var $subject ResolveInfo */
            if ($subject->getField()->getName() == 'hello') {
                return false;
            }

            return true;
        } elseif (SecurityManagerInterface::RESOLVE_ROOT_OPERATION_ATTRIBUTE == $attribute) {
            /** @var $subject Query */
            if ($subject->getName() == '__schema') {
                return true;
            }
        }
    }
}

GraphiQL extension:

To run graphiql extension just try to access to http://your_domain/graphql/explorer

Documentation

All detailed documentation is available on the main GraphQL repository – http://github.com/youshido/graphql/.

Comments
  • Removed warning in console

    Removed warning in console

      Too few arguments to function Youshido\GraphQLBundle\Command\GraphQLConfigureCommand::__construct(), 0 passed in var/cache/prod/ContainerYK9QSxf/App_KernelProdContainer.php on  
       line 38382 and exactly 1 expected                                                                                                                                                                         
    

    Added router argument in command service configuration to avoid this error.

    opened by florentdestremau 0
  • Error when run composer require with Symfony 5.2.10

    Error when run composer require with Symfony 5.2.10

    I tired to install the bundle with a fresh empty project Symfony version 5.2.10. when i ran this command
    composer require youshido/graphql-bundle

    i got this error

    • Configuring youshido/graphql-bundle (>=v1.4.1): From auto-generated recipe Executing script cache:clear [KO] [KO] Script cache:clear returned with error code 255 !! ArgumentCountError {#4504 !! #message: "Too few arguments to function Symfony\Component\Config\Definition\Builder\TreeBuilder::__construct(), 0 passed in /var/www/html/testSymfony/vendor/youshido/graphql-bundle/DependencyInjection/Configuration.php on line 21 and at least 1 expected" !! #code: 0 !! #file: "./vendor/symfony/config/Definition/Builder/TreeBuilder.php" !! #line: 26 !! trace: { !! ./vendor/symfony/config/Definition/Builder/TreeBuilder.php:26 { …} !! ./vendor/youshido/graphql-bundle/DependencyInjection/Configuration.php:21 { …} !! ./vendor/symfony/config/Definition/Processor.php:50 { …} !! ./vendor/symfony/dependency-injection/Extension/Extension.php:111 { …} !! ./vendor/youshido/graphql-bundle/DependencyInjection/GraphQLExtension.php:25 { …} !! ./vendor/symfony/dependency-injection/Compiler/MergeExtensionConfigurationPass.php:76 { …} !! ./vendor/symfony/http-kernel/DependencyInjection/MergeExtensionConfigurationPass.php:39 { …} !! ./vendor/symfony/dependency-injection/Compiler/Compiler.php:91 { …} !! ./vendor/symfony/dependency-injection/ContainerBuilder.php:736 { …} !! ./vendor/symfony/http-kernel/Kernel.php:541 { …} !! ./vendor/symfony/http-kernel/Kernel.php:780 { …} !! ./vendor/symfony/http-kernel/Kernel.php:121 { …} !! ./vendor/symfony/framework-bundle/Console/Application.php:168 { …} !! ./vendor/symfony/framework-bundle/Console/Application.php:74 { …} !! ./vendor/symfony/console/Application.php:166 { …} !! ./bin/console:43 { !! › $application = new Application($kernel); !! › $application->run($input); !! › !! } !! } !! } !! 2021-06-05T15:03:43+02:00 [critical] Uncaught Error: Too few arguments to function Symfony\Component\Config\Definition\Builder\TreeBuilder::__construct(), 0 passed in /var/www/html/testSymfony/vendor/youshido/graphql-bundle/DependencyInjection/Configuration.php on line 21 and at least 1 expected !!
      Script @auto-scripts was called via post-update-cmd

    Installation failed, reverting ./composer.json and ./composer.lock to their original content. ` Screenshot from 2021-06-05 15-08-18

    `

    opened by salmaomar 2
  • TreeBuilded constructor with no parameters broke up composer

    TreeBuilded constructor with no parameters broke up composer

    Hello,

    In Symfony 5, let's do this:

    composer require youshido/graphql-bundle composer remove youshido/graphql-bundle composer require youshido/graphql-bundle

    And you get this error: Executing script cache:clear [KO] [KO] Script cache:clear returned with error code 255 !! ArgumentCountError {#4094 !! #message: "Too few arguments to function Symfony\Component\Config\Definition\Builder\TreeBuilder::__construct(), 0 passed in C:...\vendor\youshido\graphql-bundle\DependencyInjection\Configuration.php on line 21 and at least 1 expected" !! #code: 0 !! #file: "C:...\vendor\symfony\config\Definition\Builder\TreeBuilder.php" !! #line: 26 !! trace: {

    Code: class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('graphql');

        $rootNode
            ->children()
    

    ......

    opened by logosur 1
  • Security Token

    Security Token

    Hi,

    is there any possibility to get the token into the resolve function of a type? https://graphql.org/learn/authorization/ says that accessibility control for some kind of data should be in the business logic layer.

    kind regards.

    opened by zerlpaMMT 2
  • Symfony 4 support

    Symfony 4 support

    Symfony 4 supports bundle-less applications (and it's considered best-practice).

    The configure command from this bundle doesn't work with this at the moment so I don't know how to initialize graphql in my project.

    opened by enumag 11
Releases(v1.4.1)
Owner
null
Monorepo of the PoP project, including: a server-side component model in PHP, a GraphQL server, a GraphQL API plugin for WordPress, and a website builder

PoP PoP is a monorepo containing several projects. The GraphQL API for WordPress plugin GraphQL API for WordPress is a forward-looking and powerful Gr

Leonardo Losoviz 265 Jan 7, 2023
This bundle provides tools to build a complete GraphQL server in your Symfony App.

OverblogGraphQLBundle This Symfony bundle provides integration of GraphQL using webonyx/graphql-php and GraphQL Relay. It also supports: batching with

Webedia - Overblog 720 Dec 25, 2022
Syntax to query GraphQL through URL params, which grants a GraphQL API the capability to be cached on the server.

Field Query Syntax to query GraphQL through URL params, which grants a GraphQL API the capability to be cached on the server. Install Via Composer com

PoP 4 Jan 7, 2022
GraphQL Bundle for Symfony 2.

Symfony 2 GraphQl Bundle Use Facebook GraphQL with Symfony 2. This library port laravel-graphql. It is based on the PHP implementation here. Installat

Sergey Varibrus 35 Nov 17, 2022
Pure PHP realization of GraphQL protocol

Looking for Maintainers! Unfortunatelly, we cannot longer support this package and are looking for someone to take the ownership. Currently Only PRs w

null 714 Dec 21, 2022
A PHP implementation of the GraphQL specification based on the JavaScript reference implementation

GraphQL This is a PHP implementation of the GraphQL specification based on the JavaScript reference implementation. Related projects DateTime scalar R

Digia 219 Nov 16, 2022
GraPHPinator ⚡ 🌐 ⚡ Easy-to-use & Fast GraphQL server implementation for PHP

Easy-to-use & Fast GraphQL server implementation for modern PHP. Includes features from latest draft, middleware directives and modules with extra functionality.

Infinityloop.dev 34 Dec 14, 2022
Airbrake.io & Errbit integration for Symfony 3/4/5. This bundle plugs the Airbrake API client into Symfony project

AmiAirbrakeBundle Airbrake.io & Errbit integration for Symfony 3/4/5. This bundle plugs the Airbrake API client into Symfony project. Prerequisites Th

Anton Minin 8 May 6, 2022
Symfony bundle integrating server-sent native notifications

Symfony UX Notify Symfony UX Notify is a Symfony bundle integrating server-sent native notifications in Symfony applications using Mercure. It is part

Symfony 6 Dec 15, 2022
A PHP port of GraphQL reference implementation

graphql-php This is a PHP implementation of the GraphQL specification based on the reference implementation in JavaScript. Installation Via composer:

Webonyx 4.4k Jan 7, 2023
GraphQL implementation with power of Laravel

Laravel GraphQL Use Facebook GraphQL with Laravel 5.2 >=. It is based on the PHP implementation here. You can find more information about GraphQL in t

Studionet 56 Mar 9, 2022
Test your PHP GraphQL server in style, with Pest!

Pest GraphQL Plugin Test your GraphQL API in style, with Pest! Installation Simply install through Composer! composer require --dev miniaturebase/pest

Minibase 14 Aug 9, 2022
EXPERIMENTAL plugin extending WPGraphQL to support querying (Gutenberg) Blocks as data, using Server Side Block registries to map Blocks to the GraphQL Schema.

WPGraphQL Block Editor This is an experimental plugin to work toward compatiblity between the WordPress Gutenberg Block Editor and WPGraphQL, based on

WPGraphQL 29 Nov 18, 2022
The server component of API Platform: hypermedia and GraphQL APIs in minutes

API Platform Core API Platform Core is an easy to use and powerful system to create hypermedia-driven REST and GraphQL APIs. It is a component of the

API Platform 2.2k Dec 27, 2022
DataTables bundle for Symfony

Symfony DataTables Bundle This bundle provides convenient integration of the popular DataTables jQuery library for realtime Ajax tables in your Symfon

Omines Internetbureau 199 Jan 3, 2023
An Unleash bundle for Symfony applications to provide an easy way to use feature flags

Unleash Bundle An Unleash bundle for Symfony applications. This provide an easy way to implement feature flags using Gitlab Feature Flags Feature. Ins

Stogon 7 Oct 20, 2022
Symfony Health Check Bundle Monitoring Project Status

Symfony Health Check Bundle Version Build Status Code Coverage master develop Installation Step 1: Download the Bundle Open a command console, enter y

MacPaw Inc. 27 Jul 7, 2022
A bundle providing routes and glue code between Symfony and a WOPI connector.

WOPI Bundle A Symfony bundle to facilitate the implementation of the WOPI endpoints and protocol. Description The Web Application Open Platform Interf

Champs-Libres 5 Aug 20, 2022
Mediator - CQRS Symfony bundle. Auto Command/Query routing to corresponding handlers.

Installation $ composer require whsv26/mediator Bundle configuration // config/packages/mediator.php return static function (MediatorConfig $config)

Alexander Sv. 6 Aug 31, 2022