Introduction GraphQL

Y. H. Nugroho
3 min readMay 5, 2020

REST is software architectural style for distributed hypermedia systems. for more details you can visit Fielding`s Dissertation. I commonly meet REST on Web API (Application Programming Interface) implement this, so it the service call RESTful (buzzword alert 😆).

In this article i want show you a different way how to serve APIs, other than REST style.

GraphQL

Image source: https://graphql.org/

Common misunderstanding about this technology, that assuming GraphQL(Graph Query Language) is directly connected and query to database. Actually not, GraphQL work to serve you API in query language manner and giving data by given queries (like database).

GraphQL role is became an interface to our API request in query manner with based on our code and predefined query schemas. So , we need implement function on our code base following definition on schemas for GraphQL .

How it work

Image source: https://graphql.org/learn/queries/

GraphQL returning data which stated in query we given, so that would obey it. In GraphQL there are two different query type :

  • Query
  • Schema

Query work like we enumerate all item on our table with or without filter (just read data), Mutation do the change like Create , Delete and Update.

GraphQL implement type-system in it.So we need return value with exact data type from our function follow what schema define, this like build-in type validation.

How to make one

Fortunately, I had make a basic template which help us to focus on implement query and it method implementation instead build it from scratch.

If we open resolver.go and schema.graphql, we’ll see this:

resolver.go

package resolver

type Resolver struct{}

func (_ Resolver) Hi() string {
return "Hello, how are you ?"
}

schema.graphql

schema{
query: Queries
}

type Queries{
hi: String!
}

At schema.graphql, we see schema definition (`schema{query: Queries}`). That mean any field on Queries ( hi’s fields) w’ll work as querying(reading) task.

Then we look at resolver.go, there a resolver’s with method hi and return a string. that is implementation correlated with field at schema.graphql, for precise hi’s fields on Queries type on schema.

The type name (Queries) and class name (Resolver) not have any influence except it implemented method must represent name field on schemas.

How to query it

Query example on Altair at my browser extensions

There a query type queries, you can add `query{ queries_function }`. if there mutation simply change query to mutation.

If you do not use altair or any GraphQL client, you can simply push query and variables on HTTP body header like this:

{query: "query{hi}" , variables: "{}"}

that my short introduction, sorry for bad grammars.

Thank you.

--

--