Debian Codegraph @

docs/usage/parser.rst

raw
1 Parsing GraphQL Queries and Schema Notation
2 -------------------------------------------
3
4 .. currentmodule:: graphql.language
5
6 When executing GraphQL queries, the first step that happens under the hood is parsing
7 the query. But GraphQL-core 3 also exposes the parser for direct usage via the
8 :func:`parse` function. When you pass this function a GraphQL source code, it will be
9 parsed and returned as a Document, i.e. an abstract syntax tree (AST) of :class:`Node`
10 objects. The root node will be a :class:`DocumentNode`, with child nodes of different
11 kinds corresponding to the GraphQL source. The nodes also carry information on the
12 location in the source code that they correspond to.
13
14 Here is an example::
15
16 from graphql import parse
17
18 document = parse("""
19 type Query {
20 me: User
21 }
22
23 type User {
24 id: ID
25 name: String
26 }
27 """)
28
29 You can also leave out the information on the location in the source code when creating
30 the AST document::
31
32 document = parse(..., no_location=True)
33
34 This will give the same result as manually creating the AST document::
35
36 from graphql.language.ast import *
37
38 document = DocumentNode(definitions=[
39 ObjectTypeDefinitionNode(
40 name=NameNode(value='Query'),
41 fields=[
42 FieldDefinitionNode(
43 name=NameNode(value='me'),
44 type=NamedTypeNode(name=NameNode(value='User')),
45 arguments=[], directives=[])
46 ], directives=[], interfaces=[]),
47 ObjectTypeDefinitionNode(
48 name=NameNode(value='User'),
49 fields=[
50 FieldDefinitionNode(
51 name=NameNode(value='id'),
52 type=NamedTypeNode(
53 name=NameNode(value='ID')),
54 arguments=[], directives=[]),
55 FieldDefinitionNode(
56 name=NameNode(value='name'),
57 type=NamedTypeNode(
58 name=NameNode(value='String')),
59 arguments=[], directives=[]),
60 ], directives=[], interfaces=[]),
61 ])
62
63
64 When parsing with ``no_location=False`` (the default), the AST nodes will also have a
65 ``loc`` attribute carrying the information on the source code location corresponding
66 to the AST nodes.
67
68 When there is a syntax error in the GraphQL source code, then the :func:`parse` function
69 will raise a :exc:`~graphql.error.GraphQLSyntaxError`.
70
71 The parser can not only be used to parse GraphQL queries, but also to parse the GraphQL
72 schema definition language. This will result in another way of representing a GraphQL
73 schema, as an AST document.