GraphQL Query Formatter
Format and beautify GraphQL queries, mutations, subscriptions, and fragments with proper indentation.
About this tool
GraphQL is a powerful query language for APIs, but when you're working with complex queries, mutations, and subscriptions, the raw text can become difficult to read and debug. A GraphQL Query Formatter takes your unformatted or poorly formatted GraphQL code and automatically restructures it with proper indentation and spacing, making it much easier to understand at a glance. This is especially valuable when integrating with APIs, testing different query structures, or collaborating with team members who need to review your code.
Using the tool is straightforward: paste your GraphQL query, mutation, subscription, or fragment into the input area and click the format button. The formatter instantly analyzes your code, adds appropriate indentation, aligns nested fields and arguments, and ensures consistent spacing throughout. You can then copy the beautifully formatted result and use it in your projects, documentation, or API testing tools. It handles complex scenarios including nested selections, aliases, variables, directives, and inline fragments.
This tool is particularly helpful for developers working with Apollo Client, Relay, or any GraphQL client library, as well as backend engineers managing GraphQL servers. It saves time compared to manual formatting and helps catch syntax issues before submitting requests to your API. Whether you're learning GraphQL, debugging a complex query, or preparing code for review, having a reliable formatter ensures your queries are always clear and professional.
Frequently Asked Questions
Code Implementation
def format_graphql(query: str, indent: int = 2) -> str:
"""Simple GraphQL formatter."""
result = []
depth = 0
pad = " " * indent
i = 0
q = query.strip()
while i < len(q):
ch = q[i]
if ch == '"':
# Consume string
j = i + 1
while j < len(q):
if q[j] == "\\" and j + 1 < len(q):
j += 2
continue
if q[j] == '"':
j += 1
break
j += 1
result.append(q[i:j])
i = j
continue
if ch == "{":
result.append(" {\n")
depth += 1
result.append(pad * depth)
elif ch == "}":
depth = max(0, depth - 1)
result.append("\n" + pad * depth + "}")
elif ch in ("\n", "\r", " ", "\t"):
if result and result[-1] not in ("\n", " ", "{\n"):
result.append(" ")
else:
result.append(ch)
i += 1
return "".join(result).strip()
query = """
query GetUser($id: ID!) {user(id: $id) {id name email posts {title}}}
"""
print(format_graphql(query))Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.