I'm following along with this tutorial by Bradford Lamson-Scribner to make this simple API.
First I created a base template for the project. Following the structure that Bradford Lamson-Scribner set in his tutorial. I've made only a couple of minor changes to the structure.
├── gql
│ ├── gql.go
│ ├── queries.go
│ ├── resolvers.go
│ └── types.go
├── main.go
├── db
│ └── postgres.go
└── server
└── server.go
I found a great article by Syed Komail Abbas that goes into detail to get started with a docker container with postgres db running in it.
To pull the latest docker image of postgres simply run
docker pull postgres
If you want persistant data generated by the Postgres instance, we need to map a local directory as a data volume for the container.
mkdir -p $HOME/docker/volumes/postgres
To start the postgres container simply run
docker run --rm --name pg-docker -e POSTGRES_PASSWORD=docker -d -p 5432:5432 -v $HOME/docker/volumes/postgres:/var/lib/postgresql/data postgres
Once the container is up and running, connecting to it from an application is no different than connecting to a Postgres instance running outside a docker container.
psql -h localhost -U postgres -d postgres
We need to setup a database and some mocked data to test the API against. Run psql
to enter the Postgres console and we'll create a database.
After connecting to the Postgres container run
CREATE DATABASE go_graphql_db;
Then we'll connect to the new database that we created.
\c go_graphql_db;
Once the database is created, go ahead and populate the database with some mock data.
CREATE TABLE users (
id serial PRIMARY KEY,
name VARCHAR (50) NOT NULL,
age INT NOT NULL,
profession VARCHAR (50) NOT NULL,
friendly BOOLEAN NOT NULL
);
INSERT INTO users VALUES
(1, 'kevin', 35, 'waiter', true),
(2, 'angela', 21, 'concierge', true),
(3, 'alex', 26, 'zoo keeper', false),
(4, 'becky', 67, 'retired', false),
(5, 'kevin', 15, 'in school', true),
(6, 'frankie', 45, 'teller', true);
See this tutorial to get the code for the api.
There are some great tools for exploring your GraphQL API like graphiql, Insomnia, and graphql-playground. You can also just make a POST request sending over a raw application/json body like this:
{
"query": "{users(name:\"kevin\"){id, name, age}}"
}