Skip to content

Latest commit

 

History

History
285 lines (206 loc) · 6.91 KB

README.md

File metadata and controls

285 lines (206 loc) · 6.91 KB

Strawberry GraphQL

Python GraphQL library leveraging modern Python features like dataclasses and type hints to create GraphQL APIs.

CircleCI Discord PyPI

Quick Start

Installation

pip install "strawberry-graphql[debug-server]"

Basic Example

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.

Features

Type Checking with MyPy

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.

Django Integration

  1. Add to INSTALLED_APPS:
INSTALLED_APPS = [
    "strawberry.django",
    # ... your other apps
]
  1. Configure URL routing in urls.py:
from strawberry.django.views import GraphQLView
from .schema import schema

urlpatterns = [
    path("graphql", GraphQLView.as_view(schema=schema)),
]

WebSocket Support

For GraphQL subscriptions over WebSockets:

pip install 'strawberry-graphql[debug-server]'
pip install 'uvicorn[standard]'

Testing

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:

1. Testing with httpx

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

2. Testing with requests

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

3. Testing with aiohttp (async)

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

Examples & Resources

Development

Setting Up Development Environment

git clone https://github.com/strawberry-graphql/strawberry
cd strawberry
poetry install --with integrations
poetry run pytest

Pre-commit Hooks

pre-commit install

Community & Support

License

This project is licensed under the MIT License - see the LICENSE file for details.

Recent Activity