Convert Figma logo to code with AI

graphql-python logogql

A GraphQL client in Python

1,528
179
1,528
11

Top Related Projects

GraphQL framework for Python

A GraphQL library for Python that leverages type annotations 🍓

2,187

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

Quick Overview

GQL is a GraphQL client library for Python. It provides a simple and intuitive way to interact with GraphQL APIs, offering both synchronous and asynchronous support. The library is designed to be flexible and can be used with various HTTP clients and WebSocket implementations.

Pros

  • Supports both synchronous and asynchronous operations
  • Compatible with multiple HTTP clients (requests, aiohttp, httpx)
  • Offers WebSocket support for subscriptions
  • Provides a user-friendly API for executing GraphQL queries and mutations

Cons

  • Limited documentation compared to some other GraphQL libraries
  • Smaller community and ecosystem compared to more popular alternatives
  • May have a steeper learning curve for beginners unfamiliar with GraphQL concepts
  • Some advanced features might require additional configuration or setup

Code Examples

  1. Simple synchronous query:
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

transport = RequestsHTTPTransport(url='https://api.example.com/graphql')
client = Client(transport=transport, fetch_schema_from_transport=True)

query = gql('''
    query GetUser($id: ID!) {
        user(id: $id) {
            name
            email
        }
    }
''')

result = client.execute(query, variable_values={'id': '123'})
print(result)
  1. Asynchronous query using aiohttp:
import asyncio
from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport

async def main():
    transport = AIOHTTPTransport(url='https://api.example.com/graphql')
    async with Client(transport=transport, fetch_schema_from_transport=True) as session:
        query = gql('''
            query GetPosts {
                posts {
                    title
                    author {
                        name
                    }
                }
            }
        ''')
        result = await session.execute(query)
        print(result)

asyncio.run(main())
  1. Subscription example using WebSockets:
import asyncio
from gql import gql, Client
from gql.transport.websockets import WebsocketsTransport

async def main():
    transport = WebsocketsTransport(url='wss://api.example.com/graphql')
    async with Client(transport=transport, fetch_schema_from_transport=True) as session:
        subscription = gql('''
            subscription OnNewMessage {
                messageAdded {
                    id
                    content
                }
            }
        ''')
        async for result in session.subscribe(subscription):
            print(result)

asyncio.run(main())

Getting Started

To get started with GQL, follow these steps:

  1. Install the library:

    pip install gql[all]
    
  2. Import the necessary modules:

    from gql import gql, Client
    from gql.transport.requests import RequestsHTTPTransport
    
  3. Create a transport and client:

    transport = RequestsHTTPTransport(url='https://api.example.com/graphql')
    client = Client(transport=transport, fetch_schema_from_transport=True)
    
  4. Execute a query:

    query = gql('''
        query {
            hello
        }
    ''')
    result = client.execute(query)
    print(result)
    

Competitor Comparisons

GraphQL framework for Python

Pros of Graphene

  • More comprehensive framework for building GraphQL APIs in Python
  • Supports schema definition using Python classes and objects
  • Integrates well with popular Python web frameworks like Django and Flask

Cons of Graphene

  • Steeper learning curve due to its more complex architecture
  • Can be overkill for simple GraphQL implementations
  • Less flexible for custom GraphQL client implementations

Code Comparison

Graphene schema definition:

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)

GQL query execution:

from gql import gql, Client

client = Client(schema=schema)
query = gql('''
    query {
        hello(name: "GraphQL")
    }
''')
result = client.execute(query)

Summary

Graphene is a more comprehensive framework for building GraphQL APIs in Python, offering integration with popular web frameworks and a class-based schema definition approach. However, it may be more complex for simple use cases. GQL, on the other hand, is primarily a GraphQL client library, making it more suitable for querying existing GraphQL APIs or implementing custom clients. The choice between the two depends on whether you're building a GraphQL server (Graphene) or primarily interacting with GraphQL APIs as a client (GQL).

A GraphQL library for Python that leverages type annotations 🍓

Pros of Strawberry

  • Uses Python type hints for schema definition, leading to cleaner and more intuitive code
  • Supports both synchronous and asynchronous resolvers out of the box
  • Includes built-in support for dataclasses and input types

Cons of Strawberry

  • Relatively newer project with a smaller community compared to GQL
  • May have a steeper learning curve for developers not familiar with Python type hints
  • Limited third-party integrations compared to more established libraries

Code Comparison

Strawberry:

import strawberry

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

schema = strawberry.Schema(query=Query)

GQL:

from graphql import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString

schema = GraphQLSchema(
    query=GraphQLObjectType(
        name='Query',
        fields={
            'hello': GraphQLField(
                GraphQLString,
                resolve=lambda obj, info: "Hello World!"
            )
        }
    )
)

The Strawberry example demonstrates its use of Python type hints and decorators for a more concise and readable schema definition, while the GQL example shows a more verbose approach using traditional GraphQL schema construction.

2,187

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

Pros of Ariadne

  • Schema-first approach, allowing for better separation of concerns
  • Built-in support for ASGI and WSGI applications
  • More extensive documentation and examples

Cons of Ariadne

  • Less flexible for client-side GraphQL operations
  • May require more setup for complex schemas
  • Limited support for GraphQL subscriptions

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)

GQL:

from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

transport = RequestsHTTPTransport(url='http://example.com/graphql')
client = Client(transport=transport, fetch_schema_from_transport=True)

query = gql('''
    query {
        hello
    }
''')

result = client.execute(query)

Ariadne focuses on server-side schema definition and resolver implementation, while GQL is primarily used for client-side GraphQL operations. Ariadne provides a more declarative approach to building GraphQL APIs, whereas GQL offers flexibility for querying existing GraphQL endpoints.

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

GQL

This is a GraphQL client for Python 3.8+. Plays nicely with graphene, graphql-core, graphql-js and any other GraphQL implementation compatible with the spec.

GQL architecture is inspired by React-Relay and Apollo-Client.

GitHub-Actions pyversion pypi Anaconda-Server Badge codecov

Documentation

The complete documentation for GQL can be found at gql.readthedocs.io.

Features

Installation

You can install GQL with all the optional dependencies using pip:

# Quotes may be required on certain shells such as zsh.
pip install "gql[all]"

NOTE: See also the documentation to install GQL with less extra dependencies depending on the transports you would like to use or for alternative installation methods.

Usage

Basic usage

from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport

# Select your transport with a defined url endpoint
transport = AIOHTTPTransport(url="https://countries.trevorblades.com/")

# Create a GraphQL client using the defined transport
client = Client(transport=transport, fetch_schema_from_transport=True)

# Provide a GraphQL query
query = gql(
    """
    query getContinents {
      continents {
        code
        name
      }
    }
"""
)

# Execute the query on the transport
result = client.execute(query)
print(result)

Executing the above code should output the following result:

$ python basic_example.py
{'continents': [{'code': 'AF', 'name': 'Africa'}, {'code': 'AN', 'name': 'Antarctica'}, {'code': 'AS', 'name': 'Asia'}, {'code': 'EU', 'name': 'Europe'}, {'code': 'NA', 'name': 'North America'}, {'code': 'OC', 'name': 'Oceania'}, {'code': 'SA', 'name': 'South America'}]}

WARNING: Please note that this basic example won't work if you have an asyncio event loop running. In some python environments (as with Jupyter which uses IPython) an asyncio event loop is created for you. In that case you should use instead the async usage example.

Contributing

See CONTRIBUTING.md

License

MIT License