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()
    ]
]);

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'];
    }
};

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());
}

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1591
276
edge pdf viewer not working edge pdf viewer not working Aug 07, 2025 pm 04:36 PM

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

Yii Developer: Mastering the Essential Technical Skills Yii Developer: Mastering the Essential Technical Skills Aug 04, 2025 pm 04:54 PM

To become a master of Yii, you need to master the following skills: 1) Understand Yii's MVC architecture, 2) Proficient in using ActiveRecordORM, 3) Effectively utilize Gii code generation tools, 4) Master Yii's verification rules, 5) Optimize database query performance, 6) Continuously pay attention to Yii ecosystem and community resources. Through the learning and practice of these skills, the development capabilities under the Yii framework can be comprehensively improved.

VS Code shortcut to focus on explorer panel VS Code shortcut to focus on explorer panel Aug 08, 2025 am 04:00 AM

In VSCode, you can quickly switch the panel and editing area through shortcut keys. To jump to the left Explorer panel, use Ctrl Shift E (Windows/Linux) or Cmd Shift E (Mac); return to the editing area to use Ctrl ` or Esc or Ctrl 1~9. Compared to mouse operation, keyboard shortcuts are more efficient and do not interrupt the encoding rhythm. Other tips include: Ctrl KCtrl E Focus Search Box, F2 Rename File, Delete File, Enter Open File, Arrow Key Expand/Collapse Folder.

go by example running a subprocess go by example running a subprocess Aug 06, 2025 am 09:05 AM

Run the child process using the os/exec package, create the command through exec.Command but not execute it immediately; 2. Run the command with .Output() and catch stdout. If the exit code is non-zero, return exec.ExitError; 3. Use .Start() to start the process without blocking, combine with .StdoutPipe() to stream output in real time; 4. Enter data into the process through .StdinPipe(), and after writing, you need to close the pipeline and call .Wait() to wait for the end; 5. Exec.ExitError must be processed to get the exit code and stderr of the failed command to avoid zombie processes.

Fixed: Windows Update Failed to Install Fixed: Windows Update Failed to Install Aug 08, 2025 pm 04:16 PM

RuntheWindowsUpdateTroubleshooterviaSettings>Update&Security>Troubleshoottoautomaticallyfixcommonissues.2.ResetWindowsUpdatecomponentsbystoppingrelatedservices,renamingtheSoftwareDistributionandCatroot2folders,thenrestartingtheservicestocle

Mastering Flow Control Within foreach Using break, continue, and goto Mastering Flow Control Within foreach Using break, continue, and goto Aug 06, 2025 pm 02:14 PM

breakexitstheloopimmediatelyafterfindingatarget,idealforstoppingatthefirstmatch.2.continueskipsthecurrentiteration,usefulforfilteringitemsliketemporaryfiles.3.gotojumpstoalabeledstatement,acceptableinrarecaseslikecleanuporerrorhandlingbutshouldbeused

How to work with arrays in php How to work with arrays in php Aug 20, 2025 pm 07:01 PM

PHParrayshandledatacollectionsefficientlyusingindexedorassociativestructures;theyarecreatedwitharray()or[],accessedviakeys,modifiedbyassignment,iteratedwithforeach,andmanipulatedusingfunctionslikecount(),in_array(),array_key_exists(),array_push(),arr

Fix: Ethernet 'Unidentified Network' Fix: Ethernet 'Unidentified Network' Aug 12, 2025 pm 01:53 PM

Restartyourrouterandcomputertoresolvetemporaryglitches.2.RuntheNetworkTroubleshooterviathesystemtraytoautomaticallyfixcommonissues.3.RenewtheIPaddressusingCommandPromptasadministratorbyrunningipconfig/release,ipconfig/renew,netshwinsockreset,andnetsh

See all articles