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
Lux Academy & Data Science East Africa Python Boot Camp, Building and Deploying Flask Application Using Docker Demo App.

Flask and Docker Application Demo A Docker image is a read-only, inert template that comes with instructions for deploying containers. In Docker, ever

Harun Mbaabu Mwenda 11 Oct 29, 2022
REST API built using flask framework that used for managing bookmarks by individual users.

Bookmarks REST API REST API built using flask framework that used for managing bookmarks by individual users. API Consumers Note This app is built usi

Venkatesh Tantravahi 1 Dec 27, 2021
Intranet de la Rez Flask web app

IntraRez Application Flask de l'Intranet de la Rez. Exigences Python : Probablement = 3.10 à terme, pour l'instant = 3.8 suffit ; Autres packages Li

3 Jul 03, 2022
Boilerplate code for basic flask web apps

Flask Boilerplate This repository contains boilerplate code to start a project instantly It's mainly for projects which you plan to ship in less than

Abhishek 6 Sep 27, 2021
A Python, Flask login system

Python Login System This is a basic login + authenticason system for flask using Flask_Login and Flask_SQLAlchemy Get started on your own To use this

MrShoe 0 Feb 02, 2022
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
This is a simple web application using Python Flask and MySQL database.

Simple Web Application This is a simple web application using Python Flask and MySQL database. This is used in the demonstration of development of Ans

Alaaddin Tarhan 1 Nov 16, 2021
Open-source Flask Sample built on top of flask-dance library

Open-source Flask Sample built on top of flask-dance library. The project implements the social login for Github and Twitter - Originally coded by TestDriven.IO.

App Generator 4 Jul 26, 2022
A service made with Flask and Python to help you find the weather of your favorite cities.

Weather-App A service made with Flask and Python to help you find the weather of your favorite cities. Features Backend using Flask and Jinja Weather

Cauã Rinaldi 1 Nov 17, 2022
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
A flask template with Bootstrap 4, asset bundling+minification with webpack, starter templates, and registration/authentication.

cookiecutter-flask A Flask template for cookiecutter. (Supports Python ≥ 3.6) See this repo for an example project generated from the most recent vers

4.3k Jan 06, 2023
A swagger 2.0 spec extractor for flask

flask-swagger A Swagger 2.0 spec extractor for Flask You can now specify base path for yml files: app = Flask(__name__) @app.route("/spec") def spec(

Sling 457 Dec 02, 2022
SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).

Flask-SeaSurf SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF). CSRF vulnerabilities have been found in large and popular

Max Countryman 183 Dec 28, 2022
An extension to add support of Plugin in Flask.

An extension to add support of Plugin in Flask.

Doge Gui 31 May 19, 2022
A Python chat app built with Flask that runs in the browser.

A Python chat app built with Flask that runs in the browser. Designed for local area networks that are not connected to the Internet.

Leonard Kleber 1 Dec 23, 2021
Forum written for learning purposes in flask and sqlalchemy

Flask-forum forum written for learning purposes using SQLalchemy and flask How to install install requirements pip install sqlalchemy flask clone repo

Kamil 0 May 23, 2022
A YouTube webscraper made with flask.

YouTube Webscraper This website is for you to check all the stats on your favorite Youtube video! Technologies Python Flask HTML CSS Pafy Contributing

Proconsulates 3 Nov 25, 2021
5 Flask Projects To Get Started

5 Flask Projects Projects Made By Using Flask Projects List Rock Paper Scissor Game - A Simple Game Weather App - A OpenWeatherMap Scraper Task List -

Root_Arch 59 Dec 18, 2022
A Flask web application that manages student entries in a SQL database

Student Database App This is a Flask web application that manages student entries in a SQL database. Users can upload a CSV into the SQL database, mak

rebecca 1 Oct 20, 2021
A simple web application built using python flask. It can be used to scan SMEVai accounts for broken pages.

smescan A simple web application built using python flask. It can be used to scan SMEVai accounts for broken pages. Development Process Step 0: Clone

Abu Hurayra 1 Jan 30, 2022