This is a simple GraphQL API written in Go that allows you to query and mutate (add) a list of books. The server exposes a /graphql endpoint, where you can interact with the data using GraphQL queries and mutations.
- Query the list of books or a single book by its
id. - Mutate the list of books by adding a new book.
- Written in Go using the
graphql-gopackage.
Follow these steps to set up and run the project locally.
Make sure you have the following installed:
-
Clone the repository:
git clone https://github.com/yourusername/go-graphql-books-api.git cd go-graphql-books-api -
Install dependencies:
go mod tidy
To start the GraphQL API server, run the following command:
go run main.goThe server will start and listen on http://localhost:8080/graphql.
You can send POST requests to http://localhost:8080/graphql with a GraphQL query in the request body. Below are some example queries and mutations.
{
books {
id
title
author
publishedYear
}
}Response:
{
"data": {
"books": [
{"id": "1", "title": "1984", "author": "George Orwell", "publishedYear": 1949},
{"id": "2", "title": "To Kill a Mockingbird", "author": "Harper Lee", "publishedYear": 1960},
{"id": "3", "title": "The Catcher in the Rye", "author": "J. D. Salinger", "publishedYear": 1951},
{"id": "4", "title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "publishedYear": 1925}
]
}
}{
book(id: "2") {
title
author
publishedYear
}
}Response:
{
"data": {
"book": {
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"publishedYear": 1960
}
}
}mutation {
addBook(title: "Brave New World", author: "Aldous Huxley", publishedYear: 1932) {
id
title
author
publishedYear
}
}Response:
{
"data": {
"addBook": {
"id": "5",
"title": "Brave New World",
"author": "Aldous Huxley",
"publishedYear": 1932
}
}
}You can also interact with the API using curl. Here's an example:
curl -X POST http://localhost:8080/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ books { id title author publishedYear } }"}'You can test the API using tools like:
- GraphQL Playground: Open http://localhost:8080/graphql and interact with the API via a GraphQL Playground interface.
- Postman: Create a POST request to
http://localhost:8080/graphqlwith the GraphQL query as the body.
main.go: The main entry point for the application, where the server is initialized and GraphQL schema is defined.books: A mock list of books used for querying and mutation.graphql-go: The package used for defining GraphQL types, queries, mutations, and executing the queries.
This project is licensed under the MIT License - see the LICENSE file for details.
Feel free to fork this repository and create pull requests. Contributions are welcome!
For more information on GraphQL, you can visit the official GraphQL website.