• author: Monkhaus

How to use GraphQL with Python

In this article, we'll be discussing how to use GraphQL with Python. While GraphQL has been around for a while, it is increasingly becoming a popular choice for developing APIs. We'll be using the Strawberry library to explore GraphQL in Python.

Why Use GraphQL?

Before we dive into the code, let's briefly discuss why you might want to use GraphQL in your API development. Traditionally, APIs would require the client to make multiple requests to retrieve data. With GraphQL, a client can make a single request for specifically requested data, reducing unnecessary data transfer.

Installation and Setup

Assuming you already have Python 3.6+ installed, we can use the Windows subsystem for Linux to set up our environment. First, we'll install the required libraries by running pip install fastapi uvicorn strawberry-graphql httpx.
Next, we'll create a new file called main.py.

Defining a GraphQL Type

We'll start by defining a class called the Movie class, which represents our data objects. This class includes a title and director field.


Defining a Query Class

Next, we define the root of our GraphQL schema. This is the Query class that allows us to interact with our API. We create an endpoint called "movies" that returns data from our Movie class.

fromtypingimportList@strawberry.typeclassQuery:@strawberry.fielddefmovies()->List[Movie]:return[Movie(title="Star Wars",director="George Lucas"),Movie(title="The Matrix",director="Lana Wachowski")]schema=strawberry.Schema(query=Query)

Setting up our FastAPI Application and Endpoints

With our schema defined, we can now create a FastAPI application and define our endpoints.

fromfastapiimportFastAPIapp=FastAPI()@app.get("/")defread_root():return{"Welcome":"to the GraphQL API"}@app.post("/graphql")asyncdefgraphql(query:str):result=awaitschema.execute_async(query)ifresult.errors:return{"errors":[str(x)forxinresult.errors]}return{"data":result.data}

Running the Server and Querying the API

We can now run our server using the command uvicorn main:app --reload. Once the server is running, we can query our API using an HTTP client such as HTTPx or through the GraphQL web interface.

importhttpxasyncwithhttpx.AsyncClient()asclient:query="""    query {        movies {            title            director        }    }    """response=awaitclient.post("http://localhost:8000/graphql",json={"query":query})print(response.json())

With the httpx client, we can specify which data fields we want to retrieve by adding them to the query string. The above query retrieves the title and director fields for each movie.


By using GraphQL with Python, we can quickly build a flexible and efficient API. While the example given here is simple, you can use Strawberry and FastAPI to build complex APIs and handle more complex data structures. If you have any questions or want to learn more, let us know!

Previous Post

Implementing Rate Limiting with Fast API

Next Post

What to Do with a Setup.pi File: A Tutorial

About The auther

New Posts

Popular Post