Adds GraphQL support to your Flask application.

Overview

Flask-GraphQL

Adds GraphQL support to your Flask application.

travis pypi Anaconda-Server Badge coveralls

Usage

Just use the GraphQLView view from flask_graphql

from flask import Flask
from flask_graphql import GraphQLView

from schema import schema

app = Flask(__name__)

app.add_url_rule('/graphql', view_func=GraphQLView.as_view(
    'graphql',
    schema=schema,
    graphiql=True,
))

# Optional, for adding batch query support (used in Apollo-Client)
app.add_url_rule('/graphql/batch', view_func=GraphQLView.as_view(
    'graphql',
    schema=schema,
    batch=True
))

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

This will add /graphql endpoint to your app and enable the GraphiQL IDE.

Special Note for Graphene v3

If you are using the Schema type of Graphene library, be sure to use the graphql_schema attribute to pass as schema on the GraphQLView view. Otherwise, the GraphQLSchema from graphql-core is the way to go.

More info at Graphene v3 release notes and GraphQL-core 3 usage.

Supported options for GraphQLView

  • schema: The GraphQLSchema object that you want the view to execute when it gets a valid request.
  • context: A value to pass as the context_value to graphql execute function. By default is set to dict with request object at key request.
  • root_value: The root_value you want to provide to graphql execute.
  • pretty: Whether or not you want the response to be pretty printed JSON.
  • graphiql: If True, may present GraphiQL when loaded directly from a browser (a useful tool for debugging and exploration).
  • graphiql_version: The graphiql version to load. Defaults to "1.0.3".
  • graphiql_template: Inject a Jinja template string to customize GraphiQL.
  • graphiql_html_title: The graphiql title to display. Defaults to "GraphiQL".
  • batch: Set the GraphQL view as batch (for using in Apollo-Client or ReactRelayNetworkLayer)
  • middleware: A list of graphql middlewares.
  • encode: the encoder to use for responses (sensibly defaults to graphql_server.json_encode).
  • format_error: the error formatter to use for responses (sensibly defaults to graphql_server.default_format_error.
  • subscriptions: The GraphiQL socket endpoint for using subscriptions in graphql-ws.
  • headers: An optional GraphQL string to use as the initial displayed request headers, if not provided, the stored headers will be used.
  • default_query: An optional GraphQL string to use when no query is provided and no stored query exists from a previous session. If not provided, GraphiQL will use its own default query.
  • header_editor_enabled: An optional boolean which enables the header editor when true. Defaults to false.
  • should_persist_headers: An optional boolean which enables to persist headers to storage when true. Defaults to false.

You can also subclass GraphQLView and overwrite get_root_value(self, request) to have a dynamic root value per request.

class UserRootValue(GraphQLView):
    def get_root_value(self, request):
        return request.user

Contributing

Since v3, flask-graphql code lives at graphql-server repository to keep any breaking change on the base package on sync with all other integrations. In order to contribute, please take a look at CONTRIBUTING.md.

Comments
  • Is this project still mantained?

    Is this project still mantained?

    @syrusakbary thank you for this great project! I noticed that there have been a lot of commits since the last release, of which the last one was 6 months ago. Are you still planning on working on this project?

    Best regards

    opened by lucasrcosta 9
  • Update context and root executor options

    Update context and root executor options

    📦 Enhancement

    Fixes #70 and Fixes #71

    • [x] Bump graphl-core minimum version to 2.3 (was 2.1).
    • [x] Provide context_value and root_value to executor options (was context and root).
    opened by KingDarBoja 5
  • How to get request headers when resolving field?

    How to get request headers when resolving field?

    What's the right way to get request header when resolving a query/mutation? A related issue, #17, lead me to believe that info.context.headers will work but I'm finding that doesn't exist when I try to print it:

     ❮❮❮ curl -i -H 'Content-Type: application/json' -H 'x-authorization-info: testing' -X POST -d '{"query": "query { latestSnapshot { url } }"}' http://localhost:5000/graphql
    HTTP/1.0 200 OK
    Content-Type: application/json
    Content-Length: 160
    Server: Werkzeug/0.14.1 Python/3.6.7
    Date: Thu, 18 Apr 2019 22:21:51 GMT
    
    {"errors":[{"message":"'dict' object has no attribute 'headers'","locations":[{"line":1,"column":9}],"path":["latestSnapshot"]}],"data":{"latestSnapshot":null}}% 
    

    with a resolver of:

        def resolve_latest_snapshot(self, info: ResolveInfo, org_id: Optional[int] = None) -> models.Snapshot:
            print(info.context.headers)
            # more stuff
    

    I have flask-graphql version 2.0.0.

    EDIT: other related packages I have:

    graphene==2.1.3
    graphql-core==2.1
    graphql-relay==0.4.5
    graphql-server-core==1.1.1
    graphene-sqlalchemy==2.1.1
    
    opened by paymog 4
  • Use context option (if provided)

    Use context option (if provided)

    Related to https://github.com/graphql-python/flask-graphql/issues/18

    Currently, the GraphQLView class accepts the context keyword argument when initializing, but it's not using it to set the context_value when executing the query.

    This PR modifies the get_context instance method inside GraphQLView so that the context option is used when it is provided, defaulting to request otherwise.

    opened by luisincrespo 4
  • Flask-GraphQL now returns warnings when using `graphql-core

    Flask-GraphQL now returns warnings when using `graphql-core

    Now that the minimum version of graphql-core was bumped to >=2.3 we're now seeing warnings returning when running tests that leverage Flask-GraphQL.

    Here's the relevant diff between graphql-core 2.2.1 and 2.3: https://github.com/graphql-python/graphql-core/compare/v2.2.1...v2.3.0#diff-a2c439ae03cccc507934c1377530d14aL74-L87

    In graphqlview.py - arguments are being passed as root and context though it seems these arguments are getting deprecated in favor of root_value and context_value.

    https://github.com/graphql-python/flask-graphql/blob/0137ca1315d811a7e01a1d256e41c74bc1c3fc2c/flask_graphql/graphqlview.py#L92-L93

    Here's the relevant DeprecationWarning

    DeprecationWarning: The 'context' alias has been deprecated. Please use 'context_value' instead.
    DeprecationWarning: The 'root' alias has been deprecated. Please use 'root_value' instead.
    
    opened by traviscook21 3
  • Upgrade to graphql-core v3

    Upgrade to graphql-core v3

    Hi, I'm currently looking at upgrading an application to graphql-core v3 (graphql-core-next) and I was wondering if there are any plans to create a version that would be compatible.

    Besides this package there's graphene as the main dependency and they have released a pre-release that is compatible with graphql-core v3

    opened by fhennig 3
  • Customizable HTML title in GraphiQL

    Customizable HTML title in GraphiQL

    It's nice to have an HTML <title> element on the page, so that it's easier for the developer to identify which browser tab is which. This pull request adds a customizable <title> element, so that you can make the title refer to your project if you want.

    opened by singingwolfboy 3
  • Incompatible with graphql-core==3.0.0

    Incompatible with graphql-core==3.0.0

    graphql-core 3.0.0 was just released 3 days ago and now my builds are breaking. I have had to specify graphql-core==2.2.1 in my requirements.txt to fix this. I'm guessing that the Flask-Graphql module dependencies need updated to prevent graqhql-core>=3.

    Python: 3.7.5 Flask-Graphql: 2.0.0 graphql-core: 3.0.0

    Truncated stack trace:

    ...
      File "/opt/python3.7/lib/python3.7/site-packages/flask_graphql/__init__.py", line 1, in <module>
        from .blueprint import GraphQL
      File "/opt/python3.7/lib/python3.7/site-packages/flask_graphql/blueprint.py", line 5, in <module>
        from .graphqlview import GraphQLView
      File "/opt/python3.7/lib/python3.7/site-packages/flask_graphql/graphqlview.py", line 7, in <module>
        from graphql_server import (HttpQueryError, default_format_error,
      File "/opt/python3.7/lib/python3.7/site-packages/graphql_server/__init__.py", line 5, in <module>
        from graphql import get_default_backend
    ImportError: cannot import name 'get_default_backend' from 'graphql' (/opt/python3.7/lib/python3.7/site-packages/graphql/__init__.py)
    
    opened by crunk1 2
  • Multipart Request Spec

    Multipart Request Spec

    As mentioned in #33, it would be nice to support file uploads. This PR implements the multipart request spec for graphql-flask.

    If it's preferable to move the logic somewhere else (either a more general library or a plugin), please let me know.

    opened by davidroeca 2
  • Fix typo in link format in README.md

    Fix typo in link format in README.md

    I do not really know why there are 2 READMEs in this project. :confused: But the *.md, rendered by Github, have a typo that breaks the formatting. :v:

    opened by rafaelcaricio 2
  • Fail to decode unicode payloads

    Fail to decode unicode payloads

    GraphQL requests that contain unicode characters fails with the error message 'POST body sent invalid JSON.'

    I was able to fix it by adding utf-8 parameter to decode method .

    graphqlview.py L132: request_json = json.loads(request.data.decode('utf-8'))

    opened by varuna82 2
  • Error when importing flask_graphql

    Error when importing flask_graphql

    Unable to import this library into my project. I always get an ImportError even if I create a new project with only one import.

    My code api.py

    from http.client import HTTPException
    from multiprocessing import AuthenticationError
    import os
    from flask import Flask, request, jsonify, abort
    from sqlalchemy import exc
    import json
    from flask_cors import CORS
    from graphene import ObjectType, String, Schema
    from flask_graphql import GraphQLView
    
    app = Flask(__name__)
    

    My requirements.txt In the beginning, I specify the version of each library, but there was an error. To solve the error, I removed the FLask-GraphQL because it is in conflict with other graphene dependency. As it said, could not import flask_graphql I remove graphene version and specify the last version in the Flask-GraphQL so that my project use the last version of this library and solve the dependency conflict with graphene. But always the same error.

    Flask == 2.2.2
    Flask-SQLAlchemy == 3.0.2
    Jinja2 == 3.1.2
    pylint == 2.15.9
    Flask-Cors == 3.0.10
    graphene  #For graphql python support
    Flask-GraphQL == 2.0.1
    

    Error message

    Error: While importing 'src.api', an ImportError was raised:
    
    Traceback (most recent call last):
      File "/home/sticlab/Documents/NotebookProject/rasa-car-location-services/backend/venv/lib/python3.10/site-packages/flask/cli.py", line 218, in locate_app
        __import__(module_name)
      File "/home/sticlab/Documents/NotebookProject/rasa-car-location-services/backend/src/api.py", line 9, in <module>
        from flask_graphql import GraphQLView
      File "/home/sticlab/Documents/NotebookProject/rasa-car-location-services/backend/venv/lib/python3.10/site-packages/flask_graphql/__init__.py", line 1, in <module>
        from .blueprint import GraphQL
      File "/home/sticlab/Documents/NotebookProject/rasa-car-location-services/backend/venv/lib/python3.10/site-packages/flask_graphql/blueprint.py", line 5, in <module>
        from .graphqlview import GraphQLView
      File "/home/sticlab/Documents/NotebookProject/rasa-car-location-services/backend/venv/lib/python3.10/site-packages/flask_graphql/graphqlview.py", line 7, in <module>
        from graphql_server import (HttpQueryError, default_format_error,
      File "/home/sticlab/Documents/NotebookProject/rasa-car-location-services/backend/venv/lib/python3.10/site-packages/graphql_server/__init__.py", line 2, in <module>
        from collections import namedtuple, MutableMapping
    ImportError: cannot import name 'MutableMapping' from 'collections' (/usr/lib/python3.10/collections/__init__.py)
    
    opened by stic-lab 0
  • Dependency conflicts with graphene>=3.0

    Dependency conflicts with graphene>=3.0

    Attempting a pip install flask_graphql ends up with a dependency conflict.

    Logs

    ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
    graphql-relay 3.2.0 requires graphql-core<3.3,>=3.2, but you have graphql-core 2.3.2 which is incompatible.
    graphene 3.1 requires graphql-core<3.3,>=3.1, but you have graphql-core 2.3.2 which is incompatible.
    gql 3.3.0 requires graphql-core<3.3,>=3.2, but you have graphql-core 2.3.2 which is incompatible.
    
    opened by leeyspaul 2
  • which graphiql version is using?

    which graphiql version is using?

    I have Flask-GraphQL==2.0.1 installed and inside Chrome it is requiring dependencies like

    http://cdn.jsdelivr.net/npm/[email protected]/graphiql.min.js note: currently the latest version in jsdelivr is 1.0.6

    however the github readme says

    graphiql_version: The graphiql version to load. Defaults to "1.0.3".

    reallly? If I set graphiql_version=1.0.3 explicitly, then Chrome throws error

    Uncaught Error: GraphiQL 0.18.0 and after is not compatible with React 15 or below

    I did not find anywhere the render_graphiql.py set the variable to "1.0.3" In my local drive is GRAPHIQL_VERSION = '0.11.11'; and gitlab GRAPHIQL_VERSION = '0.7.1'

    opened by qinst64 2
  • CSRF Exemption?

    CSRF Exemption?

    With Django and Graphene users can do the following to exempt the graphql endpoint from CSRF authentication.

    urlpatterns = [
        path("admin/", admin.site.urls),
        path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True, schema=schema))),
    ]
    

    How can one do this with Flask-GraphQL?

    app.add_url_rule(
        '/graphql',
        view_func=GraphQLView.as_view(
            'graphql',
            schema=schema,
            graphiql=True
    
        )
    )```
    opened by KrishyV 1
Releases(v2.0.1)
  • v2.0.1(Dec 5, 2019)

  • v2.0.0(Jul 19, 2018)

    Changelog

    • Added official support for Python 3.7 https://github.com/graphql-python/flask-graphql/commit/64bab0799666a3a0a49b55637ef5c96d731003ec
    • Use stable version of graphql-server-core (1.1) https://github.com/graphql-python/flask-graphql/commit/3d607a0bd96321840b1960126900be46a709ba89
    Source code(tar.gz)
    Source code(zip)
  • v2.0rc0(Jun 5, 2018)

    Changelog

    • Added support for pluggable backends 068ee717f97f7b156dda24645c5a2616dadc2121
    • Updated GraphiQL 298d89009b5c517ddc34e2bf53291c743225ca97
    • Fixed docs 23fb85c6c8067c557b934c5f1d5f09eee80fa64e
    Source code(tar.gz)
    Source code(zip)
  • v1.4.1(Feb 24, 2017)

    Changelog

    • Don't send referrer to jsdelivr f7a5b3644aa290065c0bdb9ceac44e71d7f7acd5
    • Refactored GraphiQL rendering 5fb5cd66bb817900da84c54640802500f7812a1e
    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Dec 14, 2016)

    Changelog

    • Added support for batch GraphQL queries #21
    • Prettify result of query when using GraphiQL b26ee010954b73acd2e18e05c74508f1699d7e1f
    • Add context as attribute to the view 31de8ccf9af4236f0b8faeaa5d7056e5809f88e1
    • Added GraphiQL template injection 2128bf54d03d833f30553c60204f80d9e807b83d

    Extra

    • Improved testing (context and pretty extra tests)
    Source code(tar.gz)
    Source code(zip)
Owner
GraphQL Python
GraphQL Python
GraphQL security auditing script with a focus on performing batch GraphQL queries and mutations

BatchQL BatchQL is a GraphQL security auditing script with a focus on performing batch GraphQL queries and mutations. This script is not complex, and

Assetnote 267 Dec 24, 2022
This is a graphql api build using ariadne python that serves a graphql-endpoint at port 3002 to perform language translation and identification using deep learning in python pytorch.

Language Translation and Identification this machine/deep learning api that will be served as a graphql-api using ariadne, to perform the following ta

crispengari 2 Dec 30, 2021
A Django GraphQL Starter that uses graphene and graphene_django to interface GraphQL.

Django GraphQL Starter GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data... According to the doc

0101 Solutions 1 Jan 10, 2022
MGE-GraphQL is a Python library for building GraphQL mutations fast and easily

MGE-GraphQL Introduction MGE-GraphQL is a Python library for building GraphQL mutations fast and easily. Data Validations: A similar data validation w

MGE Software 4 Apr 23, 2022
ASGI support for the Tartiflette GraphQL engine

tartiflette-asgi is a wrapper that provides ASGI support for the Tartiflette Python GraphQL engine. It is ideal for serving a GraphQL API over HTTP, o

tartiflette 99 Dec 27, 2022
ASGI support for the Tartiflette GraphQL engine

tartiflette-asgi is a wrapper that provides ASGI support for the Tartiflette Python GraphQL engine. It is ideal for serving a GraphQL API over HTTP, o

tartiflette 99 Dec 27, 2022
Support for Apollo's Automatic Persisted Queries in Strawberry GraphQL 🍓

strawberry-apollo-apq Supporting Apollo's automatic persisted queries in Strawberry GraphQL ?? Notes Don't use this for production yet, unless you kno

Bas 3 May 17, 2022
(Now finding maintainer) 🐍A Pythonic way to provide JWT authentication for Flask-GraphQL

Flask-GraphQL-Auth What is Flask-GraphQL-Auth? Flask-GraphQL-Auth is JWT decorator for flask-graphql inspired from Flask-JWT-Extended. all you have to

Seonghyeon Kim 64 Feb 19, 2022
Django GraphQL To Do List Application

Django GraphQL Simple ToDo HOW TO RUN just run the following instructions: python -m venv venv pip install -r requirements.txt source venv/bin/activat

pedram shahsafi 1 Nov 13, 2021
Integrate GraphQL into your Django project.

Graphene-Django A Django integration for Graphene. ?? Join the community on Slack Documentation Visit the documentation to get started! Quickstart For

GraphQL Python 4k Dec 31, 2022
Pygitstats - a package that allows you to use the GitHub GraphQL API with ease in your Python programs

Pygitstats - a package that allows you to use the GitHub GraphQL API with ease in your Python programs

Dillon Barnes 4 Mar 29, 2022
GraphQL framework for Python

Graphene ?? Join the community on Slack We are looking for contributors! Please check the ROADMAP to see how you can help ❤️ The below readme is the d

GraphQL Python 7.5k Jan 1, 2023
tartiflette-aiohttp is a wrapper of aiohttp which includes the Tartiflette GraphQL Engine, do not hesitate to take a look of the Tartiflette project.

tartiflette-aiohttp is a wrapper of aiohttp which includes the Tartiflette GraphQL Engine. You can take a look at the Tartiflette API documentation. U

tartiflette 60 Nov 8, 2022
GraphQL is a query language and execution engine tied to any backend service.

GraphQL The GraphQL specification is edited in the markdown files found in /spec the latest release of which is published at https://graphql.github.io

GraphQL 14k Jan 1, 2023
GraphQL framework for Python

Graphene ?? Join the community on Slack We are looking for contributors! Please check the ROADMAP to see how you can help ❤️ The below readme is the d

GraphQL Python 7.5k Jan 1, 2023
Ariadne is a Python library for implementing GraphQL servers using schema-first approach.

Ariadne Ariadne is a Python library for implementing GraphQL servers. Schema-first: Ariadne enables Python developers to use schema-first approach to

Mirumee Labs 1.9k Jan 1, 2023
A library to help construct a graphql-py server supporting react-relay

Relay Library for GraphQL Python GraphQL-relay-py is the Relay library for GraphQL-core. It allows the easy creation of Relay-compliant servers using

GraphQL Python 143 Nov 15, 2022
GraphQL Engine built with Python 3.6+ / asyncio

Tartiflette is a GraphQL Server implementation built with Python 3.6+. Summary Motivation Status Usage Installation Installation dependencies Tartifle

tartiflette 839 Dec 31, 2022
Django registration and authentication with GraphQL.

Django GraphQL Auth Django registration and authentication with GraphQL. Demo About Abstract all the basic logic of handling user accounts out of your

pedrobern 301 Dec 9, 2022