To run a Graphene hello world script:
pip install graphene
Then run python hello.py
with this code in hello.py
:
import graphene
class Query(graphene.ObjectType):
hello = graphene.String(name=graphene.String(default_value="World"))
def resolve_hello(self, info, name):
return 'Hello ' + name
schema = graphene.Schema(query=Query)
result = schema.execute('{ hello }')
print(result.data['hello']) # "Hello World"
There are also nice bindings for Relay, Django, SQLAlchemy, and Google App Engine.
Here’s an example of a Strawberry hello world, first install the library:
pip install strawberry-graphql
Create an app.py
file with this content:
import strawberry
@strawberry.type
class Query:
@strawberry.field
def hello(self, name: str = "World") -> str:
return f"Hello {name}"
schema = strawberry.Schema(query=Query)
Then run strawberry server app
and you will have a basic schema server
running on http://localhost:8000
.
Strawberry also has views for ASGI, Flask and Django and provides utilities like dataloaders and tracing.
Ariadne can be installed with pip:
$ pip install ariadne
Minimal “Hello world” server example:
from ariadne import ObjectType, gql, make_executable_schema
from ariadne.asgi import GraphQL
type_defs = gql(
"""
type Query {
hello: String!
}
"""
)
query_type = ObjectType("Query")
@query_type.field("hello")
def resolve_hello(*_):
return "Hello world!"
schema = make_executable_schema(type_defs, query_type)
app = GraphQL(schema, debug=True)
Run the server with uvicorn:
$ pip install uvicorn
$ uvicorn example:app
To run a tartiflette hello world script:
pip install tartiflette
Then run python hello.py
with this code in hello.py
:
import asyncio
from tartiflette import Engine, Resolver
@Resolver("Query.hello")
async def resolver_hello(parent, args, ctx, info):
return "hello " + args["name"]
async def run():
tftt_engine = Engine("""
type Query {
hello(name: String): String
}
""")
result = await tftt_engine.execute(
query='query { hello(name: "Chuck") }'
)
print(result)
# {'data': {'hello': 'hello Chuck'}}
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
There is also a nice HTTP wrapper.
Install Ariadne Codegen:
$ pip install ariadne-codegen
Create queries.graphql
file:
mutation CreateToken($username: String!, $password: String!) {
createToken(username: $username, password: $password) {
token
errors {
field
message
}
}
}
Add [ariadne-codegen]
section to your pyproject.toml
:
[ariadne-codegen]
queries_path = "queries.graphql"
remote_schema_url = "http://example.com/graphql/"
Generate client:
$ ariadne-codegen
And use it in your Python projects:
from graphql_client import Client
with Client("http://example.com/graphql/") as client:
result = client.create_token(username="Admin", password="Example123)
if result.errors:
error = result.errors[0]
raise ValidationError({error.field: error.message})
auth_token = result.token
graphql_query is complete GraphQL query string builder for python. With graphql_query you can The documentation for graphql_query can be found at https://denisart.github.io/graphql-query.
$ pip install graphql_query
Code for the simple query
{
hero {
name
}
}
it is
from graphql_query import Operation, Query
hero = Query(name="hero", fields=["name"])
operation = Operation(type="query", queries=[hero])
print(operation.render())
"""
query {
hero {
name
}
}
"""
For generation of the following query
query Hero($episode: Episode, $withFriends: Boolean!) {
hero(episode: $episode) {
name
friends @include(if: $withFriends) {
name
}
}
}
we have
from graphql_query import Argument, Directive, Field, Operation, Query, Variable
episode = Variable(name="episode", type="Episode")
withFriends = Variable(name="withFriends", type="Boolean!")
arg_episode = Argument(name="episode", value=episode)
arg_if = Argument(name="if", value=withFriends)
hero = Query(
name="hero",
arguments=[arg_episode],
fields=[
"name",
Field(
name="friends",
fields=["name"],
directives=[Directive(name="include", arguments=[arg_if])]
)
]
)
operation = Operation(
type="query",
name="Hero",
variables=[episode, withFriends],
queries=[hero]
)
print(operation.render())
"""
query Hero(
$episode: Episode
$withFriends: Boolean!
) {
hero(
episode: $episode
) {
name
friends @include(
if: $withFriends
) {
name
}
}
}
"""
Here’s an example of a qlient hello world.
first install the library:
pip install qlient
Create a swapi_client_example.py
file with this content:
from qlient.http import HTTPClient, GraphQLResponse
client = HTTPClient("https://swapi-graphql.netlify.app/.netlify/functions/index")
res: GraphQLResponse = client.query.film(
# swapi graphql input fields
id="ZmlsbXM6MQ==",
# qlient specific
_fields=["id", "title", "episodeID"]
)
print(res.request.query) # query film($id: ID) { film(id: $id) { id title episodeID } }
print(res.request.variables) # {'id': 'ZmlsbXM6MQ=='}
print(res.data) # {'film': {'id': 'ZmlsbXM6MQ==', 'title': 'A New Hope', 'episodeID': 4}}
Close the file and run it using python:
python swapi_client_example.py
You can install the package with pip
pip install graphene-django-cruddals
To use it, simply create a new class that inherits “DjangoModelCruddals
”
Suppose we have the following models.
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
is_active = models.BooleanField(default=True)
Then we can create a complete CRUD+DALS for the models Question
with the following code
from graphene_django_cruddals import DjangoModelCruddals
class CruddalsQuestion(DjangoModelCruddals):
class Meta:
model = Question
Now you can use the schema
that was generated for you,
schema = CruddalsQuestion.Schema
or use in your existing schema root Query
and Mutation
class Query(
# ... your others queries
CruddalsQuestion.Query,
graphene.ObjectType,
):
pass
class Mutation(
# ... your others mutations
CruddalsQuestion.Mutation,
graphene.ObjectType,
):
pass
schema = graphene.Schema( query=Query, mutation=Mutation, )
That’s it! You can test in graphiql or any other client that you use to test your GraphQL APIs..
Find more information in the official documentation.
A Quickstart for Django Graphbox:
pip install django-graphbox
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
myapp/models.py
:from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
python manage.py makemigrations
python manage.py migrate
myapp/schema.py
:from django_graphbox.builder import SchemaBuilder
from myapp.models import MyModel
builder = SchemaBuilder()
builder.add_model(MyModel)
query_class = builder.build_schema_query()
mutation_class = builder.build_schema_mutation()
myproject/schema.py
(In this main schema you can add your own queries and mutations):import graphene
from myapp.schema import query_class, mutation_class
class Query(query_class, graphene.ObjectType):
pass
class Mutation(mutation_class, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query, mutation=Mutation)
myproject/urls.py
:from django.urls import path
from graphene_file_upload.django import FileUploadGraphQLView
from django.views.decorators.csrf import csrf_exempt
from myproject.schema import schema
urlpatterns = [
path('graphql/', csrf_exempt(FileUploadGraphQLView.as_view(graphiql=True, schema=schema))),
]
python manage.py runserver
http://localhost:8000/graphql
and start querying your API!You can find advanced examples with authentication, filters, validations and more on GitHub or pypi.