GraphQL API with PHP: Step-by-Step Practical Tutorial

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to GraphQL with PHP: Why You Should Try It

\n\n

GraphQL is a modern query language for APIs, developed by Facebook. Unlike REST, where each endpoint returns a fixed data structure, GraphQL allows the client to request only the fields it needs. This reduces the amount of data transferred and simplifies the development of complex applications.

\n\n

In this tutorial, we will create a full-fledged GraphQL API in PHP using the webonyx/graphql-php library. You will learn how to define a schema, write resolvers, handle queries and mutations, and test the API via GraphiQL.

\n\n

It is assumed that you have PHP 8.0+ and Composer installed. If not, start by installing them.

\n\n

Project Installation and Setup

\n\n

Step 1: Creating the Project and Installing Dependencies

\n\n

Create a new directory for the project and initialize Composer:

\n\n
mkdir graphql-php-tutorial\ncd graphql-php-tutorial\ncomposer init
\n\n

Install the webonyx/graphql-php library:

\n\n
composer require webonyx/graphql-php
\n\n

Also install nikic/fast-route for simple routing (optional but convenient):

\n\n
composer require nikic/fast-route
\n\n

Step 2: Project Structure

\n\n

Create the following folder structure:

\n\n
graphql-php-tutorial/\n├── src/\n│   ├── Schema/\n│   │   └── schema.php\n│   ├── Resolvers/\n│   │   ├── QueryResolver.php\n│   │   └── MutationResolver.php\n│   └── Data/\n│       └── Database.php\n├── public/\n│   └── index.php\n├── vendor/\n└── composer.json
\n\n

Creating the GraphQL Schema

\n\n

Step 3: Defining Types and Schema

\n\n

Let's create a simple data model: User and Post. Open src/Schema/schema.php and add the following code:

\n\n
<?php\n\nnamespace App\\Schema;\n\nuse GraphQL\\Type\\Definition\\ObjectType;\nuse GraphQL\\Type\\Definition\\Type;\nuse GraphQL\\Type\\Schema as GraphQLSchema;\n\nclass Schema\n{\n    public static function build(): GraphQLSchema\n    {\n        // User type\n        $userType = new ObjectType([\n            'name' => 'User',\n            'fields' => [\n                'id' => Type::int(),\n                'name' => Type::string(),\n                'email' => Type::string(),\n                'posts' => [\n                    'type' => Type::listOf(function() use (&$postType) {\n                        return $postType;\n                    }),\n                    'resolve' => function($user) {\n                        return \\App\\Resolvers\\QueryResolver::getPostsByUser($user['id']);\n                    }\n                ]\n            ]\n        ]);\n\n        // Post type\n        $postType = new ObjectType([\n            'name' => 'Post',\n            'fields' => [\n                'id' => Type::int(),\n                'title' => Type::string(),\n                'content' => Type::string(),\n                'author' => [\n                    'type' => $userType,\n                    'resolve' => function($post) {\n                        return \\App\\Resolvers\\QueryResolver::getUserById($post['author_id']);\n                    }\n                ]\n            ]\n        ]);\n\n        // Root Query type\n        $queryType = new ObjectType([\n            'name' => 'Query',\n            'fields' => [\n                'users' => [\n                    'type' => Type::listOf($userType),\n                    'resolve' => function() {\n                        return \\App\\Resolvers\\QueryResolver::getAllUsers();\n                    }\n                ],\n                'user' => [\n                    'type' => $userType,\n                    'args' => [\n                        'id' => Type::nonNull(Type::int())\n                    ]                

Blogs

Book Recommendations