Overview
We've got a better understanding of how GraphQL works; now it's time to implement it!
Strawberry
GraphQL by itself is a specification, a query language for APIs. To implement GraphQL in a server, we typically use a GraphQL framework.
For example, if you're a JavaScript/TypeScript developer, you might use Apollo Server.
In the Python ecosystem, we can use Strawberry, a GraphQL library developed and maintained by the Strawberry team. Here's how they introduce themselves:
Strawberry is a developer friendly GraphQL library for Python, designed for modern development.
Setting up Strawberry with FastAPI
From your project directory, open up a new terminal. Let's install Strawberry using pip.
pip install strawberry-graphql
Note: Make sure that you've activated the .venv
virtual environment we created in the first lesson.
Next, open up main.py
in the root of the repo. Currently, it's set up to return a simple "Hello, world!" message from the root of where the server is running (which by default is http://localhost:8000).
from fastapi import FastAPIapp = FastAPI()@app.get("/")async def hello_world():return {"message": "Hello World"}
Let's replace this with a GraphQL endpoint, using Strawberry's GraphQLRouter
with FastAPI.
First, we'll import the package at the top of main.py
.
from strawberry.fastapi import GraphQLRouter
The GraphQLRouter
is a FastAPI router that serves as a GraphQL endpoint. It takes in a schema, a path, and optionally a GraphQL IDE.
Let's create an instance of GraphQLRouter
below our initialization of app
.
graphql_router = GraphQLRouter(..., path="/", graphql_ide="apollo-sandbox")
We'll use ...
as a placeholder for the schema we'll define in the next lesson.
We're also setting the path to the root /
and the GraphQL IDE to apollo-sandbox
. We'll play with Sandbox later in the course.
Finally, we'll include graphql_router
in our FastAPI app using app.include_router
.
app.include_router(graphql_router)
Let's also remove the hello_world
route; we don't need it anymore.
- @app.get("/")- async def hello_world():- return {"message": "Hello World"}
Key takeaways
- Strawberry is a Python library for building GraphQL APIs using type annotations.
- Strawberry provides an integration with FastAPI that serves as a GraphQL endpoint.
Up next
Our GraphQL server is on standby, awaiting a schema. We'll give it what it wants in the next lesson!
Share your questions and comments about this lesson
This course is currently in
You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.