Ariadne basics

From wikinotes

Example

Sample API

#!/usr/bin/env python
# ${PROJECT}/app.py

import ariadne
from ariadne import asgi


# Your GraphQL SDL Schema
type_defs = ariadne.gql("""
    type Query {
        hello: String!
    }
""")

# Resolvers for Query 'hello'
query = ariadne.QueryType()

@query.field("hello")
def resolve_hello(parent, info):
    request = info.context["request"]
    user_agent = request.headers.get("user-agent", "guest")
    return "Hello, %s!" % user_agent

# Build Schema, and create app
schema = ariadne.make_executable_schema(type_defs, query)
graphql_app = asgi.GraphQL(schema, debug=True)
  • queries are performed by accessing as fields on objects
  • two top-level objects expose the top-level fields categorized by type of operation
    QueryType or MutationType (query vs operation w/ side-effects)
  • each field has a resolver function.
    Resolvers are parametrized with the parent-node, and an object with HTTP request info.

Run API

# run server
pip install ariadne
pip install uvicorn

uvicorn app:graphql_app

Query API

Execute API query

# execute graphql query
curl -X POST \
    -H 'Content-Type: application/json' \
    -d '{"query": "query { hello }"}' \
    http://127.0.0.1:8000

Or, Use Interactive Editor

firefox http://127.0.0.1:8000