Going GraphQL

REST is the current leader in client-server interactions. Our services have better tooling like grpc and better formats like protocol buffers and avro. Being well typed, GraphQL can bring these together to become the next step in client/server interaction.




Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

GraphQL with React: The Complete Developers Guide

How to create a simple CRUD App using GraphQL and Node.js

A Beginner’s Guide to GraphQL

Node, Express, PostgreSQL, Vue 2 and GraphQL CRUD Web App

Developing and Securing GraphQL APIs with Laravel

Explore GraphQL with Apollo & React: Build a Superhero Database

Explore GraphQL with Apollo & React: Build a Superhero Database

In this article, We share some light on what GraphQL is and give you an opportunity for some hands-on experience with Apollo and React.

In this article, We share some light on what GraphQL is and give you an opportunity for some hands-on experience with Apollo and React.

Curious about all the buzz surrounding GraphQL, but not quite sure why you should be excited? You’re in the right place! We’ll shed some light on what GraphQL is and give you an opportunity for some hands-on experience.

Let’s start by clearing the air and answering the $20,000 question: what is GraphQL? No, it’s not an obscure function on your TI-89. It’s a query language at heart — or query specification more accurately — that can be used to fetch data from just about any data source.

Better yet, it allows you to fetch the exact data you need — no more, no less — in a single network request. While that may not sound like the sexiest tech to come out of the Facebook factory of innovation, you may just find yourself pleasantly surprised at how useful it can be.

All that’s needed is an Apollo server to act as our endpoint and a React app using the Apollo client to leverage any data within. We’ll tackle the server first.

Getting Started with Apollo Server

To get our Apollo server started, create a folder called apollo-server in your favorite working directory. Next, enter that directory and run the following npm command — you do have npm and Node installed, right? — to get the Apollo framework in place:

npm install apollo-server apollo-server-express graphql

Now that you’ve got the various bits and pieces of the Apollo server in place, it’s time to actually tell our server what to serve. Go ahead and create an empty index.js file in the apollo-server directory and add the following to it:

const { ApolloServer, gql } = require('apollo-server');

This line simply pulls in the required objects for starting an Apollo server and parsing our query strings into query documents for GraphQL.

Our First GraphQL Schema

Next up, let’s add our first schema:

// This will be our GraphQL schema
const typeDefs = gql`
  type User {
    id: ID!
    name: String
    superpowers: [Superpower]!
  }

  type Superpower {
    id: ID!
    text: String
  }

  type Query {
    users: [User]
    user(id: ID!): User
  }
`;

Here we add our type definitions. The first is of type User which we define as an object having an id, name, and superpowers field. The second is a simple id and text to describe each superpower. Finally, the third defines two acceptable queries — users and user — that, respectively, return all users or a single user that matches the provided id argument.

Pretty easy, right?

Adding a Dash of Data

Next, let’s add some mock data to bring our schema to life:

// This will be our mock data to query
const users = [{
  id: '1',
  name: 'Peter Parker',
  superpowers: [{
    id: '1',
    text: 'Web slinging'
  },{
    id: '2',
    text: 'Spidey sense'
  }]
},{
  id: '2',
  name: 'Tony Stark',
  superpowers: [{
    id: '3',
    text: 'Industrial design'
  },{
    id: '4',
    text: 'Robotic fashion'
  }]
}];

All we’re doing here is adding two users to our mock data. It’s worth pointing out that GraphQL isn’t relegated to only querying JavaScript arrays. This could be any database or other data construct. We’re just keeping things simple here to focus on the task at hand.

Don’t Forget Resolvers

Next up, we need to tell GraphQL how to interpret the queries we defined above. This is done with resolvers:

// This will be a map of functions to return the data described by our schema
const resolvers = {
  Query: {
    users: () => {
      return users
    },
    user: (root, { id }) => {
      return users.find(user => user.id === id);
    },
  },
};

You’ll notice the first query users requires no arguments and returns the entire users list (at least in theory, more on that later). The second query user accepts the ID of the user to be fetched and returns said user.

Putting It All Together

To finish off our Apollo server, we just need to instantiate a new instance and start listening for connections:

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log(`Apollo server started at ${url}`)
});

Here we send the ApolloServer constructor our schema and resolvers created above. All that’s needed then is to actually start the server, but first, here’s what your index.js should look like:

const { ApolloServer, gql } = require('apollo-server');

// This will be our GraphQL schema
const typeDefs = gql`
  type User {
    id: ID!
    name: String
    superpowers: [Superpower]!
  }

  type Superpower {
    id: ID!
    text: String
  }

  type Query {
    users: [User]
    user(id: ID!): User
  }
`;

// This will be our mock data to query
const users = [{
  id: '1',
  name: 'Peter Parker',
  superpowers: [{
    id: '1',
    text: 'Web slinging'
  },{
    id: '2',
    text: 'Spidey sense'
  }]
},{
  id: '2',
  name: 'Tony Stark',
  superpowers: [{
    id: '3',
    text: 'Industrial design'
  },{
    id: '4',
    text: 'Robotic fashion'
  }]
}];

// This will be a map of functions to return the data described by our schema
const resolvers = {
  Query: {
    users: () => {
      return users
    },
    user: (root, { id }) => {
      return users.find(user => user.id === id);
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log(`Apollo server started at ${url}`)
});

Go ahead and fire it up with node index.js and visit http://localhost:4000/ to see the fruit of your labor!

You should be greeted with a GraphQL playground that lets you try out interactive queries against the schema you’ve created.

Going Hands-on

Let’s test it out by entering this query in the left-hand pane:

query {
  user(id: 1) {
    name
  }
}

Here we use the user query we just set up, and pass it the id of 1. We’re also telling GraphQL that we only want to return the name of said user. The result in the left hand pane — after clicking the play-like button — should look like this:

{
  "data": {
    "user": {
      "name": "Peter Parker"
    }
  }
}

Let’s say you want to take a peek at his superpowers too. All you have to do is request that field:

query {
  user(id: 1) {
    name,
    superpowers {
      text
    }
  }
}

We added the superpowers field and, since we only care about the text and not the superpower ID, we specify as much. The result should now display each superpower for our first user:

{
  "data": {
    "user": {
      "name": "Peter Parker",
      "superpowers": [
        {
          "text": "Web slinging"
        },
        {
          "text": "Spidey sense"
        }
      ]
    }
  }
}

Say we want to grab all users and their superpowers, we can rely on the users query we defined:

query {
  users {
    id,
    name,
    superpowers {
      text
    }
  }
}

And the result:

{
  "data": {
    "users": [
      {
        "id": "1",
        "name": "Peter Parker",
        "superpowers": [
          {
            "text": "Web slinging"
          },
          {
            "text": "Spidey sense"
          }
        ]
      },
      {
        "id": "2",
        "name": "Tony Stark",
        "superpowers": [
          {
            "text": "Industrial design"
          },
          {
            "text": "Robotic fashion"
          }
        ]
      }
    ]
  }
}

Only care about superpowers? We can do that too:

query {
  users {
    superpowers {
      text
    }
  }
}

And you get:

{
  "data": {
    "users": [
      {
        "superpowers": [
          {
            "text": "Web slinging"
          },
          {
            "text": "Spidey sense"
          }
        ]
      },
      {
        "superpowers": [
          {
            "text": "Industrial design"
          },
          {
            "text": "Robotic fashion"
          }
        ]
      }
    ]
  }
}

At this point you should be able to appreciate the supreme flexibility and allure of GraphQL. With a single query and connection we can retrieve any slice of the data we desire. All that’s necessary is a well designed schema and the resolvers to support it.

Even better, back-end developers and front-end developers can do their thing almost independently. With the schema acting as a middle man, both groups can effectively avoid stepping on each other’s toes. And really, that’s GraphQL in a nutshell. Before we wrap this tutorial up however, let’s take a look at how to integrate these queries with an actual React app.

Introducing React to the Mix

Go back to your root working directory and run the following commands to set up a bootstrapped React app with the requisite GraphQL and Apollo libraries:

npm install -g create-react-app
create-react-app my-graphql
cd my-graphql
npm install apollo-boost react-apollo graphql

Next, replace the contents of src/index.js with the following:

index.js:

import React from 'react'
import ReactDOM from 'react-dom'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloProvider } from 'react-apollo'

import App from './App'

const client = new ApolloClient({
    link: new HttpLink({ uri: 'http://localhost:4000/graphql' }),
    cache: new InMemoryCache()
})

ReactDOM.render(
    <ApolloProvider client={client}>
    <App />
    </ApolloProvider>,
    document.getElementById('root')
)

All we need here are the usual imports for a React app along with the Apollo client to interface with our new Apollo server. To create the Apollo client we just need a link to the server http://localhost:4000/graphql and a way to cache our goods. With that, we simply render the app.

Next, we need to set up the app to query and display the data presented by our Apollo server. Go ahead and replace the default src/App.js with this:

App.js:

import React from 'react'
import { Query } from 'react-apollo'
import { gql } from 'apollo-boost'

const TEST_QUERY = gql`
  {
    user(id: 1) {
      id,
      name,
      superpowers {
        text
      }

  }}
`;

const App = () => (
  <Query query={TEST_QUERY}>
  {({ data: { user }, loading }) => {
      if (loading || !user) {
        return <div>Loading ...</div>;
      }
      return (
    <p>
        {user.name} ({user.id}) has the following superpowers:
        <ul>
        {user.superpowers.map(superpower => (
            <li>
                {superpower.text}
            </li>
        ))}
        </ul>
    </p>
      );
    }}
  </Query>
);

export default App

You should see some familiar patterns here. We first use gql to create a GraphQL query document that requests the user with ID 1 — more specifically, their ID, name and superpowers text. Then we pass the document to our server with the Query tag. It’s here that we can format the results in a pretty React app.

Go ahead and start the server with npm start and check out the beautiful results at http://localhost:3000/.

And with that, our tutorial is complete. You’ve created an Apollo server and fed it some simple data structures. You discovered how to write schemas and resolvers to define interactions with the data. You then practiced querying specific pieces of that data. Finally, you tied it all together with a React app that retrieves data from the server and presents it in a nicely formatted way.

While this should be enough to get you started with integrating GraphQL in your future projects, there’s lots still to learn. Mutations for adding and changing data is a great next step.

Learn Database Management System - Database modeling with Golang & PostgreSQL

Learn how to do all Database Management System directly from Golang to PostgreSQL.

Golang OR Go Programming language is modern programming language specialized in building server side applications.

Postgresql is world's most popular open source database management system.

Both are one of the best technologies to build server side modern applications.

So, In this course i will try to give introduction how you guys can use these both technologies togather to build robust backend services.

Remark: This series contains just golang and postgresql integration and workings, it doesn't contain how to build REST apis.

What you'll learn

  • People will learn how to connect to postgresql using golang and how to do DBMS directly from golang.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Golang & PostgreSQL

Google’s Go Essentials For Node.js / JavaScript Developers

Go Programming Language Tutorial | Golang Tutorial For Beginners | Go / Golang Crash Course

Learn Go Programming - Golang Tutorial for Beginners

MySQL vs PostgreSQL - What to Choose the Right Database for Your Project

Learn Database Administration - PostgreSQL Database Administration (DBA) for Beginners

Learn PostgreSQL - Full Course for Beginners

Why should you choose GraphQL?

Why should you choose GraphQL?

Have you heard of GraphQL and wondering if it would be a good fit for your next project? In this post, we are going to understand what GraphQL is, and its benefits. ## Introduction to GraphQL If you are new to GraphQL, here is the long story...

Have you heard of GraphQL and wondering if it would be a good fit for your next project? In this post, we are going to understand what GraphQL is, and its benefits.

Introduction to GraphQL

If you are new to GraphQL, here is the long story short. GraphQL is the new specification that you can use for your API. It is an alternative to writing APIs using REST.

It was developed by Facebook as an internal solution for their mobile apps, and was later open sourced to the community. Ever since then, it has been widely popular among developers and has become a favorite solution for building services.

GraphQL is a query language and is agnostic of the language you use. It is just a specification. The client can query for the data they need from the server. And the server responds back with a JSON response to the query. The interesting thing to note here is that, the client can ask for exactly what they need, and they receive only that. Yes!

Why GraphQL?

Before picking any technology, we need to understand the reason behind choosing it. Let’s dive right it and understand why GraphQL can fit your development needs.

1. Superior Developer Experience

The biggest benefit of using GraphQL, is the superior developer experience that it provides in comparison to alternatives like REST. An interesting thing to note is that with GraphQL, frontend developers stand to benefit a ton. The client driven approach provides a lot of power to the clients to query for what they like by creating custom queries.

No versioning of APIs

This may come as a surprise to some developers. GraphQL has introduced developers to a whole new era in API design and development. Since the client only asks for the data that it needs, it has made API design using GraphQL very flexible. There is no versioning of APIs and adding new fields has no effect on the current client’s call to the APIs. What does this mean? Well, developers do not have to deal with the huge headache of maintaining multiple versions of the API.

The APIs can be continuously evolved without changing versions.

Modifications to GraphQL APIs are non-breaking changes. This principle is very desirable to developers, so that they can continue with their work with no hassle. GraphQL provides a higher level of flexibility in API development that developers have not seen before.

Teams work independently

With GraphQL, multiple teams can work independently in parallel. Have you been in a situation where the frontend team stalls their development, because they are waiting on the backend team to release the latest version of their API or finalize it? It is very common to run into situations where, the frontend/client teams are stalled while they wait on the final version of the API. This causes delays in development and leads to frustration.

With GraphQL, the front-end and back-end teams can work independently. With the strictly typed schema that GraphQL has, the teams can work in parallel. The front-end team can continue working with just a mock version of the API. They can also test the code with it. This gives the developers a pleasant experience without stalling their development work.

2. Declarative Data Fetching

One of the biggest perks of using GraphQL is its declarative data fetching approach.

GraphQL: No multiple rounds trips to server, no over-fetching and no under-fetching of data

Queries can be aggregated to ask for exactly what you want in one trip. With this approach, you can eliminate any over-fetching or under-fetching of data. You ask for what exactly you need and GraphQL gives you back what you asked for.

GraphQL Query in Action

Let’s try to understand this better with an example below. I want to build an app, that displays the blog author information. I want it to display the name of the author, the blog posts written by the author and the three most recent blog topics written by the author.

GraphQL Query Request

Our query will look like below:

 {
  author (id: 6) {
    name 
    posts (last: 3) {
      title
    }
    topics (last : 3) {
     name
    }
  }
}

We pass in the fields that we need response for. We are looking for the author’s name, last three blog posts written, and the last three topics they wrote. The query is structured to ask for exactly what we need.

GraphQL Query Response

Here is what we get back from the server in the form of a JSON response.

{
  "data" : {
    "author" : {
      "name" : "Adhithi Ravichandran",
      "posts" : [
        { title: "React vs. Vue : A Wholesome Comparison"},
        { title: "React Lifecycle Methods: A Deep Dive"},
        { title: "5 Essential Skills A Frontend Developer Should Possess"}
      ],
      "topics" : [
        { name: "React and Vue"},
        { name: "React"},
        { name: "General"}
      ]
    }
  }
}

We got a JSON response back from the server that has exactly what we asked for. It has returned the author name, the last three posts written by the author and the last three topics authored by author. Nothing more, nothing less and everything in a single trip to the server. Isn’t this amazing?!

3. Strongly Typed Schema

Another reason why you should use GraphQL is because of its strongly typed schema. We know that GraphQL is essentially a query language, and it is strongly typed. What this means is that the GraphQL schema should have types for all the objects that it uses. Thus, the schema acts as a contract between the client and the server. The example below shows how types are defined in a GraphQL schema.

type Person {
 id : ID
 name: String
 age: Int
 gender: String
}

We have defined a complex object Person of type _Person. _The object comprises of several fields, each with its own type.

The strongly typed GraphQL schema has several advantages.

  • Code is predictable
  • Schema acts as contract between client and server
  • Teams can work independently
  • Can detect errors early