Skip to main content

HTTP Server for GraphQL.

Project description

GraphQL HTTP Server

A lightweight, production-ready HTTP server for GraphQL APIs built on top of Starlette/FastAPI. This server provides a simple yet powerful way to serve GraphQL schemas over HTTP with built-in support for authentication, CORS, GraphiQL integration, and more.

Features

  • 🚀 High Performance: Built on Starlette/ASGI for excellent async performance
  • 🔐 JWT Authentication: Built-in JWT authentication with JWKS support
  • 🌐 CORS Support: Configurable CORS middleware for cross-origin requests
  • 🎨 GraphiQL Integration: Interactive GraphQL IDE for development
  • 📊 Health Checks: Built-in health check endpoints
  • 🔄 Batch Queries: Support for batched GraphQL operations
  • 🛡️ Error Handling: Comprehensive error handling and formatting
  • 📝 Type Safety: Full TypeScript-style type hints for Python

Installation

pip install graphql_http

Quick Start

Basic Usage

from graphql import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString
from graphql_http import GraphQLHTTP

# Define your GraphQL schema
schema = GraphQLSchema(
    query=GraphQLObjectType(
        name="Query",
        fields={
            "hello": GraphQLField(
                GraphQLString,
                resolve=lambda obj, info: "Hello, World!"
            )
        }
    )
)

# Create the HTTP server
app = GraphQLHTTP(schema=schema)

# Run the server
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

Using with GraphQL-API

For more advanced schemas, integrate with graphql-api:

from graphql_api import GraphQLAPI
from graphql_http import GraphQLHTTP

api = GraphQLAPI()

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

# Create server from API
server = GraphQLHTTP.from_api(api)
server.run()

Configuration Options

Basic Configuration

app = GraphQLHTTP(
    schema=schema,
    serve_graphiql=True,              # Enable GraphiQL interface
    graphiql_default_query="{ hello }", # Default query in GraphiQL
    allow_cors=True,                  # Enable CORS
    health_path="/health"             # Health check endpoint
)

Authentication Configuration

app = GraphQLHTTP(
    schema=schema,
    auth_enabled=True,
    auth_jwks_uri="https://your-auth0-domain/.well-known/jwks.json",
    auth_issuer="https://your-auth0-domain/",
    auth_audience="your-api-audience",
    auth_enabled_for_introspection=False  # Allow introspection without auth
)

Advanced Configuration

from graphql.execution import ExecutionContext

class CustomExecutionContext(ExecutionContext):
    # Custom execution logic
    pass

app = GraphQLHTTP(
    schema=schema,
    root_value={"version": "1.0"},
    middleware=[your_middleware_function],
    context_value=custom_context,
    execution_context_class=CustomExecutionContext
)

API Reference

GraphQLHTTP Class

Constructor Parameters

  • schema (GraphQLSchema): The GraphQL schema to serve
  • root_value (Any, optional): Root value passed to resolvers
  • middleware (List[Callable], optional): List of middleware functions
  • context_value (Any, optional): Context passed to resolvers
  • serve_graphiql (bool, default: True): Whether to serve GraphiQL interface
  • graphiql_default_query (str, optional): Default query for GraphiQL
  • allow_cors (bool, default: False): Enable CORS middleware
  • health_path (str, optional): Path for health check endpoint
  • execution_context_class (Type[ExecutionContext], optional): Custom execution context
  • auth_enabled (bool, default: False): Enable JWT authentication
  • auth_jwks_uri (str, optional): JWKS URI for JWT validation
  • auth_issuer (str, optional): Expected JWT issuer
  • auth_audience (str, optional): Expected JWT audience
  • auth_enabled_for_introspection (bool, default: False): Require auth for introspection

Methods

  • from_api(api, **kwargs): Create server from GraphQL-API instance
  • run(host, port, **kwargs): Run the server
  • client(): Get test client for testing

HTTP Endpoints

POST /graphql

Execute GraphQL operations:

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

GET /graphql

Execute GraphQL queries via GET (with query parameter):

curl "http://localhost:8000/graphql?query={hello}"

Access GraphiQL interface in browser:

http://localhost:8000/graphql

GET /health

Health check endpoint (if configured):

curl http://localhost:8000/health

Authentication

When authentication is enabled, requests must include a valid JWT token:

curl -X POST http://localhost:8000/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{"query": "{ hello }"}'

Testing

The server includes a built-in test client:

from graphql_http import GraphQLHTTP

server = GraphQLHTTP(schema=schema)
client = server.client()

response = client.post("/graphql", json={"query": "{ hello }"})
assert response.status_code == 200
assert response.json() == {"data": {"hello": "Hello, World!"}}

Error Handling

The server provides comprehensive error handling:

  • 400 Bad Request: Malformed queries or invalid JSON
  • 401 Unauthorized: Invalid or missing authentication
  • 405 Method Not Allowed: Invalid HTTP method
  • 500 Internal Server Error: Server-side errors

Development

Running Tests

python -m pytest tests/ -v

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for your changes
  4. Ensure all tests pass
  5. Submit a pull request

License

MIT License - see LICENSE file for details.

Changelog

See CHANGELOG.md for version history and updates.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

graphql_http-2.0.0.tar.gz (58.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

graphql_http-2.0.0-py3-none-any.whl (60.4 kB view details)

Uploaded Python 3

File details

Details for the file graphql_http-2.0.0.tar.gz.

File metadata

  • Download URL: graphql_http-2.0.0.tar.gz
  • Upload date:
  • Size: 58.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for graphql_http-2.0.0.tar.gz
Algorithm Hash digest
SHA256 c86e87e176847e4cd098f007bcfd95b075cbb49911ff6bd375f260490627454e
MD5 d6c4f78ac34fd464545cee21f52524b8
BLAKE2b-256 0251c00e5aa667f2b382a77f78a4775c4dd228ebe0b72de990a280ee60a50899

See more details on using hashes here.

File details

Details for the file graphql_http-2.0.0-py3-none-any.whl.

File metadata

  • Download URL: graphql_http-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 60.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for graphql_http-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 678af3e8e29006d27466a78f4512c47449860788d7538ba6f5ae7d7b7d283bfd
MD5 621159c6e6b8c40c44d15d7d5b1d7be6
BLAKE2b-256 e28efba8fc3a8a2fe03e0cdfcb3c8ed15f300e7e6921cab286c42d5b5165299c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page