graphql_http


Namegraphql_http JSON
Version 2.0.6 PyPI version JSON
download
home_pageNone
SummaryHTTP Server for GraphQL.
upload_time2025-09-03 09:23:31
maintainerNone
docs_urlNone
authorNone
requires_python<3.13,>=3.11
licenseMIT
keywords graphql http server starlette
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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

```bash
uv add graphql_http
```

Or with pip:
```bash
pip install graphql_http
```

## Quick Start

### Basic Usage

```python
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`:

```python
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

```python
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

```python
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

```python
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:

```bash
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):

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

Access GraphiQL interface in browser:

```
http://localhost:8000/graphql
```

### GET /health

Health check endpoint (if configured):

```bash
curl http://localhost:8000/health
```

## Authentication

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

```bash
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:

```python
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

With UV:
```bash
uv run pytest tests/ -v
```

Or with Python directly:
```bash
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.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "graphql_http",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<3.13,>=3.11",
    "maintainer_email": null,
    "keywords": "GraphQL, HTTP, Server, starlette",
    "author": null,
    "author_email": "Robert Parker <rob@parob.com>",
    "download_url": "https://files.pythonhosted.org/packages/e9/b8/368852074bb5a9b44187cabb6581291c869d831f9dd3e46988be9f6af5ef/graphql_http-2.0.6.tar.gz",
    "platform": null,
    "description": "# GraphQL HTTP Server\n\nA 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.\n\n## Features\n\n- \ud83d\ude80 **High Performance**: Built on Starlette/ASGI for excellent async performance\n- \ud83d\udd10 **JWT Authentication**: Built-in JWT authentication with JWKS support\n- \ud83c\udf10 **CORS Support**: Configurable CORS middleware for cross-origin requests\n- \ud83c\udfa8 **GraphiQL Integration**: Interactive GraphQL IDE for development\n- \ud83d\udcca **Health Checks**: Built-in health check endpoints\n- \ud83d\udd04 **Batch Queries**: Support for batched GraphQL operations\n- \ud83d\udee1\ufe0f **Error Handling**: Comprehensive error handling and formatting\n- \ud83d\udcdd **Type Safety**: Full TypeScript-style type hints for Python\n\n## Installation\n\n```bash\nuv add graphql_http\n```\n\nOr with pip:\n```bash\npip install graphql_http\n```\n\n## Quick Start\n\n### Basic Usage\n\n```python\nfrom graphql import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString\nfrom graphql_http import GraphQLHTTP\n\n# Define your GraphQL schema\nschema = GraphQLSchema(\n    query=GraphQLObjectType(\n        name=\"Query\",\n        fields={\n            \"hello\": GraphQLField(\n                GraphQLString,\n                resolve=lambda obj, info: \"Hello, World!\"\n            )\n        }\n    )\n)\n\n# Create the HTTP server\napp = GraphQLHTTP(schema=schema)\n\n# Run the server\nif __name__ == \"__main__\":\n    app.run(host=\"0.0.0.0\", port=8000)\n```\n\n### Using with GraphQL-API\n\nFor more advanced schemas, integrate with `graphql-api`:\n\n```python\nfrom graphql_api import GraphQLAPI\nfrom graphql_http import GraphQLHTTP\n\napi = GraphQLAPI()\n\n@api.type(is_root_type=True)\nclass Query:\n    @api.field\n    def hello(self, name: str = \"World\") -> str:\n        return f\"Hello, {name}!\"\n\n# Create server from API\nserver = GraphQLHTTP.from_api(api)\nserver.run()\n```\n\n## Configuration Options\n\n### Basic Configuration\n\n```python\napp = GraphQLHTTP(\n    schema=schema,\n    serve_graphiql=True,              # Enable GraphiQL interface\n    graphiql_default_query=\"{ hello }\", # Default query in GraphiQL\n    allow_cors=True,                  # Enable CORS\n    health_path=\"/health\"             # Health check endpoint\n)\n```\n\n### Authentication Configuration\n\n```python\napp = GraphQLHTTP(\n    schema=schema,\n    auth_enabled=True,\n    auth_jwks_uri=\"https://your-auth0-domain/.well-known/jwks.json\",\n    auth_issuer=\"https://your-auth0-domain/\",\n    auth_audience=\"your-api-audience\",\n    auth_enabled_for_introspection=False  # Allow introspection without auth\n)\n```\n\n### Advanced Configuration\n\n```python\nfrom graphql.execution import ExecutionContext\n\nclass CustomExecutionContext(ExecutionContext):\n    # Custom execution logic\n    pass\n\napp = GraphQLHTTP(\n    schema=schema,\n    root_value={\"version\": \"1.0\"},\n    middleware=[your_middleware_function],\n    context_value=custom_context,\n    execution_context_class=CustomExecutionContext\n)\n```\n\n## API Reference\n\n### GraphQLHTTP Class\n\n#### Constructor Parameters\n\n- `schema` (GraphQLSchema): The GraphQL schema to serve\n- `root_value` (Any, optional): Root value passed to resolvers\n- `middleware` (List[Callable], optional): List of middleware functions\n- `context_value` (Any, optional): Context passed to resolvers\n- `serve_graphiql` (bool, default: True): Whether to serve GraphiQL interface\n- `graphiql_default_query` (str, optional): Default query for GraphiQL\n- `allow_cors` (bool, default: False): Enable CORS middleware\n- `health_path` (str, optional): Path for health check endpoint\n- `execution_context_class` (Type[ExecutionContext], optional): Custom execution context\n- `auth_enabled` (bool, default: False): Enable JWT authentication\n- `auth_jwks_uri` (str, optional): JWKS URI for JWT validation\n- `auth_issuer` (str, optional): Expected JWT issuer\n- `auth_audience` (str, optional): Expected JWT audience\n- `auth_enabled_for_introspection` (bool, default: False): Require auth for introspection\n\n#### Methods\n\n- `from_api(api, **kwargs)`: Create server from GraphQL-API instance\n- `run(host, port, **kwargs)`: Run the server\n- `client()`: Get test client for testing\n\n## HTTP Endpoints\n\n### POST /graphql\n\nExecute GraphQL operations:\n\n```bash\ncurl -X POST http://localhost:8000/graphql \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"query\": \"{ hello }\"}'\n```\n\n### GET /graphql\n\nExecute GraphQL queries via GET (with query parameter):\n\n```bash\ncurl \"http://localhost:8000/graphql?query={hello}\"\n```\n\nAccess GraphiQL interface in browser:\n\n```\nhttp://localhost:8000/graphql\n```\n\n### GET /health\n\nHealth check endpoint (if configured):\n\n```bash\ncurl http://localhost:8000/health\n```\n\n## Authentication\n\nWhen authentication is enabled, requests must include a valid JWT token:\n\n```bash\ncurl -X POST http://localhost:8000/graphql \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\"query\": \"{ hello }\"}'\n```\n\n## Testing\n\nThe server includes a built-in test client:\n\n```python\nfrom graphql_http import GraphQLHTTP\n\nserver = GraphQLHTTP(schema=schema)\nclient = server.client()\n\nresponse = client.post(\"/graphql\", json={\"query\": \"{ hello }\"})\nassert response.status_code == 200\nassert response.json() == {\"data\": {\"hello\": \"Hello, World!\"}}\n```\n\n## Error Handling\n\nThe server provides comprehensive error handling:\n\n- **400 Bad Request**: Malformed queries or invalid JSON\n- **401 Unauthorized**: Invalid or missing authentication\n- **405 Method Not Allowed**: Invalid HTTP method\n- **500 Internal Server Error**: Server-side errors\n\n## Development\n\n### Running Tests\n\nWith UV:\n```bash\nuv run pytest tests/ -v\n```\n\nOr with Python directly:\n```bash\npython -m pytest tests/ -v\n```\n\n### Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Add tests for your changes\n4. Ensure all tests pass\n5. Submit a pull request\n\n## License\n\nMIT License - see LICENSE file for details.\n\n## Changelog\n\nSee CHANGELOG.md for version history and updates.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "HTTP Server for GraphQL.",
    "version": "2.0.6",
    "project_urls": {
        "Homepage": "https://gitlab.com/parob/graphql-http",
        "Repository": "https://gitlab.com/parob/graphql-http"
    },
    "split_keywords": [
        "graphql",
        " http",
        " server",
        " starlette"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8b0a6f4bf7a66b6d1bc536bf9c4e1d4a8ae41655555a979a72eee1c2b2c951ab",
                "md5": "199604b6b9c638c8dbe046265a3efb51",
                "sha256": "706699a235ed297e6f8719ccd11d0e555305a1973e6d8bb71e82c2a059e8d367"
            },
            "downloads": -1,
            "filename": "graphql_http-2.0.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "199604b6b9c638c8dbe046265a3efb51",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<3.13,>=3.11",
            "size": 48193,
            "upload_time": "2025-09-03T09:23:30",
            "upload_time_iso_8601": "2025-09-03T09:23:30.605343Z",
            "url": "https://files.pythonhosted.org/packages/8b/0a/6f4bf7a66b6d1bc536bf9c4e1d4a8ae41655555a979a72eee1c2b2c951ab/graphql_http-2.0.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e9b8368852074bb5a9b44187cabb6581291c869d831f9dd3e46988be9f6af5ef",
                "md5": "1903952b8f706056185559604b1ae265",
                "sha256": "5954598e1e911f9bc0f642f39439ac1120b545cd5e6de2920306fa00ad11bcc1"
            },
            "downloads": -1,
            "filename": "graphql_http-2.0.6.tar.gz",
            "has_sig": false,
            "md5_digest": "1903952b8f706056185559604b1ae265",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<3.13,>=3.11",
            "size": 121740,
            "upload_time": "2025-09-03T09:23:31",
            "upload_time_iso_8601": "2025-09-03T09:23:31.482173Z",
            "url": "https://files.pythonhosted.org/packages/e9/b8/368852074bb5a9b44187cabb6581291c869d831f9dd3e46988be9f6af5ef/graphql_http-2.0.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-03 09:23:31",
    "github": false,
    "gitlab": true,
    "bitbucket": false,
    "codeberg": false,
    "gitlab_user": "parob",
    "gitlab_project": "graphql-http",
    "lcname": "graphql_http"
}
        
Elapsed time: 1.21533s