Skip to main content

GraphQL API Integration with any PHP Project

There are 3 primary ways to use this package to generate your GraphQL queries:

  • Query Class: Simple class that maps to GraphQL queries. It's designed to manipulate queries with ease and speed.
  • QueryBuilder Class: Builder class that can be used to generate Query objects dynamically. It's design to be used in cases where a query is being build in a dynamic fashion.
  • PHP GraphQL-OQM: An extension to this package. It Eliminates the need to write any GraphQL queries or refer to the API documentation or syntax. It generates query objects from the API schema, declaration exposed through GraphQL's introspection, which can then be simply interacted with.

Installation

Run the following command to install the package using composer:

$ composer require gmostafa/php-graphql-client

Constructing The Client

A Client object can easily be instantiated by providing the GraphQL endpoint URL.

The Client constructor also receives an optional "authorizationHeaders" array, which can be used to add authorization headers to all requests being sent to the GraphQL server.

note

Always remember to replace API_SECRET with the correct value that you copied from apito console. Go to this page if you do not know where to find your api secrets for your project

Example:

$client = new Client(
'https://api.apito.io/secured/graphql',
['Authorization' => 'Basic API_SECTET']
);

The Client constructor also receives an optional "httpOptions" array, which overrides the "authorizationHeaders" and can be used to add custom Guzzle HTTP Client request options.

Example:

$client = new Client(
'https://api.apito.io/secured/graphql',
[],
[
'connect_timeout' => 5,
'timeout' => 5,
'headers' => [
'Authorization' => 'Basic API_SECTET'
'User-Agent' => 'testing/1.0',
],
'proxy' => [
'http' => 'tcp://localhost:8125', // Use this proxy with "http"
'https' => 'tcp://localhost:9124', // Use this proxy with "https",
'no' => ['.mit.edu', 'foo.com'] // Don't use a proxy with these
],
'cert' => ['/path/server.pem', 'password']
...
]
);

It is possible to use your own preconfigured HTTP client that implements the PSR-18 interface.

Example:

$client = new Client(
'https://api.apito.io/secured/graphql',
[],
[],
$myHttpClient
);

Running Queries

Running Raw Queries

Although not the primary goal of this package, but it supports running raw string queries, just like any other client using the runRawQuery method in the Client class. Here's an example on how to use it:

$gql = <<<QUERY
query {
pokemon(name: "Pikachu") {
id
number
name
attacks {
special {
name
type
damage
}
}
}
}
QUERY;

$results = $client->runRawQuery($gql);

Result Formatting

Running query with the GraphQL client and getting the results in object structure:

$results = $client->runQuery($gql);
$results->getData()->companies[0]->branches;

Or getting results in array structure:

$results = $client->runQuery($gql, true);
$results->getData()['companies'][1]['branches']['address'];

Passing Variables to Queries

Running queries containing variables requires passing an associative array which maps variable names (keys) to variable values (values) to the runQuery method. Here's an example:

$gql = (new Query('companies'))
->setVariables(
[
new Variable('name', 'String', true),
new Variable('limit', 'Int', false, 5)
]
)
->setArguments(['name' => '$name', 'first' => '$limit'])
->setSelectionSet(
[
'name',
'serialNumber'
]
);
$variablesArray = ['name' => 'Tech Co.', 'first' => 5];
$results = $client->runQuery($gql, true, $variablesArray);

Mutations

Mutations follow the same rules of queries in GraphQL, they select fields on returned objects, receive arguments, and can have sub-fields.

Here's a sample example on how to construct and run mutations:

$mutation = (new Mutation('createCompany'))
->setArguments(['companyObject' => new RawObject('{name: "Trial Company", employees: 200}')])
->setSelectionSet(
[
'_id',
'name',
'serialNumber',
]
);
$results = $client->runQuery($mutation);

Mutations can be run by the client the same way queries are run.

Mutations With Variables Example

Mutations can utilize the variables in the same way Queries can. Here's an example on how to use the variables to pass input objects to the GraphQL server dynamically:

$mutation = (new Mutation('createCompany'))
->setVariables([new Variable('company', 'CompanyInputObject', true)])
->setArguments(['companyObject' => '$company']);

$variables = ['company' => ['name' => 'Tech Company', 'type' => 'Testing', 'size' => 'Medium']];
$client->runQuery(
$mutation, true, $variables
);

These are the resulting mutation and the variables passed with it:

mutation($company: CompanyInputObject!) {
createCompany(companyObject: $company)
}
{"company":{"name":"Tech Company","type":"Testing","size":"Medium"}}

Detailed Guide

For a detailed guide, be sure to check out the official github page here