Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Python schema-first GraphQL library based on GraphQL-core.
Python 3.7+
pip install python-gql
import graphql
from gql import gql, make_schema, query, mutate
type_defs = gql("""
type Query {
hello(name: String!): String!
}
type Post {
author: String!
comment: String!
}
type Mutation {
addPost(author: String, comment: String): Post!
}
""")
@query
def hello(parent, info, name: str) -> str:
return name
@mutate
def add_post(parent, info, author: str = None, comment: str = None) -> dict:
return {'author': author, 'comment': comment}
schema = make_schema(type_defs)
q = """
query {
hello(name: "graphql")
}
"""
result = graphql.graphql_sync(schema, q)
print(result.data)
# result: {'hello': 'graphql'}
q = """
mutation {
addPost(author: "syfun", comment: "This is a good library.") {
author
comment
}
}
"""
result = graphql.graphql_sync(schema, q)
print(result.data)
# result: {'addPost': {'author': 'syfun', 'comment': 'This is a good library.'}}
This library is schema-first
, so you must build a schema explicitly.
Here, we have two methods to build a schema, by a type definitions
or a schema file
.
from gql import gql, make_schema
type_defs = gql("""
type Query {
hello(name: String!): String!
}
""")
schema = make_schema(type_defs)
gql
function will check your type definitions syntax.
from gql import make_schema_from_file
schema = make_schema_from_file('./schema.graphql')
In Python,
decorator
is my favorite function, it save my life!
We can use query
, mutation
, subscribe
to bind functions to GraphQL resolvers.
@query
def hello(parent, info, name: str) -> str:
return name
These decorators will auto convert the snake function to camel one.
# add_port => addPost
@mutate
def add_post(parent, info, author: str = None, comment: str = None) -> dict:
return {'author': author, 'comment': comment}
When the funcation name different from the resolver name, you can give a name argument to these decorators.
@query('hello')
def hello_function(parent, info, name: str) -> str:
return name
About subscribe
, please see gql-subscriptions.
Use enum_type
decorator with a python Enum class.
from enum import Enum
from gql import enum_type
@enum_type
class Gender(Enum):
MALE = 1
FEMALE = 2
Use scalar_type
decorator with a python class.
from gql import scalar_type
@scalar_type
class JSONString:
description = "The `JSONString` represents a json string."
@staticmethod
def serialize(value: Any) -> str:
return json.dumps(value)
@staticmethod
def parse_value(value: Any) -> dict:
if not isinstance(value, str):
raise TypeError(f'JSONString cannot represent non string value: {inspect(value)}')
return json.loads(value)
@staticmethod
def parse_literal(ast, _variables=None):
if isinstance(ast, StringValueNode):
return json.loads(ast.value)
return INVALID
from gql import gql, make_schema, query, SchemaDirectiveVisitor
from gql.resolver import default_field_resolver
type_defs = gql("""
directive @upper on FIELD_DEFINITION
type Query {
hello(name: String!): String! @upper
}
""")
class UpperDirective(SchemaDirectiveVisitor):
def visit_field_definition(self, field, object_type):
original_resolver = field.resolve or default_field_resolver
def resolve_upper(obj, info, **kwargs):
result = original_resolver(obj, info, **kwargs)
if result is None:
return None
return result.upper()
field.resolve = resolve_upper
return field
schema = make_schema(type_defs, directives={'upper': UpperDirective})
Thanks to Ariadne
FAQs
Python schema-first GraphQL library based on GraphQL-core
We found that python-gql demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.