Convert Figma logo to code with AI

graphql-python logographene

GraphQL framework for Python

8,058
823
8,058
113

Top Related Projects

1,528

A GraphQL client in Python

A GraphQL library for Python that leverages type annotations 🍓

2,187

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

Adds GraphQL support to your Flask application.

Quick Overview

Graphene is a Python library for building GraphQL APIs. It provides a simple yet powerful framework to define schemas, resolve queries, and handle mutations, making it easier for developers to create GraphQL servers in Python applications.

Pros

  • Easy to integrate with popular Python web frameworks like Django, Flask, and FastAPI
  • Supports automatic schema generation from SQLAlchemy and Django ORM models
  • Provides a clean and intuitive API for defining GraphQL types and fields
  • Offers built-in support for relay-style pagination and connections

Cons

  • Documentation can be outdated or incomplete in some areas
  • Performance can be a concern for complex queries or large datasets
  • Limited built-in support for real-time subscriptions
  • Steeper learning curve compared to REST API development for developers new to GraphQL

Code Examples

  1. Defining a simple GraphQL schema:
import graphene

class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="World"))

    def resolve_hello(self, info, name):
        return f"Hello {name}!"

schema = graphene.Schema(query=Query)
  1. Creating a mutation:
class CreateUser(graphene.Mutation):
    class Arguments:
        name = graphene.String()
        email = graphene.String()

    user = graphene.Field(lambda: User)

    def mutate(self, info, name, email):
        user = User(name=name, email=email)
        return CreateUser(user=user)

class Mutation(graphene.ObjectType):
    create_user = CreateUser.Field()
  1. Integrating with Django:
from graphene_django import DjangoObjectType

class BookType(DjangoObjectType):
    class Meta:
        model = Book
        fields = ("id", "title", "author")

class Query(graphene.ObjectType):
    books = graphene.List(BookType)

    def resolve_books(self, info):
        return Book.objects.all()

Getting Started

To get started with Graphene, follow these steps:

  1. Install Graphene:

    pip install graphene
    
  2. Create a simple schema:

    import graphene
    
    class Query(graphene.ObjectType):
        hello = graphene.String()
    
        def resolve_hello(self, info):
            return "Hello, Graphene!"
    
    schema = graphene.Schema(query=Query)
    
  3. Execute a query:

    result = schema.execute('{ hello }')
    print(result.data['hello'])  # Output: Hello, Graphene!
    

For more advanced usage and integration with web frameworks, refer to the official Graphene documentation.

Competitor Comparisons

1,528

A GraphQL client in Python

Pros of gql

  • More lightweight and focused solely on client-side GraphQL operations
  • Supports async/await syntax for easier asynchronous programming
  • Better integration with external GraphQL APIs and services

Cons of gql

  • Less comprehensive than Graphene, lacking server-side schema definition capabilities
  • Smaller community and ecosystem compared to Graphene
  • Limited built-in tools for testing and debugging GraphQL queries

Code Comparison

gql:

from gql import gql, Client

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

Graphene:

import graphene

class Continent(graphene.ObjectType):
    code = graphene.String()
    name = graphene.String()

class Query(graphene.ObjectType):
    continents = graphene.List(Continent)

    def resolve_continents(self, info):
        return [Continent(code="EU", name="Europe")]

schema = graphene.Schema(query=Query)

The code examples illustrate the different focus of each library. gql is designed for client-side operations, making API requests to a GraphQL server. Graphene, on the other hand, is used to define GraphQL schemas and resolvers on the server-side.

A GraphQL library for Python that leverages type annotations 🍓

Pros of Strawberry

  • Type-first approach with Python 3.6+ type hints, leading to cleaner and more intuitive code
  • Built-in support for asynchronous resolvers, making it easier to work with async code
  • Extensive plugin system for customizing behavior and extending functionality

Cons of Strawberry

  • Newer project with a smaller community and ecosystem compared to Graphene
  • Steeper learning curve for developers not familiar with Python's type hinting system
  • Limited backward compatibility with older Python versions

Code Comparison

Strawberry:

import strawberry

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

@strawberry.type
class Query:
    @strawberry.field
    def user(self) -> User:
        return User(name="John", age=30)

Graphene:

import graphene

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

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

    def resolve_user(self, info):
        return User(name="John", age=30)

The code comparison demonstrates Strawberry's use of type hints and decorators, resulting in more concise and readable code compared to Graphene's class-based approach.

2,187

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

Pros of Ariadne

  • Schema-first approach, allowing for better separation of concerns
  • Easier integration with existing Python code and frameworks
  • More flexible and customizable resolver implementation

Cons of Ariadne

  • Less mature ecosystem compared to Graphene
  • Fewer built-in tools and integrations
  • Steeper learning curve for developers new to GraphQL

Code Comparison

Ariadne:

from ariadne import QueryType, make_executable_schema

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

query = QueryType()

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

schema = make_executable_schema(type_defs, query)

Graphene:

import graphene

class Query(graphene.ObjectType):
    hello = graphene.String()

    def resolve_hello(self, info):
        return "Hello, world!"

schema = graphene.Schema(query=Query)

Both Ariadne and Graphene are popular Python libraries for building GraphQL APIs, but they differ in their approach and implementation. Ariadne follows a schema-first approach, which can lead to cleaner code separation and easier integration with existing Python projects. However, Graphene's code-first approach may be more familiar to developers coming from traditional Python backgrounds. The choice between the two often depends on project requirements and team preferences.

Adds GraphQL support to your Flask application.

Pros of flask-graphql

  • Specifically designed for Flask integration, offering seamless compatibility
  • Lightweight and focused on Flask-specific GraphQL implementation
  • Easier setup for Flask developers already familiar with the framework

Cons of flask-graphql

  • Limited to Flask applications, less versatile for other frameworks
  • Smaller community and fewer resources compared to Graphene
  • Less frequent updates and maintenance

Code Comparison

flask-graphql:

from flask import Flask
from flask_graphql import GraphQLView

app = Flask(__name__)
app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True))

Graphene:

from flask import Flask
from graphene import ObjectType, String, Schema

class Query(ObjectType):
    hello = String(name=String(default_value="World"))
    def resolve_hello(self, info, name):
        return f'Hello {name}!'

schema = Schema(query=Query)

Summary

While flask-graphql offers a more streamlined experience for Flask developers, Graphene provides a more versatile and widely-supported solution for GraphQL implementation in Python. Graphene's larger community and broader framework support make it a more robust choice for complex projects, while flask-graphql excels in simplicity for Flask-specific applications.

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

Graphene Logo Graphene PyPI version Coverage Status

💬 Join the community on Discord

We are looking for contributors! Please check the current issues to see how you can help ❤️

Introduction

Graphene is an opinionated Python library for building GraphQL schemas/types fast and easily.

  • Easy to use: Graphene helps you use GraphQL in Python without effort.
  • Relay: Graphene has builtin support for Relay.
  • Data agnostic: Graphene supports any kind of data source: SQL (Django, SQLAlchemy), Mongo, custom Python objects, etc. We believe that by providing a complete API you could plug Graphene anywhere your data lives and make your data available through GraphQL.

Integrations

Graphene has multiple integrations with different frameworks:

integrationPackage
SQLAlchemygraphene-sqlalchemy
Mongographene-mongo
Apollo Federationgraphene-federation
Djangographene-django

Also, Graphene is fully compatible with the GraphQL spec, working seamlessly with all GraphQL clients, such as Relay, Apollo and gql.

Installation

To install graphene, just run this command in your shell

pip install "graphene>=3.1"

Examples

Here is one example for you to get started:

import graphene

class Query(graphene.ObjectType):
    hello = graphene.String(description='A typical hello world')

    def resolve_hello(self, info):
        return 'World'

schema = graphene.Schema(query=Query)

Then Querying graphene.Schema is as simple as:

query = '''
    query SayHello {
      hello
    }
'''
result = schema.execute(query)

If you want to learn even more, you can also check the following examples:

Documentation

Documentation and links to additional resources are available at https://docs.graphene-python.org/en/latest/

Contributing

After cloning this repo, create a virtualenv and ensure dependencies are installed by running:

virtualenv venv
source venv/bin/activate
pip install -e ".[test]"

Well-written tests and maintaining good test coverage is important to this project. While developing, run new and existing tests with:

pytest graphene/relay/tests/test_node.py # Single file
pytest graphene/relay # All tests in directory

Add the -s flag if you have introduced breakpoints into the code for debugging. Add the -v ("verbose") flag to get more detailed test output. For even more detailed output, use -vv. Check out the pytest documentation for more options and test running controls.

Regularly ensure your pre-commit hooks are up to date and enabled:

pre-commit install

You can also run the benchmarks with:

pytest graphene --benchmark-only

Graphene supports several versions of Python. To make sure that changes do not break compatibility with any of those versions, we use tox to create virtualenvs for each Python version and run tests with that version. To run against all Python versions defined in the tox.ini config file, just run:

tox

If you wish to run against a specific version defined in the tox.ini file:

tox -e py39

Tox can only use whatever versions of Python are installed on your system. When you create a pull request, GitHub Actions pipelines will also be running the same tests and report the results, so there is no need for potential contributors to try to install every single version of Python on their own system ahead of time. We appreciate opening issues and pull requests to make graphene even more stable & useful!

Building Documentation

The documentation is generated using the excellent Sphinx and a custom theme.

An HTML version of the documentation is produced by running:

make docs