2022-03-11 18:00:00+00:00

When designing GraphQL APIs in Python, developers can use a schema-first or code-first design. A Schema-First design requires writing the API structure using official GraphQL Schema Definition Language (SDL) files. This makes APIs easier to read and align across frontend and backend teams. Ariadne is a lightweight, schema-first Python library that maps Python resolvers directly to SDL schemas without code generation overhead.

By mapping SDL definitions to resolver dictionaries, we can build clean GraphQL APIs.


1. Defining GraphQL Schemas and Resolvers

We write our GraphQL schema and define resolver functions to return database records:

# app.py
from ariadne import QueryType, make_executable_schema, graphql_sync
from ariadne.constants import PLAYGROUND_HTML
from flask import Flask, request, jsonify

type_defs = """
    type Query {
        hello: String!
        user(id: ID!): User
    }
    type User {
        id: ID!
        username: String!
    }
"""

query = QueryType()

@query.field("hello")
def resolve_hello(*_):
    return "Hello world!"

@query.field("user")
def resolve_user(*_, id):
    # Fetch from database
    return {"id": id, "username": f"User_{id}"}

schema = make_executable_schema(type_defs, query)

2. Serving the Endpoint

We configure our web framework (like Flask or FastAPI) to handle POST requests targeting the GraphQL endpoint and serve the interactive GraphQL playground interface, enabling fast developer debugging.