Develop a Todo GraphQL Server in Golang 🔥
Tags: go, graphql, webdev
Published: 2022-07-05 07:45:44

## Introduction
This is a simple Todo application developed in Golang using GraphQL. This tutorial helps you to find the right way for building your own GraphQL Server implementation in Go.

[Click here](https://github.com/rahul-yr/learn-go-graphql) to access full source code

[Click here](https://www.postman.com/rahul-public/workspace/learn-go-graphql-todo-app) to access the Postman collections. 

In this tutorial we will focus mainly on 3 things
- It's beginner friendly.
- Focused on industry best practices.
- Deploy to the cloud.

The scope of this tutorial is to focus mostly on building graphQL servers rather than Go basics. If you're completely new to Golang, I would highly encourage you to have a strong knowledge on Go basics before going into this article.

## What is GraphQL ?
GraphQL is created by Facebook, implemented in their mobile app in 2012 and open-sourced in 2015.

GraphQL is a query language and server-side runtime for APIs. GraphQL provides a flexible and intuitive syntax that enables clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time. 

As an alternative to REST, GraphQL lets developers construct requests that pull data from multiple data sources in a single API call. Therefore reducing the network calls and bandwidth that saves the battery life and CPU cycles consumed by the backend applications ([Official source](https://graphql.org/)). 

Additionally, GraphQL gives API maintainers the flexibility to add or deprecate fields without impacting existing queries. 

GraphQL is rapidly becoming the standard for API-based data access.
## What is Schemas ?
API developers create GraphQL schema that describes all the possible data that clients can query through that service. GraphQL schema is made up of object types, which defines the kind of object you can request and the fields it has. 

The most common operations on any GraphQL APIs are `Queries` and `Mutations`. `Queries` is used for reading data from APIs. `Mutations` are used for Create, Update and Delete operations.

Each operation in GraphQL schema is attached to a function called `resolvers`. A `resolver` is used to perform the actual execution of `Query` or `Mutation`.

## Live Demo
[Use this endpoint to perform live test](https://learn-go-graphql.herokuapp.com/todo)

{% embed https://youtu.be/5cvnsjQHwYQ %}

## Develop a GraphQL Server in Go
- Open your favorite code editor and create a go module using this `go mod init github.com/rahul-yr/learn-go-graphql` command.
- Install the below modules.

{% embed https://gist.github.com/rahul-yr/3f115c0e70889fac57af743202719ef7 %}
- Create a folder named `todo` in the root directory and 3 files named `todo/models.go`, `todo/schema.go` and `todo/udf.go`
- Create a Todo model in the `todo/models.go` file. This model represents the todo item.

{% embed https://gist.github.com/rahul-yr/4f661f732232bb37cd7506b40329e508 %}
### Implement CRUD operations.
- Let's create the CRUD operations for the TODO model(`todo/udf.go`). 

{% embed https://gist.github.com/rahul-yr/658c54b9698c698f742bd463834f392b %}
- The above snippet has 5 functions defined 2 for `Queries` and 3 for `Mutations`. As well as a variable to store all the todo items(you could use a database instance here).
- `GetTodos()` method is used for fetching all the todo items.
- `GetTodo(id int)` method is used for fetching a todo item based on item id.
-  `AddTodo(title string)` method is used for creating a new todo item.
- `UpdateTodo(id int, title string, completed bool)` method is used for updating the existing todo item based on item id.
- `DeleteTodo(id int)` method is used for deleting the todo item based on item id.

### Implement GraphQL schema
- Now it's finally time to create the GraphQL schema (`todo/schema.go`).

{% embed https://gist.github.com/rahul-yr/43efde290f00c722591eaa9df99ea670 %}
- GraphQL schema is implemented using this `graphql.NewSchema(graphql.SchemaConfig{...})` method. This method actually resolves the GraphQL requests.
- You could define `Queries`,`Mutations` and other `object types` using this `graphql.NewObject(graphql.Objectconfig{...})` method.
- This `graphql.Fields{...}` method is useful for defining fields.
- Below method is used for declaring input arguments.

```
graphql.FieldConfigArgument{
					"some_id": &graphql.ArgumentConfig{
						Type: graphql.SomeDataType,
					},
				}
``` 
- `Resolve` block is where actual execution happens.

### Implement an endpoint for GraphQL
- Create a route handler(`graph/router.go`) file.
- Here I have used the `gin` package. You could use any http package of your choice for creating endpoints.
- The most important part here is to add this `graphql.Do(...)` method. This actually resolves the graphql  request.

{% embed https://gist.github.com/rahul-yr/4cba688e8ccb347fc058a63ea1bfaeb4 %}
## Run the server
- Create a `main.go` file for running the graphql server.

{% embed https://gist.github.com/rahul-yr/d48615186714c6a4f663419d70e85ef7 %}
- Run the server using `go run .` command
- You can find the live [postman api collection here](https://www.postman.com/rahul-public/workspace/learn-go-graphql-todo-app). Refer this for api specifications.
- Below are the few snapshots of API requests and responses in action using Postman.

### Create a Todo item
![create-todo.PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgh3aqki80ctqc9k5be4.PNG)

### Update a Todo item
![update-todo.PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhreyaivpxzo20seqks8.PNG)

### Read a Todo item based on item id
![read-todo-by-id.PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nsg5x0050a6l2cesy10g.PNG)

### Read all Todo items
![read-all-todos.PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2mfq034pdcwf6cpvrild.PNG)

### Delete a Todo item
![delete-todo.PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/idiy1k7zd75my7wjae6y.PNG)

## Deploy to Cloud
Know how to deploy this repo to Heroku ? [Click here to find out right way](https://dev.to/rahulyr/how-to-deploy-any-backend-to-heroku-easily--22mf)

## Summary
Awesome 🔥, you have successfully completed this tutorial. I would 💝 to hear your feedback and comments on the great things you're gonna build with this. If you are struck somewhere feel free to comment. I am always available.
Please find the complete code at [github](https://github.com/rahul-yr/learn-go-graphql)