GraphQL API with PHP: Step-by-Step 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: Why GraphQL and PHP Are a Great Pair

In the world of web development, REST API has long been the de facto standard. However, with the growing complexity of applications and the emergence of mobile clients, the drawbacks of REST have become obvious: over-fetching or under-fetching of data, multiple endpoints, complex versioning. GraphQL, developed by Facebook, solves these problems by allowing the client to request only the data it needs and receive it in a single request.

PHP, despite its "old school" reputation, remains a powerful language for building server-side logic. Thanks to modern libraries like webonyx/graphql-php, implementing a GraphQL API in PHP has become simple and efficient. In this tutorial, we will create a full-fledged GraphQL server step by step that can handle queries, mutations, and work with a database.

We will use PHP 8.0+, Composer for dependency management, and the built-in PHP server for local testing. By the end of this article, you will be able to deploy your own API and integrate it with any frontend.



1. Environment Setup and Configuration

Before writing code, you need to prepare the project. Make sure you have PHP 8.0+ and Composer installed. Create a new folder for the project and navigate into it:

mkdir graphql-php-tutorialcd graphql-php-tutorial

Now install the main library webonyx/graphql-php using Composer:

composer require webonyx/graphql-php

For working with the database, we will use PDO, which is built into PHP. Additionally, install a library for convenient query parsing:

composer require graphql-php/graphql-php

Create a file index.php — this will be the entry point for our application. Set up Composer autoloading and the basic structure:

<?phprequire_once __DIR__ . '/vendor/autoload.php';

use GraphQL\\GraphQL;use GraphQL\\Type\\Schema;use GraphQL\\Type\\Definition\\ObjectType;use GraphQL\\Type\\Definition\\Type;

// Our logic will go here

Also create a file schema.graphql to store the schema in text format (optional, but convenient for large projects).



2. Defining the Schema and Data Types

The heart of any GraphQL API is the schema. It describes what data is available and how to access it. In our example, we will create a simple model for a User and a Post.

Let's start by defining the types. In the index.php file, add the following classes:

// User type$userType = new ObjectType([    'name' => 'User',    'fields' => [        'id' => Type::int(),        'name' => Type::string(),        'email' => Type::string(),        'posts' => [            'type' => Type::listOf($postType),            'resolve' => function ($user) use ($db) {                // Resolver function to load user's posts                $stmt = $db->prepare('SELECT * FROM posts WHERE user_id = :id');                $stmt->execute([':id' => $user['id']]);                return $stmt->fetchAll(PDO::FETCH_ASSOC);            }        ]    ]]);

// Post type$postType = new ObjectType([ 'name' => 'Post', 'fields' => [ 'id' => Type::int(), 'title' => Type::string(), 'content' => Type::string(), 'author' => [ 'type' => $userType, 'resolve' => function ($post) use ($db) { $stmt = $db->prepare('SELECT * FROM users WHERE id = :id'); $stmt->execute([':id' => $post['user_id']]); return $stmt->fetch(PDO::FETCH_ASSOC); } ] ]]);

Pay attention to the resolvers — these are functions that determine how to get data for each field. In the example above, we use PDO for database queries.

Now create

Blogs

Book Recommendations