-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
97 lines (85 loc) · 3.1 KB
/
main.py
File metadata and controls
97 lines (85 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# FastAPI server with pure GraphQL handling + custom GraphiQL UI
# -----------------------------------------------
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from graphql import graphql_sync
from schema import schema # Import the GraphQL schema defined in schema.py
# Initialize FastAPI application
app = FastAPI(title="Python GraphQL Server")
# --------------------------
# CORS (Cross-Origin Resource Sharing)
# Allow requests from any origin, with any method and headers.
# This mimics the permissive CORS setup from Ruby/Rust versions.
# --------------------------
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# --------------------------
# GraphQL endpoint (POST /graphql)
# Accepts JSON payload with 'query' and optional 'variables'
# --------------------------
@app.post("/graphql")
async def graphql_server(request: Request):
# Parse request JSON body
body = await request.json()
query = body.get("query") # GraphQL query string
variables = body.get("variables") # Optional variables dictionary
# Execute query synchronously using graphql-core
# Returns an ExecutionResult object
result = graphql_sync(schema, query, variable_values=variables)
# Convert ExecutionResult to JSON-friendly dict
response = {}
if result.data:
response["data"] = result.data
if result.errors:
# Convert errors to string messages
response["errors"] = [str(e) for e in result.errors]
# Return JSON response
return JSONResponse(response)
# --------------------------
# GraphiQL UI (GET /)
# Interactive in-browser IDE for exploring the GraphQL API
# --------------------------
GRAPHIQL_HTML = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Python GraphQL Server</title>
<link
href="https://unpkg.com/graphiql@2.2.0/graphiql.min.css"
rel="stylesheet"
/>
</head>
<body style="margin:0; height:100vh;">
<!-- Container for GraphiQL -->
<div id="graphiql" style="height:100vh"></div>
<!-- React and ReactDOM are required for GraphiQL -->
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/graphiql@2.2.0/graphiql.min.js"></script>
<script>
// Function used by GraphiQL to send queries/mutations
const graphQLFetcher = (graphQLParams) =>
fetch("/graphql", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(graphQLParams),
}).then((response) => response.json());
// Render GraphiQL interface
ReactDOM.render(
React.createElement(GraphiQL, { fetcher: graphQLFetcher }),
document.getElementById("graphiql")
);
</script>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse)
async def graphiql():
"""Serve the GraphiQL UI at root path."""
return GRAPHIQL_HTML