Setting Up Basic Routes and Testing GraphQL Endpoints in Laravel GraphQL


GraphQL offers a flexible and efficient way of interacting with APIs by allowing clients to request only the data they need. Integrating GraphQL into a Laravel application is made simple using packages like Rebing GraphQL. In this guide, we'll walk through setting up basic routes for GraphQL and testing your GraphQL endpoints in a Laravel application.


Prerequisites


Before diving into the details, ensure you have the following:


  • A Laravel project installed. If you don't have one, you can create it using:

  

  composer create-project --prefer-dist laravel/laravel graphql-demo


  • Composer for dependency management.

  

  • Rebing GraphQL package installed in your Laravel project.


Step 1: Installing and Configuring Rebing GraphQL


To get started with GraphQL in Laravel, we'll use the Rebing GraphQL package, which makes integrating GraphQL seamless.


Install the package using Composer:


composer require rebing/graphql-laravel


Once installed, publish the package's configuration file:


php artisan vendor:publish --provider="Rebing\GraphQL\GraphQLServiceProvider"


This will generate a `graphql.php` configuration file in the `config` folder. You can now configure your GraphQL schema and define routes for your GraphQL API.


Step 2: Defining Your First GraphQL Schema


GraphQL revolves around schemas that define the structure of your API. A schema consists of queries (for reading data) and mutations (for modifying data). Let's create a simple schema with a single query.


Create a User Type


In GraphQL, types define the shape of the data. Let's create a `UserType` for querying user data. In your `app/GraphQL/Types/` directory, create a new file `UserType.php`:


namespace App\GraphQL\Types;


use Rebing\GraphQL\Support\Type as GraphQLType;

use GraphQL\Type\Definition\Type;


class UserType extends GraphQLType

{

    protected $attributes = [

        'name' => 'User',

        'description' => 'A type that describes a user',

    ];


    public function fields(): array

    {

        return [

            'id' => [

                'type' => Type::nonNull(Type::int()),

                'description' => 'The ID of the user',

            ],

            'name' => [

                'type' => Type::string(),

                'description' => 'The name of the user',

            ],

            'email' => [

                'type' => Type::string(),

                'description' => 'The email of the user',

            ],

        ];

    }

}


Create a User Query


Next, we’ll define a query to fetch users from the database. In your `app/GraphQL/Queries/` directory, create a new file `UserQuery.php`:


namespace App\GraphQL\Queries;


use GraphQL\Type\Definition\Type;

use Rebing\GraphQL\Support\Query;

use App\Models\User;


class UserQuery extends Query

{

    protected $attributes = [

        'name' => 'user',

    ];


    public function type(): Type

    {

        return Type::listOf(\GraphQL::type('User'));

    }


    public function resolve($root, $args)

    {

        return User::all();

    }

}


This query fetches all users from the database.


Registering the Query and Type in the Schema


Now, register the `UserType` and `UserQuery` in your `config/graphql.php` file:


return [

    'schema' => [

        'default' => [

            'query' => [

                'user' => App\GraphQL\Queries\UserQuery::class,

            ],

        ],

    ],

    'types' => [

        'User' => App\GraphQL\Types\UserType::class,

    ],

];


This configuration registers the default schema with one query (`UserQuery`) and one type (`UserType`).


Step 3: Setting Up Routes for GraphQL


With your GraphQL schema in place, Laravel automatically sets up a default route for GraphQL endpoints. The Rebing GraphQL package adds a `/graphql` route, which is defined in the `graphql.php` configuration file.


You don’t need to explicitly define routes for GraphQL queries or mutations. By default, all GraphQL queries and mutations are available at the `/graphql` endpoint.


If you want to modify the default GraphQL route, you can customize the endpoint by modifying the `graphql.php` file:


'routes' => '{graphql_endpoint}' // Default: 'graphql'


For example, if you want to change the route to `/api/graphql`, you can set it as:


'routes' => 'api/graphql',


Step 4: Testing GraphQL Endpoints


Once your GraphQL routes are set up, you can test them by sending HTTP requests to the `/graphql` endpoint.


Using Postman or Insomnia


You can test your GraphQL queries and mutations using API clients like Postman or Insomnia.


1. Set up a new request in Postman/Insomnia.

2. Select `POST` as the request method.

3. Use the URL of your Laravel application followed by `/graphql`. For example, `http://localhost:8000/graphql`.

4. In the request body, add your GraphQL query. For example:


   {

     user {

       id

       name

       email

     }

   }


5. Send the request. You should receive a JSON response with user data if everything is configured correctly.


Using GraphiQL


GraphiQL is a web-based tool for testing GraphQL queries. You can install GraphiQL in your Laravel project by adding the laravel-graphql-playground package:


composer require mll-lab/laravel-graphql-playground


After installation, visit `/graphql-playground` in your browser to interact with your GraphQL API using an intuitive interface.


Step 5: Handling Errors in GraphQL


If there are errors in your query, GraphQL will return an error response. For example, if you query a non-existent field, you will receive an error message indicating the problem.


Example Error Response


{

  "errors": [

    {

      "message": "Cannot query field \"age\" on type \"User\".",

      "locations": [

        {

          "line": 2,

          "column": 5

        }

      ]

    }

  ]

}


Make sure to handle these errors properly in your client-side application.


Setting up basic routes and testing GraphQL endpoints in Laravel is straightforward when using the Rebing GraphQL package. By defining types, queries, and mutations, and configuring the default `/graphql` route, you can build flexible APIs that allow clients to request exactly the data they need. Tools like Postman, Insomnia, and GraphiQL make it easy to test and interact with your GraphQL API, ensuring that your endpoints work as expected.