<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jigar on Medium]]></title>
        <description><![CDATA[Stories by Jigar on Medium]]></description>
        <link>https://medium.com/@jigar_xyz?source=rss-f05f37e1d13b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uScvaAsell159Fh6YNUPaQ.png</url>
            <title>Stories by Jigar on Medium</title>
            <link>https://medium.com/@jigar_xyz?source=rss-f05f37e1d13b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:05:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jigar_xyz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a GraphQL API in Go using gqlgen]]></title>
            <link>https://medium.com/weareservian/building-a-graphql-api-in-go-using-gqlgen-f7a42eba2193?source=rss-f05f37e1d13b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a42eba2193</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[gqlgen]]></category>
            <dc:creator><![CDATA[Jigar]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 23:56:32 GMT</pubDate>
            <atom:updated>2021-04-24T05:28:50.387Z</atom:updated>
            <content:encoded><![CDATA[<p>This article demonstrates how one can leverage existing open source tools in order to rapidly develop a <a href="https://graphql.org/">GraphQL</a> API in the <a href="https://golang.org/">Go</a> programming language. We are going to use a relational database (<a href="https://www.postgresql.org/">Postgres</a>) to store data in and retrieve data from, make the whole stack runnable locally while attempting to use Go best practices.</p><p>In future posts, I will highlight how one can use <a href="https://gitlab.com/">Gitlab</a> to build, test and deploy this API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*AUVT6mNGirqbbhcoUlMRIw.png" /><figcaption>GraphQL + Golang image source <a href="https://medium.com/appointy/developing-graphql-servers-in-go-abc97dc892aa">https://medium.com/appointy/developing-graphql-servers-in-go-abc97dc892aa</a></figcaption></figure><p>GraphQL gives us a great framework to document an API contract (using <a href="https://graphql.org/learn/schema/">schema and types</a>) and <a href="https://gqlgen.com/">gqlgen</a> is a Go library that helps one <strong>generate a type-safe API server</strong> for that contract, relatively easily. You create your GraphQL schema, run gqlgen on it to auto-generate all the Go bindings and boilerplate you need, then implement your resolvers — thus implementing your API contract.</p><blockquote>Designing the API contract first and then implementing it is often referred to as schema first API development and it is a good fit for GraphQL</blockquote><p>Let’s get started!</p><h3>Step 1 — Create your GraphQL Schema</h3><p>Let’s say the root directory of your project is called my-awesome-project . Create your graphql schema file under my-awesome-project/src/cmd/go-graphql</p><p>For this blog post, I am going to use <a href="https://github.com/99designs/gqlgen/blob/v0.13.0/example/todo/schema.graphql">this</a> To Do List schema from one of gqlgens example projects. It describes queries, mutations, an input type as well as directives.</p><p>Why create the src/cmd/go-graphql path? So that in the future, if we prefer, we could use the same project for non-graphql work. For example, we could have a Go REST API for To Do items under src/cmd/go-rest or a some front-end code under src/cmd/ui , leading to a directory layout as shown below.</p><pre>my-awesome-project/<br>├── src/cmd<br>│   ├── go-graphql<br>|       ├── &lt;code for the GraphQL api&gt;<br>│   ├── go-rest<br>|       ├── &lt;code for the REST api&gt;<br>│   ├── ui<br>|       ├── &lt;code for front-end UI&gt;</pre><h3>Step 2 — Install Go, docker and docker compose</h3><ul><li>Follow steps on the Go official <a href="https://golang.org/doc/install">download and install page</a></li><li>Follow steps on the docker official <a href="https://docs.docker.com/get-docker/">install page</a></li><li>Follow steps on the docker-compose official <a href="https://docs.docker.com/compose/install/">install page</a></li></ul><h3>Step 3 — Setup Git</h3><p>Setup the <a href="https://git-scm.com/">git</a> repository. This typically involves the following steps:</p><pre>git init<br>git config user.name &quot;some_username&quot;<br>git config user.email &quot;some_email_address&quot;</pre><p>You might want to create a .gitignore file under my-awesome-project/ as well, for obvious reasons.</p><h3>Step 3 — Initialise your Go project</h3><p>In Go, this is trivial to do. Let’s initialise our project and then add its first dependency within the go-graphql sub-folder:</p><pre>cd my-awesome-project/src<br>go mod init gitlab.com/jigar_xyz/my-awesome-project<br>cd cmd/go-graphql<br>go get github.com/99designs/gqlgen<br>go run github.com/99designs/gqlgen init --verbose</pre><p>This will initialise a <a href="https://blog.golang.org/v2-go-modules">Go v2 module</a> with the name gitlab.com/jigar_xyz/my-awesome-project. This module will contain a bunch of other auto-generated files in a well defined package layout.</p><p>If you run go run server.go at this point, a Go GraphQL API server will be spun up along with a <a href="https://github.com/graphql/graphql-playground">GraphQL Playground</a> at: <a href="http://localhost:8080/">http://localhost:8080</a>. Point your browser to it and give it a go.</p><blockquote>Note: This API complies with the default schema that the gqlgen init command generates under src/cmd/go-graphql/graph/schema.graphqls. It does not yet comply with our schema under src/cmd/go-graphql/schema.graphql.</blockquote><h3>Step 4 — Generate the GraphQL server for your schema!</h3><p>First, we need to let gqlgen know where our GraphQL schema is. Modify the src/cmd/go-graphql/gqlgen.yml file and set schema to schema.graphql</p><pre>schema:<br>  - schema.graphql</pre><p>At this point, we should delete the following obsolete files:</p><ul><li>the default schema file src/cmd/go-graphql/graph/schema.graphqls</li><li>the default schema resolver file src/cmd/go-graphql/graph/schema.resolvers.go</li></ul><p>Now run the gqlgen generate command to generate Go models, resolvers and a dummy server implementation for our target schema.</p><pre>cd src/cmd/go-graphql<br>go run github.com/99designs/gqlgen generate --verbose</pre><blockquote>The gqlgen.yml file gives you a lot of control over the code generation. More on that <a href="https://gqlgen.com/config/">here</a></blockquote><p>All the GraphQL boilerplate code for your spec is now ready. If you run go run server.go and point your browser to it, then inspect the GraphQL schema, you should see our target schema.</p><figure><img alt="Target schema visible in GraphQL Playground" src="https://cdn-images-1.medium.com/max/1024/1*hqXbNIfmhhjYylDpH8REjw.png" /><figcaption>Initial GraphQL API Playground</figcaption></figure><blockquote>Note: have a look at <a href="https://gitlab.com/jigar_xyz/my-awesome-project/-/commit/ef93a139b5466e1e0eb4c3df79255d1820b5380e">this</a> commit to see what has changed under the hood. You can safely ignore the changes under the src/cmd/go-graphql/graph/generated folder — they are auto-generated files that do a lot of GraphQL specific heavy lifting, that we don’t need to worry about because of gqlgen</blockquote><h3>Step 5 — Setup implementation dependencies</h3><p>gqlgen generates some dummy resolvers that simply panic with an error message not implemented . These are in src/cmd/go-graphql/graph/schema.resolvers.go</p><p>Before we go about implementing them, lets first think about how we will implement the functionality that the resolvers expose. For example, how will we save a given to do item in the database?</p><p>It’s good practice to keep your implementations separate from where you actually need them. This helps with code re-use, enables the use different implementations for a certain feature and also helps test each implementation easily. This follows the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle of software development</a>. It also makes your code a lot more readable.</p><p>With that in mind, let’s create an interface in src/pkg/todo/todo_service.go that clearly defines <strong>what</strong> we can do with a To Do item:</p><pre>package todo<br><br>type ToDo interface {<br>   Create(text string, isDone bool)<br>}</pre><p>For now, all we can do is create to dos — we still don’t know how though.</p><p>Now, let’s create an implementation of this interface in src/pkg/postgres/todo_service.go — <strong>how</strong> do we do what the interface tells us to do?</p><pre>package postgres<br><br>import &quot;fmt&quot;<br><br>type ToDoImpl struct {<br>   Message string<br>}<br><br>func (t *ToDoImpl Create(text string, isDone bool)  {<br>   fmt.Printf(&quot;I have a message: %s\n&quot;, t.Message)<br>   panic(&quot;oops!&quot;)<br>}</pre><p>To implement an interface in Go, we just need to implement all the methods in the interface. Here, I’ve implemented the only method Create , from the ToDo interface.</p><p>I’ve also defined a ToDoImpl struct that holds the dependencies I need for this implementation to work. This is the <em>method receiver</em> for Create i.e. everything in the ToDoImpl struct is available to us in the Create method. For now, lets just assume that I need a string , the implementation simply prints that string and then panics.</p><p>Now let’s make our resolver <em>depend </em>on this interface so that we can use all the functionality that the interface provides, without worrying about how its implemented.</p><p>The src/cmd/go-graphql/graph/resolver.go file has the Resolver struct that we can use to pull the ToDo interface in</p><pre>package graph<br><br>import &quot;gitlab.com/jigar_xyz/my-awesome-project/pkg/todo&quot;<br><br>// This file will not be regenerated automatically.<br>//<br>// It serves as dependency injection for your app, add any dependencies you require here.<br><br>type Resolver struct {<br>   ToDo todo.ToDo<br>}</pre><p>Resolver is available to us in our actual resolver implementation in src/cmd/go-graphql/graph/schema.resolvers.go , thus giving us the ToDo interface to use in our resolver implementation.</p><p>We can implement on of our resolvers now, lets implement the CreateTodo resolver in src/cmd/go-graphql/graph/schema.resolvers.go:</p><pre>func (r *myMutationResolver) CreateTodo(ctx context.Context, todo model.TodoInput) (*model.Todo, error) {<br>   if todo.Done == nil {<br>      r.ToDo.Create(todo.Text, true)<br>   } else {<br>      r.ToDo.Create(todo.Text, false)<br>   }<br>   panic(fmt.Errorf(&quot;not implemented&quot;))<br>}</pre><p>Now, we just hook in the implementation we want to use for the interface, when we create the Resolver in src/cmd/go-graphql/server.go. We could any implementation of the ToDo interface we want, but we’ll use the postgres implementation for now.</p><pre>toDoService := &amp;postgres.ToDoImpl{Message: &quot;Hello!&quot;}<br>srv := handler.NewDefaultServer(<br>   generated.NewExecutableSchema(<br>      generated.Config{Resolvers: &amp;graph.Resolver{ToDo: toDoService}}))</pre><blockquote>Note: toDoService is a reference to the postgres implementation of the ToDo interface. Further, we just pass in Hello! as the string that the postgres implementation currently depends on</blockquote><p>This is what our dependency graph looks like now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*FJTuDffP36UrwRzt5aFqhg.png" /></figure><p>With this setup, we have:</p><ul><li>successfully defined <strong>what</strong> we can do with To Do items in the ToDo interface</li><li>successfully defined <strong>how</strong> we can implement the ToDo interface with one implementation</li><li>ensured that our GraphQL resolvers can work with the ToDo interface so that they’re not coupled with the implementation — we can swap out the implementation without affecting the GraphQL related code in the resolvers (perhaps because we want to move to a different database or we want to test the resolvers with a mock database implementation)</li><li>clearly defined dependencies for each layer, with dependency injection pushed all the way out, in the main server.go file</li><li>the ability to re-use the ToDo interface and/or its implementations else where in the codebase, perhaps for exposing a REST API for To Do items under src/cmd/go-rest in the future</li></ul><p>Have a look at <a href="https://gitlab.com/jigar_xyz/my-awesome-project/-/commit/cc14ed1274aa0d580c7050e600a0c9ff80439e3d">this commit</a> to review how we’ve set this all up.</p><p>Note that we have a few more packages and a corresponding repository layout as shown below</p><pre>my-awesome-project/<br>├── src<br>│   ├── cmd<br>|       ├── go-graphql<br>|           ├── &lt;code for the GraphQL api&gt;<br>│   ├── pkg<br>|       ├── todo<br>|           ├── &lt;ToDo Interface - no implementations&gt;<br>|       ├── postgres<br>|           ├── &lt;Postgres implementation of the ToDo Interface&gt;</pre><p>This resembles the repository layout explained in much more detail in this post about <a href="https://peter.bourgon.org/go-best-practices-2016/#repository-structure">Go best practices, six years in</a></p><p>Now, lets create a <a href="https://docs.docker.com/compose/">docker compose</a> definition file docker-compose.yml that we can use to quickly spin up a local postgres docker container for use in local development.</p><p>Now that we have an actual database, lets set up a database schema migration tool — this will allow us to create and maintain our database schema in code and make sure that whenever our application runs, it runs against the correct target schema. I’ll use the <a href="https://github.com/golang-migrate/migrate">golang-migrate</a> library in code to do this and I will place all our database schema creation and modification scripts under src/pkg/postgres/migrations right next to the postgres implementation. The schema creation scripts will include creation of the todo_item table, where we will store our to do items. I will also use the <a href="https://github.com/jackc/pgx/">jackc/pgx</a> postgres driver.</p><p>In the ToDo interface, I’ll add an Initialise() method so implementations can do whatever they want as part of their initialisation.</p><pre>package todo<br><br>type ToDo interface {<br>   Initialise() error<br>   Create(text string, isDone bool)<br>}</pre><p>This will allow our implementation to set up and maintain database the schema that it needs to run properly.</p><p>We implement the Initialise() method in the postgres implementation src/pkg/postgres/todo_service.go (using <a href="https://github.com/golang-migrate/migrate">golang-migrate</a>)</p><pre>func (t *ToDoImpl) Initialise() error {<br>   dbConnectionString := fmt.Sprintf(&quot;postgres://%s:%s@%s/%s?sslmode=disable&quot;, t.DbUserName, t.DbPassword, t.DbURL, t.DbName)<br>   db, err := sql.Open(&quot;pgx&quot;, dbConnectionString)<br>   if err != nil {<br>      return err<br>   }<br>   driver, err := postgres.WithInstance(db, &amp;postgres.Config{})<br>   if err != nil {<br>      return err<br>   }<br>   m, err := migrate.NewWithDatabaseInstance(&quot;file://../../pkg/postgres/migrations&quot;, t.DbName, driver)<br>   if err != nil {<br>      return err<br>   }<br>   err = m.Steps(2)<br>   if err != nil {<br>      return err<br>   }<br>   return nil<br>}</pre><p>Then we make sure to call Initialise() as soon as we create an instance of the implementation, to use in src/cmd/go-graphql/server.go</p><pre>toDoService := &amp;postgres.ToDoImpl{<br>   DbUserName: dbUserName,<br>   DbPassword: dbPassword,<br>   DbURL:      dbURL,<br>   DbName:     dbName,<br>}<br><br>err := toDoService.Initialise()<br>if err != nil {<br>   log.Fatal(err)<br>}<br><br>srv := handler.NewDefaultServer(<br>   generated.NewExecutableSchema(<br>      generated.Config{Resolvers: &amp;graph.Resolver{ToDo: toDoService}}))</pre><p>Now, we have:</p><ul><li>a postgres database we can run locally</li><li>the database schema for our application</li><li>a database schema migration tool that will run whenever our application starts, set up the database with our schema (apply any updates to the schema, in case there are any updates to it) and ensure that our application only runs if the database schema requirements are met</li></ul><p>If we run the following steps in order, we will have a self bootstrapped application that will run locally with the current implementation:</p><pre>cd my-awesome-project<br>docker-compose up<br>cd src/cmd/go-graphql<br>POSTGRES_USER=graphql_api POSTGRES_PASSWORD=_please_change_me_now_ POSTGRES_URL=localhost POSTGRES_DB=graphql go run server.go</pre><blockquote>Note: the POSTGRES_* environment variables correspond to those in docker-compose.yml</blockquote><p>Check out <a href="https://gitlab.com/jigar_xyz/my-awesome-project/-/commit/95002147741d8608046b5d635bcc62f0298b1f6e">this commit</a> to see how this is all set up.</p><h3>Step 6 — Implement our GraphQL resolvers</h3><p>Implementing all the resolver methods now is pretty trivial. Feel free to take a look at the various commits in the git repository. Here are some notable changes:</p><ul><li><a href="https://gitlab.com/jigar_xyz/my-awesome-project/-/commit/548ffa0aa4f3e2bd44237368a66853fe20984925">here</a> we implement our first resolver — the create to do item resolver. Note the changes in our database schema and in the Initialise() method of the postgres implementation — where we check the schema version and run database migrations <strong>explicitly</strong> by setting a targetSchemaVersion</li><li><a href="https://gitlab.com/jigar_xyz/my-awesome-project/-/commit/f61e1d08863179a8f2cf6867674832d6192d29ca">here</a> we change a mutation in our GraphQL schema updateTodo(id: ID!, changes: Map!): Todo to updateTodo(id: ID!, updatedTodo: TodoInput!): Todo! because we want the full ToDoInput when updating a to do item, instead of relying on just a Map . Because our GraphQL schema changed, I ran go run github.com/99designs/gqlgen generate --verbose again to reflect the change in generated code</li><li><a href="https://gitlab.com/jigar_xyz/my-awesome-project/-/commit/732534b81f993eabea1e8c29e62bb01def7e293f">here</a> we added a struct next to the ToDo interface definition, because we want to use it to represent a ToDo item we get from the database. Our implementations will need to return this struct which will be used wherever the Get(id string) (*ToDoItem, error) method is used. It is good practice to keep all structs used by an interface in the same file as the interface itself —everything to do with the interface is all in one place</li></ul><p>Now that we’ve implemented our resolvers, we’re ready to run the API locally and play around with it a little bit.</p><pre>cd my-awesome-project<br>docker-compose up<br>cd src/cmd/go-graphql<br>POSTGRES_USER=graphql_api POSTGRES_PASSWORD=_please_change_me_now_ POSTGRES_URL=localhost POSTGRES_DB=graphql go run server.go</pre><p>The console log prints</p><pre>2020/10/09 11:20:18 Target database schema version is: 2 and current database schema version is: -1<br>2020/10/09 11:20:18 Migrating database schema from version: -1 to version 2<br>2020/10/09 11:20:18 connect to <a href="http://localhost:8080/">http://localhost:8080/</a> for GraphQL playground</pre><p>Great, our database is up and running with everything set up. Our resolvers should work as expected now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*De_TNzuXk7D7fuLajpWy7g.png" /><figcaption>Create a To Do</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_oEDkit72JnpDRTepGUWA.png" /><figcaption>Get To Do items</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvIebyxMN2ssqYYXC16PrQ.png" /><figcaption>todo_item table in the database</figcaption></figure><h3>Step 7 — Implement our directives</h3><p>Our GraphQL schema has a couple of directives we still need to implement</p><pre>directive @hasRole(role: Role!) on FIELD_DEFINITION<br>directive @user(id: ID!) on MUTATION | QUERY | FIELD</pre><p>The field definition for the done field on the ToDo type in our schema is associated with the @hasRole directive</p><pre>type Todo {<br>    id: ID!<br>    text: String!<br>    done: Boolean! @hasRole(role: OWNER) # only the owner can see if a todo is done<br>}</pre><p>When we try to access this field without implementing the directive, we get an error as expected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKDYrgzi2tC-Wz2sjtJSGA.png" /><figcaption>Missing directive implementation</figcaption></figure><p>Implementing directives is pretty straight forward with gqlgen as explained <a href="https://gqlgen.com/reference/directives/">here</a>. Let’s implement a directive in src/cmd/go-graphql/server.go that simply prints a log message for now</p><pre>func hasRoleDirective(ctx context.Context, obj interface{}, next graphql.Resolver, role model.Role) (res interface{}, err error) {<br>   log.Printf(&quot;Inside hasRoleDirective - ignore the role check for now&quot;)<br>   return next(ctx)<br>}</pre><p>Now, we can use this directive with our server</p><pre>config := generated.Config{Resolvers: &amp;graph.Resolver{ToDo: toDoService}}</pre><pre>config.Directives.HasRole = hasRoleDirective // referencing the method above<br><br>srv := handler.NewDefaultServer(generated.NewExecutableSchema(config))</pre><p>When we run the query again after restarting the server, we see the done field as expected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pI2diTiJGu20CSw5WdnYLA.png" /><figcaption>Directive implemented, output as expected</figcaption></figure><p>And the server logs indicate that our directive did indeed execute</p><pre>2020/10/09 12:01:07 Target database schema version is: 2 and current database schema version is: 2<br>2020/10/09 12:01:07 No database schema migrations need to be performed.<br>2020/10/09 12:01:07 connect to <a href="http://localhost:8080/">http://localhost:8080/</a> for GraphQL playground<br>2020/10/09 12:01:09 Inside hasRoleDirective - ignore the role check for now</pre><p>Check <a href="https://gitlab.com/jigar_xyz/my-awesome-project/-/commit/d61110de61a77d96f40c1e60a20673d3f8b871c2">this</a> commit to see the actual code changes.</p><p>And there you have it, the To Do list GraphQL API is up and running locally!</p><h3>Next Steps</h3><p>I encourage you to check-out/fork the <a href="https://gitlab.com/jigar_xyz/my-awesome-project">git repository</a> for this project and play around with it. Try changing the GraphQL schema and then implementing those changes in code. Or try modifying the ToDo interface and see what breaks.</p><p>And like I mentioned earlier, in future posts, I will highlight how one can use <a href="https://gitlab.com/">Gitlab</a> to build, test and deploy this API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a42eba2193" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weareservian/building-a-graphql-api-in-go-using-gqlgen-f7a42eba2193">Building a GraphQL API in Go using gqlgen</a> was originally published in <a href="https://medium.com/weareservian">Cognizant Servian</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>