Top Related Projects
GraphQL framework for Python
A GraphQL library for Python that leverages type annotations 🍓
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
- 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)
- 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())
- 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:
-
Install the library:
pip install gql[all]
-
Import the necessary modules:
from gql import gql, Client from gql.transport.requests import RequestsHTTPTransport
-
Create a transport and client:
transport = RequestsHTTPTransport(url='https://api.example.com/graphql') client = Client(transport=transport, fetch_schema_from_transport=True)
-
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.
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 designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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
.
Documentation
The complete documentation for GQL can be found at gql.readthedocs.io.
Features
- Execute GraphQL queries using different protocols:
- http
- websockets:
- apollo or graphql-ws protocol
- Phoenix channels
- AWS AppSync realtime protocol (experimental)
- Possibility to validate the queries locally using a GraphQL schema provided locally or fetched from the backend using an instrospection query
- Supports GraphQL queries, mutations and subscriptions
- Supports sync or async usage, allowing concurrent requests
- Supports File uploads
- Supports Custom scalars / Enums
- gql-cli script to execute GraphQL queries or download schemas from the command line
- DSL module to compose GraphQL queries dynamically
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
Top Related Projects
GraphQL framework for Python
A GraphQL library for Python that leverages type annotations 🍓
Python library for implementing GraphQL servers using schema-first approach.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot