Python ariadne: Difference between revisions

From wikinotes
(Created page with "A schema-first approach to building graphql APIs in python. = Documentation = <blockquote> {| class="wikitable" |- | official docs || https://ariadnegraphql.org/docs/...")
 
No edit summary
Line 9: Line 9:
|}
|}
</blockquote><!-- Documentation -->
</blockquote><!-- Documentation -->
= Example =
<blockquote>
<syntaxhighlight lang="python">
#!/usr/bin/env python
# ${PROJECT}/app.py
import ariadne
from ariadne import asgi
# Your GraphQL SDL Schema
type_defs = ariadne.gql("""
    type Query {
        hello: String!
    }
""")
# Resolvers for Query 'hello'
query = ariadne.QueryType()
@query.field("hello")
def resolve_hello(parent, info):
    request = info.context["request"]
    user_agent = request.headers.get("user-agent", "guest")
    return "Hello, %s!" % user_agent
# Build Schema, and create app
schema = ariadne.make_executable_schema(type_defs, query)
graphql_app = asgi.GraphQL(schema, debug=True)
</syntaxhighlight>
<syntaxhighlight lang="bash">
# run server
pip install ariadne
pip install uvicorn
uvicorn app:graphql_app
</syntaxhighlight>
<syntaxhighlight lang="bash">
# execute graphql query
curl -X POST \
    -H 'Content-Type: application/json' \
    -d '{"query": "query { hello }"}' \
    http://127.0.0.1:8000
</syntaxhighlight>
</blockquote><!-- Example -->

Revision as of 12:53, 4 September 2021

A schema-first approach to building graphql APIs in python.

Documentation

official docs https://ariadnegraphql.org/docs/intro

Example

#!/usr/bin/env python
# ${PROJECT}/app.py

import ariadne
from ariadne import asgi


# Your GraphQL SDL Schema
type_defs = ariadne.gql("""
    type Query {
        hello: String!
    }
""")

# Resolvers for Query 'hello'
query = ariadne.QueryType()

@query.field("hello")
def resolve_hello(parent, info):
    request = info.context["request"]
    user_agent = request.headers.get("user-agent", "guest")
    return "Hello, %s!" % user_agent

# Build Schema, and create app
schema = ariadne.make_executable_schema(type_defs, query)
graphql_app = asgi.GraphQL(schema, debug=True)
# run server
pip install ariadne
pip install uvicorn

uvicorn app:graphql_app
# execute graphql query
curl -X POST \
    -H 'Content-Type: application/json' \
    -d '{"query": "query { hello }"}' \
    http://127.0.0.1:8000