GraphQL with Python
Using GraphQL with Python is quite straightforward thanks to libraries like graphene, graphql-core, and ariadne. Here's a brief overview of how you can get started with each:
Graphene: Graphene is a Python library for building GraphQL APIs. It allows you to define your schema using Python classes and then automatically generates the GraphQL schema from them.
Python Code
from graphene import ObjectType, String, Schema
class Query(ObjectType):
hello = String(name=String(default_value="stranger"))
def resolve_hello(root, info, name):
return 'Hello ' + name
schema = Schema(query=Query)
graphql-core: This is a low-level Python library for parsing and executing GraphQL queries. It provides utilities for parsing, validation, and execution of GraphQL queries.
Python Code
from graphql import graphql, build_schema
schema = build_schema('''
type Query {
hello: String
}
''')
def resolve_hello(root, info):
return 'Hello world!'
result = graphql(schema, '{ hello }', root=resolve_hello)
Ariadne: Ariadne is a new library for Python that makes it easy to implement a GraphQL API. It's particularly great for integrating with web frameworks like Flask or Django.
Python Code
from ariadne import ObjectType, QueryType, gql, make_executable_schema
from ariadne.asgi import GraphQL
type_defs = gql("""
type Query {
hello: String
}
""")
query = QueryType()
@query.field("hello")
def resolve_hello(_, info):
return "Hello, world!"
schema = make_executable_schema(type_defs, query)
app = GraphQL(schema)
# Now you can integrate `app` with your chosen ASGI web server, e.g., Starlette or FastAPI.
These examples should give you a good starting point for working with GraphQL . Depending on your project requirements and preferences, you can choose the library that best fits your needs.