How to build the API using Laravel and GraphQL

GraphQL is a query language for your API and runs on the server side a for executing queries by using a type system you define for your data. GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.~ graphql.org. GraphQL can increase flexibility call API, we can specify required data with write query language like write the query in the database to access API, this is very powerful for build complex API. GraphQL already has a user interface to help us write a query and it has UI autocomplete when we typing some query, this is awesome.

Before we start coding install latest laravel using command and the GraphQL using composer. The GraphQL is very helpful and has many features for integrating Laravel with GraphQL.

Create Model

Create Query And Type GraphQL

Query in graphQL same as we define endpoint path in Restful API, Query only use to get data and for create, update and delete action we called it MutationType in GraphQL for define type each field in Query, Type will help us to formatting type field of result from query, example of type boolean, string, float, int etc or we can define custom type. this is structure directory for query and type

structure directory for query and type

structure query and type
Here’s the complete source code for UsersQuery.php And UsersType.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php namespaceApp\GraphQL\Type; useApp\User; useGraphQL\Type\Definition\Type; useRebing\GraphQL\Support\Facades\GraphQL; useRebing\GraphQL\Support\Type asGraphQLType; classUsersType extendsGraphQLType { protected$attributes= [ 'name'=> 'Users',
        'description'=> 'A type',
        'model'=> User::class, // define model for users type
    ];
     
    // define field of type
    publicfunctionfields()
    {
        return[
            'id'=> [
                'type'=> Type::nonNull(Type::int()),
                'description'=> 'The id of the user'
            ],
            'email'=> [
                'type'=> Type::string(),
                'description'=> 'The email of user'
            ],
            'name'=> [
                'type'=> Type::string(),
                'description'=> 'The name of the user'
            ],
            // field relation to model user_profiles
            'user_profiles'=> [
                'type'=> GraphQL::type('user_profiles'),
                'description'=> 'The profile of the user'
            ]
        ];
    }
  
    protectedfunctionresolveEmailField($root, $args)
    {
        returnstrtolower($root->email);
    }
}

after creating query (Copy from Github) and type, we need register query and type to schema with edit file config/graphql.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php useApp\GraphQL\Query\ProductsQuery; useApp\GraphQL\Query\UsersQuery; useApp\GraphQL\Type\ProductImagesType; useApp\GraphQL\Type\ProductsType; useApp\GraphQL\Type\UserProfilesType; useApp\GraphQL\Type\UsersType; return[ 'prefix'=> 'graphql',
    'routes'=> 'query/{graphql_schema?}',
    'controllers'=> \Rebing\GraphQL\GraphQLController::class. '@query',
    'middleware'=> [],
    'default_schema'=> 'default',
    // register query 
    'schemas'=> [
        'default'=> [
            'query'=> [
                'users'=> UsersQuery::class,
                'products'=> ProductsQuery::class,
            ],
            'mutation'=> [
            ],
            'middleware'=> []
        ],
    ],
    // register types
    'types'=> [
        'product_images'=> ProductImagesType::class,
        'products'  => ProductsType::class,
        'user_profiles'  => UserProfilesType::class,
        'users'  => UsersType::class,
    ],
    'error_formatter'=> ['\Rebing\GraphQL\GraphQL', 'formatError'],
    'params_key'    => 'params'
];

Testing

We will use GraphiQL to test the API, it is very easy because we will get autocomplete query when we write some query or we can using postman to call API, following is example for autocomplete query.

example for autocomplete query

autocomplete query and result and this is the result

autocomplete query and result

Conclusion

Laravel is a fine choice for PHP developers to use for building an API, especially when a project’s requirements are not precisely defined. It’s a comprehensive framework suitable for any kind of web development, is logically structured, and enjoys strong community support.

 

PhoneWhatsApp