graphql-python/gql

Any best practice using async gql with FastAPI?

PaleNeutron opened this issue · 2 comments

I am really confused about lifecycle of client and session in an async web server.

Should I create a new session for every new request?

from fastapi import Depends, FastAPI
from gql import Client, gql
from gql.transport.aiohttp import AIOHTTPTransport

# Select your transport with a defined url endpoint
transport = AIOHTTPTransport(url="https://countries.trevorblades.com/")

# Create a GraphQL client using the defined transport
client = Client(transport=transport, fetch_schema_from_transport=True)

app = FastAPI()


@app.get("/items/")
async def read_items():
    # Provide a GraphQL query
    query = gql(
        """
        query getContinents {
          continents {
            code
            name
          }
        }
    """
    )

    result = await client.async_execute(query)
    return result 
$ uvicorn main:app --reload --port 8888

Check out the FastAPI example using a permanent session in the gql documentation.

Thanks, it works well now!