Example taken from https://strawberry.rocks/docs/general/subscriptions + integration with fastapi and uvicorn
import asyncio
from typing import AsyncGenerator
from fastapi import FastAPI, Depends, Request, Response
import strawberry
from strawberry.fastapi import BaseContext, GraphQLRouter
from strawberry.subscriptions import GRAPHQL_TRANSPORT_WS_PROTOCOL, GRAPHQL_WS_PROTOCOL
@strawberry.type
class Query:
@strawberry.field
def hello(self) -> str:
return "world"
@strawberry.type
class Subscription:
@strawberry.subscription
async def count(self, target: int = 100) -> AsyncGenerator[int, None]:
for i in range(target):
yield i
await asyncio.sleep(0.5)
schema = strawberry.Schema(query=Query, subscription=Subscription)
graphql_app = GraphQLRouter(
schema,
subscription_protocols=[
GRAPHQL_TRANSPORT_WS_PROTOCOL,
GRAPHQL_WS_PROTOCOL,
],
)
app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")
Running via (in a Docker container): uvicorn app:app --host 0.0.0.0 --port 8080
Getting the following exception:
Cannot return null for non-nullable field Subscription.count.
GraphQL request:2:3
1 | subscription {
2 | count(target: 5)
| ^
3 | }
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/graphql/execution/execute.py", line 540, in execute_field
completed = self.complete_value(
^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/graphql/execution/execute.py", line 620, in complete_value
raise TypeError(
TypeError: Cannot return null for non-nullable field Subscription.count.
python:3.11-slim-bullseye
'fastapi==0.101.1',
'uvicorn[standard]==0.23.2',
'strawberry-graphql[fastapi]==0.203.3'
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too