Home Backend Development PHP Tutorial Learn how to create a GraphQL API using PHP: Steps to build an API interface

Learn how to create a GraphQL API using PHP: Steps to build an API interface

Jan 22, 2024 am 11:24 AM
php api graphql

PHP API接口:如何创建GraphQL API?

GraphQL is a query language for APIs that allows clients to accurately query data and avoid wasting network bandwidth and server resources. In this article, we will discuss how to create a GraphQL API using PHP.

How GraphQL API works

GraphQL API is based on query language. The client sends a query request to the server, and the server parses the request and returns the corresponding data. Requests and responses are sent and received in GraphQL language format.

The GraphQL API also supports multi-level associated queries, where the client can query some data and then request related data in the same query. This greatly reduces network bandwidth and server overhead.

There are three main concepts in the GraphQL API: queries, types, and parsers. Queries are requests sent by the client, GraphQL types are the objects used in the API, and resolvers are the code that converts requests into responses.

Create GraphQL API

We will implement the GraphQL API using PHP and use the webonyx/graphql-php library to build and parse queries.

First, we need to create some GraphQL types, which describe the objects in the API. The following is an example User type:

use GraphQLTypeDefinitionType;
use GraphQLTypeDefinitionObjectType;

$userType = new ObjectType([
    'name' => 'User',
    'fields' => [
        'id' => Type::int(),
        'name' => Type::string(),
        'email' => Type::string()
    ]
]);
Copy after login

The above code creates a type named User, containing three fields: id, name, and email. Each field has a type, Type::int() represents an integer type, and Type::string() represents a string type.

Next, we need to create a parser to handle the query. The following is a sample user query parser:

$rootValue = [
    'users' => [
        ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'],
        ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com']
    ]
];

$resolver = function ($root, $args) {
    global $rootValue;

    if (isset($args['id'])) {
        foreach ($rootValue['users'] as $user) {
            if ($user['id'] == $args['id']) {
                return $user;
            }
        }
    } else {
        return $rootValue['users'];
    }
};
Copy after login

The above code creates a $rootValue array, which contains two user objects. The $resolver function will return the corresponding data according to the request sent by the client. If the request has an id parameter, the user information with that id will be returned, otherwise all user information will be returned.

Finally, we need to bind the above types and resolvers into the GraphQL API. The following is the binding code:

use GraphQLGraphQL;
use GraphQLTypeSchema;

$schema = new Schema([
    'query' => new ObjectType([
        'name' => 'Query',
        'fields' => [
            'user' => [
                'type' => $userType,
                'args' => ['id' => Type::int()],
                'resolve' => $resolver
            ],
            'users' => [
                'type' => Type::listOf($userType),
                'resolve' => $resolver
            ]
        ]
    ])
]);

if (!empty($_POST['query'])) {
    $result = GraphQL::executeQuery($schema, $_POST['query']);
    echo json_encode($result->toArray());
}
Copy after login

The above code binds the user type and resolver into the GraphQL API and creates a query object. In the query object we can define multiple queries such as 'user' and 'users'. Each query needs to specify its type and parser, which will be called when a query is detected.

Then we need to send the query into the API via a POST request and parse the response data. Taking the above code as an example, we will get the response JSON object from the API and output it directly.

Summary

In this article, we introduced how to create a GraphQL API using PHP. We discussed how the GraphQL API works and provided some sample code to demonstrate how to create types, resolvers, and bind them into the API. We also use the webonyx/graphql-php library to simplify building and parsing the API. If you want to know more about GraphQL, please refer to the official GraphQL documentation.

The above is the detailed content of Learn how to create a GraphQL API using PHP: Steps to build an API interface. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

See all articles