Skip to content

Instantly share code, notes, and snippets.

@lamoboos223
Last active April 1, 2024 02:46
Show Gist options
  • Save lamoboos223/e5f766c4f088e3fe40eacc4a4d70241c to your computer and use it in GitHub Desktop.
Save lamoboos223/e5f766c4f088e3fe40eacc4a4d70241c to your computer and use it in GitHub Desktop.
from flask import Flask, request
from graphene import ObjectType, String, Schema, List, Field
'''
Pre-requesities: python3 -m pip install graphene flask
USAGE: open Postman and create new QraphQL request then paste this url: http://localhost:5000/graphql and these Queries ...
- to get all the books:
query {
books {
title
author
}
}
- to get one book by id:
query {
bookById (id: "123") {
title
author
}
}
- to get all the products:
query {
products{
title
author
}
}
'''
app = Flask(__name__)
# Define a DTO
class Item(ObjectType):
title = String()
author = String()
# Define a query class
class Query(ObjectType):
products = List(Item)
books = List(Item)
bookById = Field(Item, id=String())
def resolve_products(self, info):
# Return a list of products
return [
Item(title="product 1", author="Author 1"),
Item(title="product 2", author="Author 2"),
Item(title="product 3", author="Author 3")
]
def resolve_books(self, info):
# Return a list of books
return [
Item(title="Book 1", author="Author 1"),
Item(title="Book 2", author="Author 2"),
Item(title="Book 3", author="Author 3")
]
def resolve_bookById(self, info, id):
return Item(title=f"Book {id}", author=f"Author {id}")
# Create a schema
schema = Schema(query=Query)
# Define the GraphQL endpoint
@app.route("/graphql", methods=["POST"])
def graphql():
# Get the GraphQL query from the request body
query = request.get_json()["query"]
# Execute the query
result = schema.execute(query)
# Return the query result
return {"data": result.data}
if __name__ == "__main__":
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment