Skip to content

Commit

Permalink
Added a custom server example using Flask
Browse files Browse the repository at this point in the history
See issue mirumee#125
  • Loading branch information
jrast committed Apr 1, 2019
1 parent 4e7625e commit 4a708b2
Showing 1 changed file with 75 additions and 1 deletion.
76 changes: 75 additions & 1 deletion docs/custom-server.rst
Expand Up @@ -116,4 +116,78 @@ The following example presents a basic GraphQL server using a Django framework::
response["errors"] = [format_error(e) for e in result.errors]

# Send response to client
return JsonResponse(response)
return JsonResponse(response)


Basic GraphQL server with Flask
--------------------------------

The following example presents a basic GraphQL server using a Flask::

from ariadne import gql, ResolverMap, make_executable_schema
from ariadne.constants import PLAYGROUND_HTML
from graphql import format_error, graphql_sync
from flask import Flask, request, jsonify


type_defs = gql("""
type Query {
hello: String!
}
""")


query = ResolverMap("Query")


@query.field("hello")
def resolve_hello(_, info):
request = info.context
user_agent = request.headers.get("User-Agent", "Guest")
return "Hello, %s!" % user_agent


app = Flask(__name__)


@app.route('/graphql/', methods=['GET'])
def graphql_playgroud():
"""Serving the GraphQL Playground

Note: This endpoint is not required if you do not want to provide the playground
But keep in mind that clients can still explore your API, for example by
using the GraphQL desktop app.
"""
return PLAYGROUND_HTML, 200


@app.route('/graphql/', methods=['POST'])
def graphql_server():
"""Serve GraphQL queries"""
data = request.get_json()
if data is None or not isinstance(data, dict):
return 'Bad Request', 400

variables = data.get('variables')
if variables and not isinstance(variables, dict):
return 'Bad Request', 400

# Note: Passing the request to the context is option. In Flask, the current
# request is allways accessible as flask.request.
result = graphql_sync(
make_executable_schema(type_defs, query),
data.get('query'),
context_value=request,
variable_values=variables,
operation_name=data.get('operationName')
)

response = {"data": result.data}
if result.errors:
response["errors"] = [format_error(e) for e in result.errors]

return jsonify(response)


if __name__ == '__main__':
app.run(debug=True)

0 comments on commit 4a708b2

Please sign in to comment.