A simple GraphQL API for managing books, built in Go and containerized with Docker. This project was initially learned from https://medium.com/@ferdousazad12/building-a-graphql-application-with-go-postgresql-and-docker-836db34f245c and then adapted with some changes.
Key files:
main.goschema/schema.gohandlers/book_handlers.gomodels/book.goutils/db.goconfig/config.goDockerfiledocker-compose.yml.env.example
Notable constructs:
http.HandleFunc()wires the GraphQL HTTP endpoint at /graphql.graphql.Do()executes GraphQL operations.graphql.NewSchema()builds the executable schema fromRootQueryandRootMutation.
Getting started
Prerequisites:
- Docker and Docker Compose installed
- Git
Setup and run with Docker Compose:
- Copy env file: cp .env.example .env Edit DB_USER and DB_PASSWORD as needed.
- Build and start: docker compose up --build
- GraphQL endpoint: http://localhost:8080/graphql
Environment variables
The app reads database settings from environment variables provided by Docker Compose. See docker-compose.yml and .env.example.
GraphQL schema overview
Type Book:
- id: Int
- title: String
- author: String
- publishedYear: Int
Queries:
- books: [Book]
- book(id: Int): Book
Mutations:
- createBook(title, author, publishedYear): Book
- updateBook(id, title, author, publishedYear): Book
- deleteBook(id): Book
Example operations
Query all books:
query {
books {
id
title
author
publishedYear
}
}Query a book by ID:
query {
book(id: 1) {
id
title
author
publishedYear
}
}Create a book:
mutation {
createBook(title: "Clean Code", author: "Robert C. Martin", publishedYear: 2008) {
id
title
author
publishedYear
}
}Update a book:
mutation {
updateBook(id: 1, title: "Clean Coder", author: "Robert C. Martin", publishedYear: 2011) {
id
title
author
publishedYear
}
}Delete a book:
mutation {
deleteBook(id: 1) {
id
title
}
}cURL examples
POST a query:
curl -X POST http://localhost:8080/graphql \
-H "Content-Type: application/json" \
-d '{"query":"{ books { id title author publishedYear } }"}'POST a mutation:
curl -X POST http://localhost:8080/graphql \
-H "Content-Type: application/json" \
-d '{"query":"mutation { createBook(title:\"Clean Code\", author:\"Robert C. Martin\", publishedYear:2008) { id title author publishedYear } }"}'Local development (without Docker)
Ensure a local PostgreSQL instance is running and set env vars (DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME). Then run:
go run ./main.goCredits
Based on the tutorial above and modified for learning and experimentation. See implementation points in main.go, schema/schema.go, and containerization via Dockerfile and docker-compose.yml.
thanks to Ferdous Azad for the original tutorial!, check it out at https://medium.com/@ferdousazad12/building-a-graphql-application-with-go-postgresql-and-docker-836db34f245c
happy learning! ✌️