Strawberry GraphQL
Strawberry GraphQL is a modern Python library for creating GraphQL APIs that leverages type annotations and dataclasses. It follows a code-first philosophy, providing type safety, async/await support, and first-class integrations with popular web frameworks like FastAPI and Django. It aims to stay close to the GraphQL specification while offering a developer-friendly experience. Currently at version 0.314.3, it has an active development cycle with frequent releases. [1, 3, 4, 7, 12, 14, 15, 20]
Warnings
- breaking In `v0.243.0`, support for GraphQL multipart file uploads was disabled by default, requiring explicit opt-in. Additionally, Django CSRF protection became enabled by default for Strawberry Django views, requiring the `csrf_exempt` decorator if previous behavior is desired. [2]
- breaking In `v0.268.0`, the generated GraphQL schema type for `GlobalID` (when using `relay.Node`) was changed to `ID`. While runtime behavior is unaffected, schema introspection will now report `ID` instead of `GlobalID`. [6]
- deprecated In `v0.213.0`, the `graphiql` parameter used in HTTP integration views (e.g., `GraphQLView` for FastAPI, Flask, Django) was deprecated and replaced by `graphql_ide`. [11]
- breaking The `types` parameter in `strawberry.union()` was deprecated in `v0.191.0` and completely removed in `v0.312.0`. [5]
- gotcha The `strawberry.ext.mypy_plugin` has seen significant changes across versions. It was removed in `v0.269.0` (as it was no longer needed due to `@dataclass_transform`) but partially restored in `v0.310.2` to support experimental Pydantic types. Relying on its specific behavior or even its presence can be inconsistent. [5]
Install
-
pip install strawberry-graphql -
pip install "strawberry-graphql[cli]" -
pip install "strawberry-graphql[fastapi]" -
pip install "strawberry-graphql[django]"
Imports
- strawberry.type
import strawberry @strawberry.type
- strawberry.field
import strawberry @strawberry.field
- strawberry.Schema
import strawberry schema = strawberry.Schema(query=Query)
- strawberry.ID
import strawberry id: strawberry.ID
- strawberry.lazy
from typing import TYPE_CHECKING, Annotated, List import strawberry if TYPE_CHECKING: from .posts import Post posts: List[Annotated["Post", strawberry.lazy(".posts")]] - strawberry.ext.mypy_plugin
The plugin is now less critical or has changed, review mypy.ini.
Quickstart
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)
# To run this example locally:
# 1. Install with `pip install "strawberry-graphql[cli]"`
# 2. Save the code above as `app.py`
# 3. Run `strawberry dev app` in your terminal.
# 4. Access the GraphiQL interface at http://0.0.0.0:8000/graphql in your browser.