📣 GraphQLConf 2024 • Sept 10-12 • San Francisco • Check out the Schedule & Get Your Ticket • Read more

Code Using GraphQL

Sort by:
Graphene
A Python library for building GraphQL APIs.
Last release 1 year ago8kMIT License
README

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.

Strawberry
Strawberry is a Python library for implementing code first GraphQL servers using modern Python features like type hints.
Last release 4 days ago4kMIT License
README

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
Ariadne is a Python library for implementing GraphQL servers using schema-first approach. It supports both synchronous and asynchronous query execution, ships with batteries included for common GraphQL server problems like query cost validation or performance tracing and has simple API that is easy to extend or replace.
Last release 6 months ago2kBSD 3-Clause "New" or "Revised" License
README

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
GQL
A GraphQL client in Python.
Last release 5 months ago2kMIT License
Tartiflette
A Python 3.6+ (asyncio) library for building GraphQL APIs.
Last release 2 years ago1kMIT License
README

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.

sgqlc
A simple Python GraphQL client. Supports generating code generation for types defined in a GraphQL schema.
1kISC License
Ariadne Codegen
Generate fully typed Python GraphQL client from any schema and queries.
Last release 2 months ago259BSD 3-Clause "New" or "Revised" License
README

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
python-graphql-client
Simple GraphQL client for Python 2.7+.
156MIT License
graphql-query
Complete GraphQL query string generation for python.
Last release 1 month ago56MIT License
README

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
    }
  }
}
"""
Qlient
A fast and modern graphql client designed with simplicity in mind.
Last release 2 years ago45MIT License
README

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
Graphene Django CRUDDALS
Turn your Django-models into a complete GraphQL API with all CRUD operations
12Apache License 2.0
README

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.

Django Graphbox
Package for easy building a GraphQL API with basic CRUD operations for Django models.
Last release 6 months ago10MIT License
README

A Quickstart for Django Graphbox:

  1. Install the package:
pip install django-graphbox
  1. Create a new Django project:
django-admin startproject myproject
  1. Create a new Django app:
cd myproject
python manage.py startapp myapp
  1. Define your Django models in myapp/models.py:
from django.db import models
 
class MyModel(models.Model):
    name = models.CharField(max_length=100)
  1. Create and run migrations:
python manage.py makemigrations
python manage.py migrate
  1. Configure and Build your GraphQL Schema in 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()
  1. Create a main Schema in 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)
  1. Add the GraphQL view to your 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))),
]
  1. Run the server:
python manage.py runserver
  1. Open the GraphiQL interface at http://localhost:8000/graphql and start querying your API!

You can find advanced examples with authentication, filters, validations and more on GitHub or pypi.