In case you’re not familiar, GraphQL 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.
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 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:
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: