### Install graphql-core with uv Source: https://github.com/graphql-python/graphql-core/blob/main/docs/intro.md Install the graphql-core package using the uv package installer. ```bash uv pip install graphql-core ``` -------------------------------- ### Install graphql-core with pip Source: https://github.com/graphql-python/graphql-core/blob/main/docs/intro.md Use pip to install the graphql-core package for your Python project. ```bash pip install graphql-core ``` -------------------------------- ### Example Execution Result Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/methods.md This is a sample output from executing a GraphQL query using synchronous resolvers and a root value object. ```python ExecutionResult( data={'droid': {'name': 'R2-D2', 'primaryFunction': 'Astromech'}}, errors=None) ``` -------------------------------- ### Define GraphQL Schema in SDL Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md This is an example of a GraphQL schema defined using the Schema Definition Language (SDL). ```graphql enum Episode { NEWHOPE, EMPIRE, JEDI } interface Character { id: String! name: String friends: [Character] appearsIn: [Episode] } type Human implements Character { id: String! name: String friends: [Character] appearsIn: [Episode] homePlanet: String } type Droid implements Character { id: String! name: String friends: [Character] appearsIn: [Episode] primaryFunction: String } type Query { hero(episode: Episode): Character human(id: String!): Human droid(id: String!): Droid } ``` -------------------------------- ### Manually Construct AST Document Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/parser.md This example shows how to manually construct an AST DocumentNode, which is equivalent to parsing a schema string with `no_location=True`. It demonstrates the structure of the AST nodes. ```python from graphql.language.ast import * document = DocumentNode(definitions=( ObjectTypeDefinitionNode( name=NameNode(value='Query'), fields=( FieldDefinitionNode( name=NameNode(value='me'), type=NamedTypeNode(name=NameNode(value='User')), arguments=None, directives=None), ), interfaces=None, directives=None), ObjectTypeDefinitionNode( name=NameNode(value='User'), fields=( FieldDefinitionNode( name=NameNode(value='id'), type=NamedTypeNode( name=NameNode(value='ID')), arguments=None, directives=None), FieldDefinitionNode( name=NameNode(value='name'), type=NamedTypeNode( name=NameNode(value='String')), arguments=None, directives=None), ), interfaces=None, directives=None), )) ) ``` -------------------------------- ### Example Execution Result Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/extension.md This is the expected output when querying the extended schema. It shows the data returned for the requested fields, including the newly added 'lastName'. ```plaintext ExecutionResult( data={'human': {'lastName': 'Skywalker', 'homePlanet': 'Tatooine'}}, errors=None) ``` -------------------------------- ### Execution Result Example Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/sdl.md Example of the `ExecutionResult` object returned after querying a schema built from SDL. It contains the query data and any errors encountered during execution. ```python ExecutionResult( data={'hero': {'name': 'Luke Skywalker', 'appearsIn': ['NEWHOPE', 'EMPIRE', 'JEDI']}}, errors=None) ``` -------------------------------- ### Execute an Asynchronous GraphQL Query Source: https://github.com/graphql-python/graphql-core/blob/main/README.md Utilize the `graphql` function with asynchronous resolvers to fetch data asynchronously. This example includes a simulated delay. ```python import asyncio from graphql import ( graphql, GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString ) async def resolve_hello(obj, info): await asyncio.sleep(3) return 'world' schema = GraphQLSchema( query=GraphQLObjectType( name='RootQueryType', fields={ 'hello': GraphQLField( GraphQLString, resolve=resolve_hello) })) async def main(): query = '{ hello }' print('Fetching the result...') result = await graphql(schema, query) print(result) asyncio.run(main()) ``` -------------------------------- ### Manually Validate GraphQL Query AST Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/validator.md Call the `validate()` function with a schema and a parsed AST document to get a list of validation errors. This is useful for pre-execution checks. ```python from graphql import parse, validate errors = validate(schema, parse(""" { human(id: NEWHOPE) { name homePlace friends } } """)) ``` -------------------------------- ### Import GraphQL Core Types Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Import necessary classes from the graphql.type sub-package to build your schema. ```python from graphql import ( GraphQLArgument, GraphQLEnumType, GraphQLEnumValue, GraphQLField, GraphQLInterfaceType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLSchema, GraphQLString) ``` -------------------------------- ### Build Schema from SDL Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/sdl.md Use `build_schema` to create a `GraphQLSchema` object from a string containing GraphQL Schema Definition Language (SDL). Resolver functions are not included and must be attached separately. ```python from graphql import build_schema schema = build_schema(""" enum Episode { NEWHOPE, EMPIRE, JEDI } interface Character { id: String! name: String friends: [Character] appearsIn: [Episode] } type Human implements Character { id: String! name: String friends: [Character] appearsIn: [Episode] homePlanet: String } type Droid implements Character { id: String! name: String friends: [Character] appearsIn: [Episode] primaryFunction: String } type Query { hero(episode: Episode): Character human(id: String!): Human droid(id: String!): Droid } "") ``` -------------------------------- ### Create GraphQL Schema Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Creates the GraphQL schema instance using the defined query type. Additional arguments for mutation and subscription types can also be passed. ```python schema = GraphQLSchema(query_type) ``` -------------------------------- ### Define a simple GraphQL Schema Source: https://github.com/graphql-python/graphql-core/blob/main/docs/intro.md Define a basic GraphQL schema with a 'hello' query that returns 'world'. This demonstrates the use of GraphQLSchema, GraphQLObjectType, and GraphQLField from the graphql.type package. ```python from graphql import ( GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString ) schema = GraphQLSchema( query=GraphQLObjectType( name='RootQueryType', fields={ 'hello': GraphQLField( GraphQLString, resolve=lambda obj, info: 'world') })) ``` -------------------------------- ### GraphQL Query Execution Result Source: https://github.com/graphql-python/graphql-core/blob/main/docs/intro.md The expected output when executing the 'hello' query against the simple schema. ```text ExecutionResult(data={'hello': 'world'}, errors=None) ``` -------------------------------- ### Query Schema Built from SDL Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/sdl.md Execute a GraphQL query against a schema that was built using the Schema Definition Language (SDL). This demonstrates querying the `hero` field with an `EMPIRE` episode argument. ```python from graphql import graphql_sync result = graphql_sync(schema, """ { hero(episode: EMPIRE) { name appearsIn } } """) print(result) ``` -------------------------------- ### Execute Async GraphQL Query Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/queries.md Use `graphql.graphql()` for asynchronous query execution within an event loop. Ensure the schema and query are correctly defined. ```python import asyncio from graphql import graphql async def query_artoo(): result = await graphql(schema, """ { droid(id: "2001") { name primaryFunction } } """) print(result) asyncio.run(query_artoo()) ``` -------------------------------- ### Execute a GraphQL Query Source: https://github.com/graphql-python/graphql-core/blob/main/docs/intro.md Execute a GraphQL query against a defined schema using graphql_sync. This function parses and validates the query before execution. ```python from graphql import graphql_sync query = '{ hello }' print(graphql_sync(schema, query)) ``` -------------------------------- ### Define a Simple GraphQL Schema Source: https://github.com/graphql-python/graphql-core/blob/main/README.md Build a basic GraphQL schema with a single query field. The resolver function can return a value, a coroutine, or a list. ```python from graphql import ( GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString ) schema = GraphQLSchema( query=GraphQLObjectType( name='RootQueryType', fields={ 'hello': GraphQLField( GraphQLString, resolve=lambda obj, info: 'world') })) ``` -------------------------------- ### Execute Synchronous GraphQL Query Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/queries.md Use `graphql.graphql_sync()` for executing queries in ordinary synchronous code. This is suitable when all resolvers operate synchronously. ```python from graphql import graphql_sync result = graphql_sync(schema, """ query FetchHuman($id: String!) { human(id: $id) { name homePlanet } } """, variable_values={'id': '1000'}) print(result) ``` -------------------------------- ### Schema Creation Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Constructs the GraphQL schema using the defined query type. ```APIDOC ## Schema Definition ### Description Creates the GraphQL schema from the defined query type. ### Usage ```python schema = GraphQLSchema(query_type) ``` ### Notes A mutation type and a subscription type can also be passed as additional arguments to `GraphQLSchema`. ``` -------------------------------- ### Implement Hero Fetching Resolver Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/resolvers.md Resolver function to fetch the hero of the trilogy. It returns Luke Skywalker for episode 5 and R2-D2 for all other episodes, demonstrating conditional data fetching. ```python def get_hero(root, _info, episode): """Allows us to fetch the undisputed hero of the trilogy, R2-D2.""" if episode == 5: return luke # Luke is the hero of Episode V return artoo # Artoo is the hero otherwise ``` -------------------------------- ### Execute Synchronous GraphQL Query with Root Value Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/methods.md Use graphql_sync() to execute a query when all resolvers are synchronous. Pass an instance of your root resolver class as the root_value argument. ```python from graphql import graphql_sync result = graphql_sync(schema, """ { droid(id: "2001") { name primaryFunction } } """, Root()) print(result) ``` -------------------------------- ### Define Character Interface Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Construct the 'Character' GraphQL interface, using a lambda thunk for fields that reference the interface itself. ```python character_interface = GraphQLInterfaceType('Character', lambda: { 'id': GraphQLField( GraphQLNonNull(GraphQLString), description='The id of the character.'), 'name': GraphQLField( GraphQLString, description='The name of the character.'), 'friends': GraphQLField( GraphQLList(character_interface), description='The friends of the character,' ' or an empty list if they have none.'), 'appearsIn': GraphQLField( GraphQLList(episode_enum), description='Which movies they appear in.'), 'secretBackstory': GraphQLField( GraphQLString, description='All secrets about their past.')}, resolve_type=get_character_type, description='A character in the Star Wars Trilogy') ``` -------------------------------- ### Execute a Synchronous GraphQL Query Source: https://github.com/graphql-python/graphql-core/blob/main/README.md Run a query against a defined schema and print the synchronous result. This function validates the query before execution. ```python from graphql import graphql_sync source = '{ hello }' print(graphql_sync(schema, source)) ``` -------------------------------- ### Attach Resolver Functions Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/sdl.md Manually attach resolver functions to the schema fields and types after building the schema from SDL. This is necessary because resolvers cannot be defined directly within the SDL. ```python schema.query_type.fields['hero'].resolve = get_hero schema.get_type('Character').resolve_type = get_character_type ``` -------------------------------- ### Generate Introspection Query with Descriptions Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/introspection.md Use `get_introspection_query` to create a query that includes schema descriptions. This is useful for detailed schema inspection. ```python from graphql import get_introspection_query query = get_introspection_query(descriptions=True) ``` -------------------------------- ### Implement Friends Fetching Resolver Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/resolvers.md Resolver function that takes a character object and returns a list of their friends by calling the `get_character` helper for each friend's ID. This enables querying for a character's connections. ```python def get_friends(character, _info): """Allows us to query for a character's friends.""" return map(get_character, character.friends) ``` -------------------------------- ### Execute Introspection Query Against a Schema Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/introspection.md Run an introspection query against a GraphQL schema using `graphql_sync`. The result contains schema details in a dictionary format. ```python from graphql import graphql_sync introspection_query_result = graphql_sync(schema, query) ``` -------------------------------- ### Querying Meta Field __typename Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/queries.md GraphQL allows querying the `__typename` meta field to verify the type of an object. This is useful for introspection and debugging. ```python result = graphql_sync(schema, """ { hero(episode: EMPIRE) { __typename name } } """) print(result) ``` -------------------------------- ### Implement Secret Backstory Resolver with Error Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/resolvers.md Resolver function designed to raise a `RuntimeError` when accessed, indicating that the 'secretBackstory' field is intentionally protected and should not be queried. ```python def get_secret_backstory(_character, _info): """Raise an error when attempting to get the secret backstory.""" raise RuntimeError('secretBackstory is secret.') ``` -------------------------------- ### Handle Query Errors Synchronously Source: https://github.com/graphql-python/graphql-core/blob/main/README.md Execute a query for a non-existent field to demonstrate error handling. The result will contain GraphQLError details. ```python from graphql import graphql_sync source = '{ BoyHowdy }' print(graphql_sync(schema, source)) ``` -------------------------------- ### Convert Introspection Result to SDL Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/introspection.md Use `print_schema` to convert a `GraphQLSchema` object, built from an introspection result, into its Schema Definition Language (SDL) string representation. ```python from graphql import print_schema sdl = print_schema(client_schema) print(sdl) ``` -------------------------------- ### Create an Enum Type with Descriptions Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Define a GraphQL enum type 'Episode' with associated values and descriptions using GraphQLEnumType and GraphQLEnumValue. ```python episode_enum = GraphQLEnumType('Episode', { 'NEWHOPE': GraphQLEnumValue(4, description='Released in 1977.'), 'EMPIRE': GraphQLEnumValue(5, description='Released in 1980.'), 'JEDI': GraphQLEnumValue(6, description='Released in 1983.') }, description='One of the films in the Star Wars Trilogy') ``` -------------------------------- ### Query Extended Schema Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/extension.md Execute a query against the extended schema to retrieve data from the newly added field. Ensure the schema has been updated and resolvers are attached. ```python from graphql import graphql_sync result = graphql_sync(schema, """ { human(id: "1000") { lastName homePlanet } } """, variable_values=None, context_value=None, root_value=None, operation_name=None) print(result) ``` -------------------------------- ### Parse GraphQL Schema String Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/parser.md Use the `parse()` function to convert a GraphQL schema string into an AST DocumentNode. This is the default behavior when parsing. ```python from graphql import parse document = parse(""" type Query { me: User } type User { id: ID name: String } ") ``` -------------------------------- ### Build GraphQLSchema from Introspection Result Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/introspection.md Convert an introspection query result dictionary into a `GraphQLSchema` object using `build_client_schema`. This is useful for client-side schema representation. ```python from graphql import build_client_schema client_schema = build_client_schema(introspection_query_result.data) ``` -------------------------------- ### Define Root Resolvers as Class Methods Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/methods.md Define synchronous resolver methods within a class that will be used as the root_value. These methods handle specific fields in your GraphQL schema. ```python class Root: """The root resolvers""" def hero(self, info, episode): return luke if episode == 5 else artoo def human(self, info, id): return human_data.get(id) def droid(self, info, id): return droid_data.get(id) ``` -------------------------------- ### Implement Character Fetching Resolver Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/resolvers.md Helper function to retrieve a character by their ID from either human or droid data. This resolver is essential for fetching specific character objects. ```python def get_character(id): """Helper function to get a character by ID.""" return human_data.get(id) or droid_data.get(id) ``` -------------------------------- ### Implement Human Fetching Resolver Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/resolvers.md Resolver function to query for a specific human character by their ID using the `human_data` dictionary. This is a direct data retrieval function. ```python def get_human(root, _info, id): """Allows us to query for the human with the given id.""" return human_data.get(id) ``` -------------------------------- ### Construct Query Type for GraphQL Schema Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Defines the root 'Query' type for the GraphQL schema. It includes fields for 'hero', 'human', and 'droid', each with their respective arguments and resolvers. ```python query_type = GraphQLObjectType('Query', lambda: { 'hero': GraphQLField(character_interface, args={ 'episode': GraphQLArgument(episode_enum, description=( 'If omitted, returns the hero of the whole saga.' ' If provided, returns the hero of that particular episode.'))}, resolve=get_hero), 'human': GraphQLField(human_type, args={ 'id': GraphQLArgument( GraphQLNonNull(GraphQLString), description='id of the human')}, resolve=get_human), 'droid': GraphQLField(droid_type, args={ 'id': GraphQLArgument( GraphQLNonNull(GraphQLString), description='id of the droid')}, resolve=get_droid)}) ``` -------------------------------- ### Generate Introspection Query without Descriptions Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/introspection.md Use `get_introspection_query` with `descriptions=False` to create a query that omits schema descriptions. This results in a more concise introspection query. ```python query = get_introspection_query(descriptions=False) ``` -------------------------------- ### Query Type Definition Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Defines the root 'Query' type for the schema, including fields for retrieving hero, human, and droid data. ```APIDOC ## Query Type ### Description Defines the available queries for the schema. ### Fields - **hero** (character_interface) ### Arguments - **episode** (episode_enum) - Optional - If omitted, returns the hero of the whole saga. If provided, returns the hero of that particular episode. - **human** (human_type) ### Arguments - **id** (GraphQLNonNull(GraphQLString)) - Required - id of the human - **droid** (droid_type) ### Arguments - **id** (GraphQLNonNull(GraphQLString)) - Required - id of the droid ``` -------------------------------- ### Droid Type Definition Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Defines the 'Droid' object type, specifying its fields, descriptions, and interfaces. ```APIDOC ## Droid Type ### Description Represents a mechanical creature in the Star Wars universe. ### Fields - **id** (GraphQLNonNull(GraphQLString)) - Description: The id of the droid. - **name** (GraphQLString) - Description: The name of the droid. - **friends** (GraphQLList(character_interface)) - Description: The friends of the droid, or an empty list if they have none. - **appearsIn** (GraphQLList(episode_enum)) - Description: Which movies they appear in. - **secretBackstory** (GraphQLString) - Description: Construction date and the name of the designer. - **primaryFunction** (GraphQLString) - Description: The primary function of the droid. ### Interfaces - character_interface ``` -------------------------------- ### Implement Droid Fetching Resolver Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/resolvers.md Resolver function to query for a specific droid character by their ID using the `droid_data` dictionary. This is a direct data retrieval function. ```python def get_droid(root, _info, id): """Allows us to query for the droid with the given id.""" return droid_data.get(id) ``` -------------------------------- ### Define Human Object Type Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Define the 'Human' GraphQL object type, implementing the 'Character' interface and including specific fields like 'homePlanet'. ```python human_type = GraphQLObjectType('Human', lambda: { 'id': GraphQLField( GraphQLNonNull(GraphQLString), description='The id of the human.'), 'name': GraphQLField( GraphQLString, description='The name of the human.'), 'friends': GraphQLField( GraphQLList(character_interface), description='The friends of the human,' ' or an empty list if they have none.', resolve=get_friends), 'appearsIn': GraphQLField( GraphQLList(episode_enum), description='Which movies they appear in.'), 'homePlanet': GraphQLField( GraphQLString, description='The home planet of the human, or null if unknown.'), 'secretBackstory': GraphQLField( GraphQLString, resolve=get_secret_backstory, description='Where are they from' ' and how they came to be who they are.')}, ) ``` -------------------------------- ### Define Enum Values Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/sdl.md Manually define the server-side values for enum types when using SDL. This loop iterates through the enum values and assigns their corresponding Python enum values. ```python for name, value in schema.get_type('Episode').values.items(): value.value = EpisodeEnum[name].value ``` -------------------------------- ### Define Character Data Structures Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/resolvers.md Define dictionaries to hold data for different characters like Luke Skywalker, Darth Vader, and others. This data is used by resolver functions to fetch character information. ```python luke = dict( id='1000', name='Luke Skywalker', homePlanet='Tatooine', friends=['1002', '1003', '2000', '2001'], appearsIn=[4, 5, 6]) vader = dict( id='1001', name='Darth Vader', homePlanet='Tatooine', friends=['1004'], appearsIn=[4, 5, 6]) han = dict( id='1002', name='Han Solo', homePlanet=None, friends=['1000', '1003', '2001'], appearsIn=[4, 5, 6]) leia = dict( id='1003', name='Leia Organa', homePlanet='Alderaan', friends=['1000', '1002', '2000', '2001'], appearsIn=[4, 5, 6]) tarkin = dict( id='1004', name='Wilhuff Tarkin', homePlanet=None, friends=['1001'], appearsIn=[4]) human_data = { '1000': luke, '1001': vader, '1002': han, '1003': leia, '1004': tarkin} threepio = dict( id='2000', name='C-3PO', primaryFunction='Protocol', friends=['1000', '1002', '1003', '2001'], appearsIn=[4, 5, 6]) artoo = dict( id='2001', name='R2-D2', primaryFunction='Astromech', friends=['1000', '1002', '1003'], appearsIn=[4, 5, 6]) droid_data = { '2000': threepio, '2001': artoo} ``` -------------------------------- ### Handle Query Errors (Non-existent Field) Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/queries.md When a query attempts to access a non-existent field, `graphql_sync()` returns an `ExecutionResult` with errors. The error message often suggests the correct field name. ```python result = graphql_sync(schema, """ { human(id: "1000") { name homePlace } } """) print(result) ``` -------------------------------- ### Parse GraphQL Schema String without Location Info Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/parser.md When parsing, you can omit location information from the AST nodes by setting `no_location=True`. This results in a cleaner AST if source code locations are not needed. ```python document = parse(..., no_location=True) ``` -------------------------------- ### Create Enum Type using Python Dictionary Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Define a GraphQL enum type 'Episode' using a Python dictionary for its values. ```python episode_enum = GraphQLEnumType( 'Episode', {'NEWHOPE': 4, 'EMPIRE': 5, 'JEDI': 6}, description='One of the films in the Star Wars Trilogy') ``` -------------------------------- ### Attach Resolver to Extended Field Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/extension.md After extending the schema, attach a resolver function to the newly added field. This function will be called when the field is queried. ```python def get_last_name(human, info): return human['name'].rsplit(None, 1)[-1] schema.get_type('Human').fields['lastName'].resolve = get_last_name ``` -------------------------------- ### Extend GraphQL Schema with New Field Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/extension.md Use extend_schema to add a new field to an existing type. The extensions must be provided as a parsed AST. This function returns a new schema object and does not modify the original. ```python from graphql import extend_schema, parse schema = extend_schema(schema, parse(""" extend type Human { lastName: String } """, parse_options=None)) ``` -------------------------------- ### Define Droid GraphQL Object Type Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Defines the 'Droid' object type for the GraphQL schema, including its fields, interfaces, and description. This type represents a mechanical creature in the Star Wars universe. ```python droid_type = GraphQLObjectType('Droid', lambda: { 'id': GraphQLField( GraphQLNonNull(GraphQLString), description='The id of the droid.'), 'name': GraphQLField( GraphQLString, description='The name of the droid.'), 'friends': GraphQLField( GraphQLList(character_interface), description='The friends of the droid,' ' or an empty list if they have none.', resolve=get_friends, ), 'appearsIn': GraphQLField( GraphQLList(episode_enum), description='Which movies they appear in.'), 'secretBackstory': GraphQLField( GraphQLString, resolve=get_secret_backstory, description='Construction date and the name of the designer.'), 'primaryFunction': GraphQLField( GraphQLString, description='The primary function of the droid.') }, interfaces=[character_interface], description='A mechanical creature in the Star Wars universe.') ``` -------------------------------- ### Create Enum Type using Python Enum Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/schema.md Define a GraphQL enum type 'Episode' by mapping an underlying Python Enum class. ```python from enum import Enum class EpisodeEnum(Enum): NEWHOPE = 4 EMPIRE = 5 JEDI = 6 episode_enum = GraphQLEnumType( 'Episode', EpisodeEnum, description='One of the films in the Star Wars Trilogy') ``` -------------------------------- ### Implement Character Type Resolver Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/resolvers.md Resolver function to determine if a character is a 'Droid' or 'Human' based on their ID. This is useful for type checking within the GraphQL schema. ```python def get_character_type(character, _info, _type): return 'Droid' if character['id'] in droid_data else 'Human' ``` -------------------------------- ### GraphQL Validation Errors Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/validator.md The `validate()` function returns a list of `GraphQLError` objects detailing validation issues. These errors indicate problems like incorrect argument types, unknown fields, or missing subfields. ```python [GraphQLError( 'String cannot represent a non string value: NEWHOPE', locations=[SourceLocation(line=3, column=17)]), GraphQLError( "Cannot query field 'homePlace' on type 'Human'." " Did you mean 'homePlanet'?", locations=[SourceLocation(line=5, column=9)]), GraphQLError( "Field 'friends' of type '[Character]' must have a selection of subfields." " Did you mean 'friends { ... }'?", locations=[SourceLocation(line=6, column=9)])] ``` -------------------------------- ### Handle Resolver Errors Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/queries.md If a resolver function raises an error during query execution, the error is captured in the `errors` attribute of the `ExecutionResult`. The `data` attribute may contain partial results. ```python result = graphql_sync(schema, """ { hero(episode: EMPIRE) { name secretBackstory } } """) print(result) ``` -------------------------------- ### Introspection Query Result Structure Source: https://github.com/graphql-python/graphql-core/blob/main/docs/usage/introspection.md The `data` attribute of the introspection query result provides a dictionary representation of the GraphQL schema, including types, fields, and arguments. ```json { "__schema": { "queryType": {"name": "Query", "kind": "OBJECT"}, "mutationType": None, "subscriptionType": None, "types": [ {"kind": "OBJECT", "name": "Query", "description": None, "fields": [{ "name": "hero", "description": None, "args": [{"name": "episode", "description": ... }], ... }, ... ], ... }, ... ], ... } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.