Convert Figma logo to code with AI

strawberry-graphql logostrawberry

A GraphQL library for Python that leverages type annotations 🍓

3,926
516
3,926
478

Top Related Projects

GraphQL framework for Python

2,187

Python library for implementing GraphQL servers using schema-first approach.

1,528

A GraphQL client in Python

10,027

The little ASGI framework that shines. 🌟

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Quick Overview

Strawberry is a modern GraphQL library for Python that leverages type annotations. It allows developers to create GraphQL schemas using Python classes and decorators, making it intuitive and easy to use. Strawberry supports both synchronous and asynchronous code, making it versatile for various application types.

Pros

  • Strong typing support with Python type hints
  • Intuitive API using decorators and classes
  • Supports both sync and async operations
  • Integrates well with popular web frameworks like FastAPI and Django

Cons

  • Relatively new compared to other GraphQL libraries in Python
  • Documentation can be improved in some areas
  • Limited ecosystem of extensions and plugins compared to more established libraries
  • May have a steeper learning curve for developers new to GraphQL

Code Examples

  1. Defining a simple GraphQL type:
import strawberry

@strawberry.type
class User:
    name: str
    age: int
  1. Creating a query:
@strawberry.type
class Query:
    @strawberry.field
    def user(self) -> User:
        return User(name="John Doe", age=30)

schema = strawberry.Schema(query=Query)
  1. Defining a mutation:
@strawberry.type
class Mutation:
    @strawberry.mutation
    def create_user(self, name: str, age: int) -> User:
        return User(name=name, age=age)

schema = strawberry.Schema(query=Query, mutation=Mutation)

Getting Started

To get started with Strawberry, follow these steps:

  1. Install Strawberry:
pip install strawberry-graphql
  1. Create a simple schema:
import strawberry

@strawberry.type
class Query:
    @strawberry.field
    def hello(self) -> str:
        return "Hello, World!"

schema = strawberry.Schema(query=Query)
  1. Run the GraphQL server:
from strawberry.asgi import GraphQL

app = GraphQL(schema)

# Run with an ASGI server like uvicorn
# uvicorn app:app

This sets up a basic GraphQL server with a single query. You can now run the server and start exploring your GraphQL API.

Competitor Comparisons

GraphQL framework for Python

Pros of Graphene

  • More mature and widely adopted in the Python GraphQL ecosystem
  • Extensive documentation and community support
  • Flexible and supports various ORMs (SQLAlchemy, Django ORM)

Cons of Graphene

  • More verbose syntax, requiring explicit type definitions
  • Steeper learning curve for beginners
  • Less type safety compared to Strawberry's approach

Code Comparison

Graphene:

import graphene

class User(graphene.ObjectType):
    name = graphene.String()
    age = graphene.Int()

class Query(graphene.ObjectType):
    user = graphene.Field(User)

Strawberry:

import strawberry

@strawberry.type
class User:
    name: str
    age: int

@strawberry.type
class Query:
    user: User

Strawberry offers a more concise and Pythonic syntax, leveraging type hints for schema definition. Graphene, while more verbose, provides explicit type definitions that may be preferred by some developers for clarity. Strawberry's approach aligns more closely with modern Python practices and offers better type safety, while Graphene's maturity and extensive ecosystem support make it a solid choice for many projects.

2,187

Python library for implementing GraphQL servers using schema-first approach.

Pros of Ariadne

  • More flexible schema definition, allowing for both SDL and code-first approaches
  • Better integration with existing Python web frameworks like Django and Flask
  • Supports both synchronous and asynchronous execution

Cons of Ariadne

  • Less type-safe compared to Strawberry's type-based approach
  • Requires more boilerplate code for resolver definitions
  • Slightly steeper learning curve for developers new to GraphQL

Code Comparison

Ariadne schema definition:

type_defs = """
type Query {
    hello: String!
}
"""

@query.field("hello")
def resolve_hello(_, info):
    return "Hello, world!"

Strawberry schema definition:

import strawberry

@strawberry.type
class Query:
    @strawberry.field
    def hello(self) -> str:
        return "Hello, world!"

schema = strawberry.Schema(query=Query)

Both Ariadne and Strawberry are popular Python GraphQL libraries, each with its own strengths. Ariadne offers more flexibility in schema definition and better integration with existing web frameworks, while Strawberry provides a more type-safe approach with its code-first schema definition. The choice between the two depends on project requirements and developer preferences.

1,528

A GraphQL client in Python

Pros of gql

  • More mature and established project with a longer history
  • Supports both synchronous and asynchronous operations
  • Offers a wider range of features for complex GraphQL operations

Cons of gql

  • Steeper learning curve, especially for beginners
  • Less intuitive API compared to Strawberry's code-first approach
  • Requires more boilerplate code for basic operations

Code Comparison

gql:

from gql import gql, Client

client = Client(transport=transport)
query = gql('''
    query getContinents {
        continents {
            code
            name
        }
    }
''')
result = client.execute(query)

Strawberry:

import strawberry

@strawberry.type
class Continent:
    code: str
    name: str

@strawberry.type
class Query:
    @strawberry.field
    def continents(self) -> List[Continent]:
        # Implementation here

schema = strawberry.Schema(query=Query)

The code comparison shows that gql uses a more traditional string-based approach for defining queries, while Strawberry employs a code-first methodology with decorators and type annotations. This difference highlights Strawberry's focus on leveraging Python's type system for GraphQL schema definition, which can lead to improved developer experience and type safety.

10,027

The little ASGI framework that shines. 🌟

Pros of Starlette

  • More versatile: Starlette is a lightweight ASGI framework suitable for various web applications, not limited to GraphQL
  • Better performance: Designed for high-speed async operations, making it efficient for handling concurrent requests
  • Extensive middleware support: Offers a wide range of built-in middleware for common web application needs

Cons of Starlette

  • Steeper learning curve: Requires more setup and configuration compared to Strawberry's focused GraphQL approach
  • Less GraphQL-specific features: Lacks built-in GraphQL schema definition and type checking capabilities

Code Comparison

Starlette (basic route):

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
    return JSONResponse({"hello": "world"})

app = Starlette(routes=[Route("/", homepage)])

Strawberry (basic GraphQL schema):

import strawberry
from strawberry.asgi import GraphQL

@strawberry.type
class Query:
    @strawberry.field
    def hello(self) -> str:
        return "world"

schema = strawberry.Schema(query=Query)
app = GraphQL(schema)
75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • Broader scope: FastAPI is a full-featured web framework for building APIs, while Strawberry focuses specifically on GraphQL
  • Extensive documentation and larger community support
  • Built-in support for asynchronous programming and automatic API documentation

Cons of FastAPI

  • Steeper learning curve due to its broader feature set
  • Requires additional libraries for GraphQL support
  • May be overkill for projects that only need GraphQL functionality

Code Comparison

FastAPI example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Strawberry example:

import strawberry

@strawberry.type
class Query:
    @strawberry.field
    def hello(self) -> str:
        return "Hello World"

schema = strawberry.Schema(query=Query)

Both frameworks offer concise and intuitive syntax for defining endpoints or schemas. FastAPI uses decorators for route definitions, while Strawberry uses decorators for type and field definitions in GraphQL schemas. FastAPI's example shows a REST API endpoint, whereas Strawberry's example demonstrates a GraphQL schema definition.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Strawberry GraphQL

Python GraphQL library based on dataclasses

CircleCI Discord PyPI

Installation ( Quick Start )

The quick start method provides a server and CLI to get going quickly. Install with:

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

Getting Started

Create a file called app.py with the following code:

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)

This will create a GraphQL schema defining a User type and a single query field user that will return a hardcoded user.

To run the debug server run the following command:

strawberry server app

Open the debug server by clicking on the following link: http://0.0.0.0:8000/graphql

This will open GraphiQL where you can test the API.

Type-checking

Strawberry comes with a mypy plugin that enables statically type-checking your GraphQL schema. To enable it, add the following lines to your mypy.ini configuration:

[mypy]
plugins = strawberry.ext.mypy_plugin

Django Integration

A Django view is provided for adding a GraphQL endpoint to your application.

  1. Add the app to your INSTALLED_APPS.
INSTALLED_APPS = [
    ...,  # your other apps
    "strawberry.django",
]
  1. Add the view to your urls.py file.
from strawberry.django.views import GraphQLView
from .schema import schema

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

WebSockets

To support graphql Subscriptions over WebSockets you need to provide a WebSocket enabled server. The debug server can be made to support WebSockets with these commands:

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

Examples

Contributing

We use poetry to manage dependencies, to get started follow these steps:

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

For all further detail, check out the Contributing Page

Pre commit

We have a configuration for pre-commit, to add the hook run the following command:

pre-commit install

Links

Licensing

The code in this project is licensed under MIT license. See LICENSE for more information.

Recent Activity