Skip to main content

GraphQL-API for Python

PyPI version Python versions License: MIT

Documentation | PyPI | GitHub


A powerful and intuitive Python library for building GraphQL APIs, designed with a code-first, decorator-based approach.

graphql-api simplifies schema definition by leveraging Python's type hints, dataclasses, and Pydantic models, allowing you to build robust and maintainable GraphQL services with minimal boilerplate.

Key Features

  • Decorator-Based Schema: Define your GraphQL schema declaratively using simple and intuitive decorators.
  • Type Hinting: Automatically converts Python type hints into GraphQL types.
  • Implicit Type Inference: Automatically maps Pydantic models, dataclasses, and classes with fields - no explicit decorators needed.
  • Pydantic & Dataclass Support: Seamlessly use Pydantic and Dataclass models as GraphQL types.
  • Asynchronous Execution: Full support for async and await for high-performance, non-blocking resolvers.
  • Apollo Federation: Built-in support for creating federated services.
  • Subscriptions: Implement real-time functionality with GraphQL subscriptions.
  • Middleware: Add custom logic to your resolvers with a flexible middleware system.
  • Relay Support: Includes helpers for building Relay-compliant schemas.

Installation

pip install graphql-api

Quick Start

For simple APIs, register plain functions directly — no class required:

# example.py
from graphql_api.api import GraphQLAPI

api = GraphQLAPI()

@api.query
def hello(name: str = "World") -> str:
    """A classic greeting."""
    return f"Hello, {name}!"

@api.mutation
def set_name(name: str) -> str:
    return f"Name set to {name}"

if __name__ == "__main__":
    result = api.execute('query { hello(name: "Developer") }')
    print(result.data)
$ python example.py
{'hello': 'Hello, Developer!'}

Use @api.query, @api.mutation, and @api.subscription for root-level fields. For nested object types, reach for the class-based form below.

Class-based form

When you need object types with their own fields (relationships, computed properties, nested resolvers), define a root class:

from graphql_api.api import GraphQLAPI

api = GraphQLAPI()

@api.type(is_root_type=True)
class Query:
    """The root query for our amazing API."""
    @api.field
    def hello(self, name: str = "World") -> str:
        return f"Hello, {name}!"

result = api.execute('query { hello(name: "Developer") }')
print(result.data)
# {'hello': 'Hello, Developer!'}

Examples

Using Pydantic Models

Leverage Pydantic for data validation and structure. graphql-api will automatically convert your models into GraphQL types.

from pydantic import BaseModel
from typing import List
from graphql_api.api import GraphQLAPI

class Book(BaseModel):
    title: str
    author: str

@api.type(is_root_type=True)
class BookAPI:
    @api.field
    def get_books(self) -> List[Book]:
        return [
            Book(title="The Hitchhiker's Guide to the Galaxy", author="Douglas Adams"),
            Book(title="1984", author="George Orwell"),
        ]

api = GraphQLAPI()

graphql_query = """
    query {
        getBooks {
            title
            author
        }
    }
"""

result = api.execute(graphql_query)
# result.data will contain the list of books

Asynchronous Resolvers

Define async resolvers for non-blocking I/O operations.

import asyncio
from graphql_api.api import GraphQLAPI

api = GraphQLAPI()

@api.type(is_root_type=True)
class AsyncAPI:
    @api.field
    async def fetch_data(self) -> str:
        await asyncio.sleep(1)
        return "Data fetched successfully!"

# To execute async queries, you'll need an async executor
# or to run it within an async context.
async def main():
    result = await api.execute("""
        query {
            fetchData
        }
    """)
    print(result.data)

if __name__ == "__main__":
    asyncio.run(main())

Mutations with Dataclasses

Use dataclasses to define the structure of your data, and mark fields as mutable to automatically separate them into the GraphQL Mutation type.

from dataclasses import dataclass
from graphql_api.api import GraphQLAPI

@dataclass
class User:
    id: int
    name: str

# A simple in-memory database
db = {1: User(id=1, name="Alice")}

api = GraphQLAPI()

@api.type(is_root_type=True)
class Root:
    @api.field
    def get_user(self, user_id: int) -> User:
        return db.get(user_id)

    @api.field(mutable=True)
    def add_user(self, user_id: int, name: str) -> User:
        new_user = User(id=user_id, name=name)
        db[user_id] = new_user
        return new_user

GraphQL automatically separates queries and mutations - you don't need separate classes. Fields marked with mutable=True are placed in the Mutation type, while regular fields go in the Query type. Fields with AsyncGenerator return types are automatically detected as subscriptions. This automatic mapping means you can define all your operations in a single class and let graphql-api handle the schema organization for you.

  • graphql-http - Serve your API over HTTP with authentication and GraphiQL
  • graphql-db - SQLAlchemy integration for database-backed APIs
  • graphql-mcp - Expose your API as MCP tools for AI agents

See the documentation for advanced schema patterns, federation, remote GraphQL, and more.

Documentation

Visit the official documentation for comprehensive guides, tutorials, and API reference.

Key Topics

Running Tests

To contribute or run the test suite locally:

# Install dependencies
uv sync

# Run tests
uv run pytest

Metadata

Release files for graphql-api 2.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for graphql-api 2.0.1
File Size Uploaded Provenance Actions
graphql_api-2.0.1.tar.gz 324.9 kB Without provenance Details for graphql_api-2.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for graphql-api 2.0.1
File Interpreter ABI Platform Actions
graphql_api-2.0.1-py3-none-any.whl Python 3 none any Details for graphql_api-2.0.1-py3-none-any.whl

Total release size: 398.8 kB

Release files / graphql_api-2.0.1.tar.gz

Download URL graphql_api-2.0.1.tar.gz
Size 324.9 kB
Tags Source
SHA-256 checksum
How to use checksums
426297c5c9079db6afe7c1cdb00f68a4341b29cb93b5fde467538c433a6747f1
BLAKE2b-256 checksum
How to use checksums
3a08b37b2a4283aa0deab33058966ea696f43ee340cb33a077003eae30212094
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / graphql_api-2.0.1-py3-none-any.whl

Download URL graphql_api-2.0.1-py3-none-any.whl
Size 73.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
897fb3dce206fa0a6297736d0965b9ee50c2f091a26098f18f3d2772297a93fd
BLAKE2b-256 checksum
How to use checksums
163584f9c3aaff9b20bfb5ab7d05532266871ae45666ecde95326d6d020529e6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for graphql-api 2.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page