Easy build API using Laravel and GraphQL
Case Study: Example product list and user list API
Yesterday we learn about Setting Visual Code for Laravel, now we will learn about GraphQL from Facebook.
GraphQL is a query language for your API, and a server-side runtime 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 increases flexibility call API, we can specify required data with write query language like write query in database to access API, this is very powerful for build complex API. GraphQL already have user interface to help us write query and it have ui autocomplete when we typing some query, this is awesome :D make write query easily.
Concept GraphQL see image below that GraphQL same as Rest, they run outside of business logic layer
more information about learn GraphQL you can visit below
# Lets Write Code
1. Install Laravel
install laravel lastest version using command
2. Add Package GraphQL
Install package graphql-laravel using composer, this package very helpful and have many features to integrating Laravel with GraphQL
3. Create Model
create model table user_profiles, products, product_images like schema below and don’t forget about relation between model
4. 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 Mutation
Type 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
Here’s the complete source code for UsersQuery.php And UsersType.php
after create query and type, we need register query and type to schema with edit file config/graphql.php
5. Testing
We can use GraphiQL to write some query to get result and this very easy because we get autocomplete query when we write some query or we can using postman to call API, this is example autocomplete query
and this is the result
don’t worry about full source code, you can access it below :). The next article we will continue learn GraphQL for mutation and authentication
Click ❤ and follow me to get other articles. thanks
related articles