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
Small flask based opds catalog designed to serve a directory via OPDS

teenyopds Small flask based opds catalog designed to serve a directory via OPDS, it has currently only been verified to work with KyBook 3 on iOS but

Adam Furbee 4 Jul 14, 2022
flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics v

249 Jan 06, 2023
Adds SQLAlchemy support to Flask

Flask-SQLAlchemy Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy

The Pallets Projects 3.9k Dec 29, 2022
Flask Multiple Database Login

Flask Multiple Database Login Handle login with flask using two diferent databases: UE | European; BR | Brazilian; These databases are separed to resp

Jose Pedro 1 Dec 16, 2021
A multi-container docker application. Implemented and dockerized a web-based service leveraging Flask

Flask-based-web-service-with-Docker-compose A multi-container docker application. Implemented and dockerized a web-based service leveraging Flask. Des

Jayshree Rathi 1 Jan 15, 2022
flask-reactize is a boostrap to serve any React JS application via a Python back-end, using Flask as web framework.

flask-reactize Purpose Developing a ReactJS application requires to use nodejs as back end server. What if you want to consume external APIs: how are

Julien Chomarat 4 Jan 11, 2022
A live chat built with python(flask + gevent + apscheduler) + redis

a live chat room built with python(flask / gevent / apscheduler) + redis Basic Architecture Screenshot Install cd /path/to/source python bootstrap.py

Limboy 309 Nov 13, 2022
Python3🐍 webApp to display your current playing music on OBS Studio.

Spotify Overlay A Overlay to display on Obs Studio or any related video/stream recorder, the current music that is playing on your Spotify. Installati

carlitos 0 Oct 17, 2022
Curso Desenvolvimento avançado Python com Flask e REST API

Curso Desenvolvimento avançado Python com Flask e REST API Curso da Digital Innovation One Professor: Rafael Galleani Conteudo do curso Introdução ao

Elizeu Barbosa Abreu 1 Nov 14, 2021
A simple example using Flask inside a container

This is a simple example of how create a container for a Python Flask Web Application using Docker.

Fazt Web 8 Aug 30, 2022
Pf-flask-rest-com - Flask REST API Common Implementation by Problem Fighter Library

In the name of God, the Most Gracious, the Most Merciful. PF-Flask-Rest-Com Docu

Problem Fighter 3 Jan 15, 2022
É uma API feita em Python e Flask que pesquisa informações em uma tabela .xlsx e retorna o resultado.

API de rastreamento de pacotes É uma API feita em Python e Flask que pesquisa informações de rastreamento de pacotes em uma tabela .xlsx e retorna o r

Marcos Beraldo Barros 4 Jun 27, 2021
A simple application builder. Made with python.

Python Flask Server Template Check the Github Repository for updates Flask is an application builder. It is very common in Python but can also be used

1 Jan 09, 2022
Full text search for flask.

flask-msearch Installation To install flask-msearch: pip install flask-msearch # when MSEARCH_BACKEND = "whoosh" pip install whoosh blinker # when MSE

honmaple 197 Dec 29, 2022
Harmony, a discord clone, allows users to chat with other users in real time via servers, channels, and direct messages

Harmony, a discord clone, allows users to chat with other users in real time via servers, channels, and direct messages

Seth Holland 3 Feb 03, 2022
Flask Boilerplate - Paper Kit Design | AppSeed

Flask Paper Kit Open-Source Web App coded in Flask Framework - Provided by AppSeed Web App Generator. App Features: SQLite database SQLAlchemy ORM Ses

App Generator 86 Nov 29, 2021
Source code for backpainfree.org - a Q&A platform similar to StackOverFlow

Source code for backpainfree.org - a Q&A platform similar to StackOverFlow, which is designed specifically for people with back pain problems. Users can ask questions, post answers and comments, vote

Olzhas Arystanov 8 Dec 11, 2022
Implement Instagram with flask

Blue club The place where manly men live and breathe. Move to Notion Move to Fig

3 Apr 07, 2022
Flask pre-setup architecture. This can be used in any flask project for a faster and better project code structure.

Flask pre-setup architecture. This can be used in any flask project for a faster and better project code structure. All the required libraries are already installed easily to use in any big project.

Ajay kumar sharma 5 Jun 14, 2022
Adds Injector support to Flask.

Flask-Injector Adds Injector support to Flask, this way there's no need to use global Flask objects, which makes testing simpler. Injector is a depend

Alec Thomas 246 Dec 28, 2022