Easy build API using Laravel and GraphQL

Ardani Rohman
SkyshiDigital
Published in
3 min readApr 27, 2017

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

Business Logic Layer http://graphql.org/learn/thinking-in-graphs

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

schema product 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

structure 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

autocomplete query and result

and this is the result

demo graphiql

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

  1. Visual Studio Code Environment For Laravel
  2. Easy Build API Using Laravel And GraphQL (Mutation) part 2
  3. Easy Build API Using Laravel And GraphQL (Authentication) part 3

--

--

Ardani Rohman
SkyshiDigital

Remote Software Engineer at Agency Analytics. Ready for collaboration 🎯 find me: http://ardani.github.io