GraphQL is a powerful query language that allows developers to define their own API structure and request exactly what they need from a server. In this guide, we will walk through the steps to implement GraphQL in a Python Flask application.

Step 1: Install dependencies
First, we need to install the necessary dependencies. We will be using the flask and graphene packages for this tutorial. You can install them using pip:
pip install flask graphene
Step 2: Define the schema
Next, we need to define the schema for our GraphQL API. The schema defines the structure of the data that we can query from the server. We will create a schema.py file and define a simple schema that allows us to query for a list of books:
import graphene class Book(graphene.ObjectType): title = graphene.String() author = graphene.String() class Query(graphene.ObjectType): books = graphene.List(Book) def resolve_books(self, info): return [ Book(title='The Great Gatsby', author='F. Scott Fitzgerald'), Book(title='To Kill a Mockingbird', author='Harper Lee') ] schema = graphene.Schema(query=Query)
In this example, we define a Book object type that has two fields: title and author. We also define a Query object type that has a single field called books, which returns a list of Book objects.
Step 3: Create a Flask app
Now that we have defined our schema, we need to create a Flask application that will serve our GraphQL API. We will create a new file called app.py and define a simple Flask app:
from flask import Flask from flask_graphql import GraphQLView from schema import schema app = Flask(__name__) app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True)) if __name__ == '__main__': app.run(debug=True)
In this example, we create a new Flask app and define a single route for our GraphQL API at /graphql. We also use the GraphQLView class from the flask_graphql package to create a view that serves our GraphQL API using our schema.
Step 4: Run the app
Now that we have defined our schema and created our Flask app, we can run the app using the following command:
python app.py
This will start the Flask development server and we should see output similar to the following:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: xxx-xxx-xxx
Step 5: Test the API
Now that our app is running, we can test our GraphQL API using a tool like GraphiQL. Navigate to http://localhost:5000/graphql in your web browser to access the GraphiQL interface.
In the left-hand pane of the GraphiQL interface, enter the following query to retrieve a list of books:
{ books { title author } }
This should return the following JSON response:
{ "data": { "books": [ { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" }, { "title": "To Kill a Mockingbird", "author": "Harper Lee" } ] } }
Step 6: Add mutations
In addition to querying data from the server, GraphQL also allows us to mutate data by defining mutations in our schema. We can add mutations to our existing schema by modifying the schema.py file:
import graphene class Book(graphene.ObjectType): title = graphene.String() author = graphene.String() class CreateBook(graphene.Mutation): class Arguments: title = graphene.String() author = graphene.String() book = graphene.Field(lambda: Book) def mutate(self, info, title, author): book = Book(title=title, author=author) return CreateBook(book=book) class Query(graphene.ObjectType): books = graphene.List(Book) def resolve_books(self, info): return [ Book(title='The Great Gatsby', author='F. Scott Fitzgerald'), Book(title='To Kill a Mockingbird', author='Harper Lee') ] class Mutation(graphene.ObjectType): create_book = CreateBook.Field() schema = graphene.Schema(query=Query, mutation=Mutation)
In this example, we define a new mutation called CreateBook that allows us to create a new book with a given title and author. We also define a new Mutation object type that includes our CreateBook mutation.
Step 7: Test mutations
Now that we have defined our mutations, we can test them using the same GraphiQL interface. In the left-hand pane of the GraphiQL interface, enter the following mutation to create a new book:
mutation { createBook(title: "1984", author: "George Orwell") { book { title author } } }
This should return the following JSON response:
{ "data": { "createBook": { "book": { "title": "1984", "author": "George Orwell" } } } }
We can also query for the list of books to verify that our new book has been created:
{ books { title author } }
This should return the following JSON response:
{ "data": { "books": [ { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" }, { "title": "To Kill a Mockingbird", "author": "Harper Lee" }, { "title": "1984", "author": "George Orwell" } ] } }
Conclusion
In this tutorial, we walked through the steps to implement a GraphQL API in a Python Flask application. We defined a schema that allowed us to query and mutate data, created a Flask app that served our GraphQL API, and tested our API using the GraphiQL interface. With these tools, we can create powerful and flexible APIs that allow clients to request exactly what they need from the server.
0 Comments