Getting Started With GraphQL Using Golang

Getting Started With GraphQL Using Golang

I’ve been hearing increasing amounts of buzz around GraphQL, a technology that has been around for quite a few years now. In case you’re not familiar, it is a technology for querying API data from a client-front end without having to make numerous requests or receiving unimportant data, both of which may cause negative affects on network latency.

Think of trying to query a relational database. Ideally you write a SQL query for the data you want and you do it in a single request. GraphQL tries to accomplish the same, but from an API consumption level.

We’re going to see how to implement a web application using the Go programming language, but uses GraphQL when working with the data.

Going into this, note that we’re going to be using mock data, not dynamic data residing in a database. If you want to see how to use GraphQL with Golang and a NoSQL database, check out my previous tutorial on the subject.

Bootstrapping a Golang Application in Preparation for GraphQL Support

We’re going to assume that you have Go installed and configured. You don’t need to be a Go wizard to be successful with this tutorial, but it probably shouldn’t be your first time using it.

From the command line, execute the following to install our GraphQL project dependency:

More information about our dependency can be found on the project’s GitHub page.

Create a project somewhere in your $GOPATH and inside that project, create a file called main.go which will hold all of our application code. Within the main.go file, include the following code as a starting point:

In the above code we’re creating several Go data structures that will represent our data model in Go. We will also be creating a GraphQL data model, but it is important not to confuse the two as they are different. You’ll need both.

This particular application will be similar to iTunes. Let’s call it MyTunes. We’ll have information about albums, the songs that reside in them and the artists that perform them.

In the main function, we create a GraphQL schema, but for now we’re going to leave it without any information. Even though we’re not creating a RESTful API, that doesn’t mean we won’t need an API endpoint. With GraphQL we can send any and all queries to this single API endpoint and it will work its magic. The /graphql endpoint will accept requests that look like this:

The important part of every request is the query property in the query parameters. This represents the GraphQL query that we’re sending to the server.

Before we get down and dirty with GraphQL, let’s come up with our mock data. Using a database is not the focus of this tutorial, so we don’t want to get hung up on those details.

Outside your main function, create the following:

We’ll keep it simple for now, but we’ve got two songs that are part of the Fearless album by Taylor Swift. At this point in time, we can do some preparation for querying with a GraphQL query.

Querying for Data with a GraphQL Query

We have the foundation of our application in place as well as a set of data to work with. Let’s try to query for that data, eventually with cURL or some other front-end application.

Remember when I mentioned the Go data structures were not our GraphQL data structures? Let’s create our GraphQL data structures.

In the main function of our application, add the following:

We can create a GraphQL object and define the fields or properties that exist in that object. Each field needs to have a type, where as in this case they are all strings. The same needs to apply for each of our models.

Take the GraphQL model for artists:

Finally, we can take a look at the model for each of our albums:

Yes, each of our fields in all three models are strings, but it isn’t really any different if you needed to change it to something else. Each of the GraphQL models were designed around the Go data structures. We can’t really work with the GraphQL models in Go like we can a native Go data structure.

The next GraphQL object we create will have a similar form, but will represent each of the possible queries we can perform. Having a model is meaningless unless we can apply it to some logic.

Take the rootQuery object, which has no specific or required name:

Every field that exists in this object will represent a possible query. We define a return type, in this case a list of songType and we provide a Resolve function that will be responsible for all of our driving logic.

When querying songs, we might want something like this for a Resolve function:

We’re returning the mock songs data. When we hook it up, and we will later, we could execute a query like this:

Notice that I’ve left out the id as well as the album property? That is because with GraphQL, you get to define exactly the data you want returned to the client.

Alright, that wasn’t a very good example because we’re just returning a variable and not really doing any logic. How about we modify it to be like the following:

Don’t pay too much attention to the Filter function. What matters here is that we’ve included Args to the field which let’s us define which parameters are allowed to be passed in. In the Resolve function we’re getting the album parameter and filtering our slice for only songs of that album. Things would be different with a database, but use your imagination.

The actual query for GraphQL would look like this:

Getting the hang of things now?

Alright, we’ve got a way to query for songs by album, so let’s create a field for querying album information as well as song information.

First we should create a query field for any particular album:

In the above example we’re expecting a parameter and we’re returning a single albumType result rather than a list. If we wanted to craft a fancy query, we could do something like this:

The above GraphQL query would get a single album by the id as well as all songs for the same particular album. In the result we’re only asking for the titles of both, but we could easily change that.

We haven’t adding querying to our GraphQL schema, so up until now it won’t function. It is an easy fix though. Head back into the schema variable we had created earlier and do the following:

We’ve got querying down as of now. We could make things more complicated, but the strategy won’t really change. Now we can focus on altering data.

Create, Delete, and Update Data by using GraphQL for Mutations

GraphQL supports mutations as well as read-only queries. Both are no more difficult than the other and setup is more or less the same, which is convenient for us.

We’re going to create a new GraphQL object like we did for our queries. This object will hold all of our mutation queries. Start it off by doing the following:

The naming doesn’t really matter. We’re going to hook it up to our schema like we did with the rootQuery object. Let’s create a mutation that will allow us to create a new song:

In the above example, we have a createSong field that returns a songType object. For input parameters, we’re expecting everything that composes our object. For the Resolve function, we are taking the data and adding it to the mock list of data.

Let’s wire it up to our schema:

That wasn’t difficult was it?

Running a query that contains a mutation is really no more difficult than running a query that is read only. Take the following for example:

You’ll notice that this particular query requires that we define it as a mutation. If we wanted to execute this query via a cURL command, it would look like the following:

Not too bad right?

We could go ahead and create more mutations, but the process would be more or less the same, just as we saw with the other queries. There isn’t too much overhead with GraphQL.

You just saw how to get started with GraphQL in a Golang application. We didn’t use a database for this example, but we saw how to create a data model, query it, and manipulate data via some kind of GraphQL mutation.

If you’re interested in wiring a NoSQL database to your GraphQL with Golang application, check out a previous tutorial that I wrote titled, Using GraphQL with Golang and a NoSQL Database.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

This content was originally published here.

Other FinTech Healines