Python GraphQL library leveraging modern Python features like dataclasses and type hints to create GraphQL APIs.
pip install "strawberry-graphql[debug-server]"
Create a new file app.py
:
import strawberry
@strawberry.type
class User:
name: str
age: int
@strawberry.type
class Query:
@strawberry.field
def user(self) -> User:
return User(name="Patrick", age=100)
schema = strawberry.Schema(query=Query)
Run the debug server:
strawberry server app
Visit http://0.0.0.0:8000/graphql to access GraphiQL and explore your API.
Enable static type checking with MyPy, Python's optional static type checker, by adding to your mypy.ini
:
[mypy]
plugins = strawberry.ext.mypy_plugin
Visit the MyPy documentation to learn more about Python type checking.
- Add to
INSTALLED_APPS
:
INSTALLED_APPS = [
"strawberry.django",
# ... your other apps
]
- Configure URL routing in
urls.py
:
from strawberry.django.views import GraphQLView
from .schema import schema
urlpatterns = [
path("graphql", GraphQLView.as_view(schema=schema)),
]
For GraphQL subscriptions over WebSockets:
pip install 'strawberry-graphql[debug-server]'
pip install 'uvicorn[standard]'
Strawberry provides built-in testing utilities through BaseGraphQLTestClient
. Let's look at how to set up and use different testing clients.
First, let's create a schema with test data:
import strawberry
@strawberry.type
class User:
name: str
age: int
# Setup test data
test_users = {
"123": User(name="Patrick", age=100),
"456": User(name="John", age=25),
}
@strawberry.type
class Query:
@strawberry.field
def user(self, id: str) -> User:
return test_users[id]
schema = strawberry.Schema(query=Query)
Now let's explore different ways to test this schema:
from strawberry.test import BaseGraphQLTestClient
import httpx
class HttpxTestClient(BaseGraphQLTestClient):
def __init__(self) -> None:
self.client = httpx.Client(base_url="http://localhost:8000")
def request(self, body: str, headers=None, files=None):
headers = headers or {}
response = self.client.post(
"/graphql",
json=body,
headers=headers,
files=files,
)
return response.json()
def test_query():
client = HttpxTestClient()
response = client.query(
"""
{
user(id: "123") {
name
age
}
}
"""
)
assert response.data["user"]["name"] == "Patrick"
assert not response.errors
from strawberry.test import BaseGraphQLTestClient
from requests import Session
class RequestsTestClient(BaseGraphQLTestClient):
def __init__(self) -> None:
self.client = Session()
self.client.base_url = "http://localhost:8000"
def request(self, body: str, headers=None, files=None):
headers = headers or {}
response = self.client.post(
f"{self.client.base_url}/graphql",
json=body,
headers=headers,
files=files,
)
return response.json()
def test_query_with_variables():
client = RequestsTestClient()
response = client.query(
"""
query GetUser($id: ID!) {
user(id: $id) {
name
age
}
}
""",
variables={"id": "123"},
)
assert response.data["user"]["name"] == "Patrick"
assert not response.errors
from strawberry.test import BaseGraphQLTestClient
import aiohttp
import asyncio
class AiohttpTestClient(BaseGraphQLTestClient):
def __init__(self) -> None:
self.base_url = "http://localhost:8000"
async def async_request(self, body: str, headers=None, files=None):
headers = headers or {}
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/graphql",
json=body,
headers=headers,
) as response:
return await response.json()
def request(self, body: str, headers=None, files=None):
return asyncio.run(self.async_request(body, headers, files))
def test_async_query():
client = AiohttpTestClient()
response = client.query(
"""
{
user(id: "123") {
name
age
}
}
"""
)
assert response.data["user"]["name"] == "Patrick"
assert not response.errors
- Official Examples Repository
- Full-stack Demo (Starlette + SQLAlchemy + TypeScript + Next.js)
- Quart Integration Tutorial
git clone https://github.com/strawberry-graphql/strawberry
cd strawberry
poetry install --with integrations
poetry run pytest
pre-commit install
- Documentation: https://strawberry.rocks
- GitHub Repository: https://github.com/strawberry-graphql/strawberry
- Issue Tracker: https://github.com/strawberry-graphql/strawberry/issues
- Discord Community: Join our active community on Discord for real-time discussions, questions, and support
- Security Issues: Contact [email protected] directly
This project is licensed under the MIT License - see the LICENSE file for details.