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
Instrument your FastAPI app

Prometheus FastAPI Instrumentator A configurable and modular Prometheus Instrumentator for your FastAPI. Install prometheus-fastapi-instrumentator fro

Tim Schwenke 441 Jan 05, 2023
Prometheus exporter for Starlette and FastAPI

starlette_exporter Prometheus exporter for Starlette and FastAPI. The middleware collects basic metrics: Counter: starlette_requests_total Histogram:

Steve Hillier 225 Jan 05, 2023
fastapi-mqtt is extension for MQTT protocol

fastapi-mqtt MQTT is a lightweight publish/subscribe messaging protocol designed for M2M (machine to machine) telemetry in low bandwidth environments.

Sabuhi 144 Dec 28, 2022
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 562 Jan 01, 2023
Lazy package to start your project using FastAPI✨

Fastapi-lazy 🦥 Utilities that you use in various projects made in FastAPI. Source Code: https://github.com/yezz123/fastapi-lazy Install the project:

Yasser Tahiri 95 Dec 29, 2022
Simple example of FastAPI + Celery + Triton for benchmarking

You can see the previous work from: https://github.com/Curt-Park/producer-consumer-fastapi-celery https://github.com/Curt-Park/triton-inference-server

Jinwoo Park (Curt) 37 Dec 29, 2022
This project shows how to serve an ONNX-optimized image classification model as a web service with FastAPI, Docker, and Kubernetes.

Deploying ML models with FastAPI, Docker, and Kubernetes By: Sayak Paul and Chansung Park This project shows how to serve an ONNX-optimized image clas

Sayak Paul 104 Dec 23, 2022
Redis-based rate-limiting for FastAPI

Redis-based rate-limiting for FastAPI

Glib 6 Nov 14, 2022
FastAPI Socket.io with first-class documentation using AsyncAPI

fastapi-sio Socket.io FastAPI integration library with first-class documentation using AsyncAPI The usage of the library is very familiar to the exper

Marián Hlaváč 9 Jan 02, 2023
Github timeline htmx based web app rewritten from Common Lisp to Python FastAPI

python-fastapi-github-timeline Rewrite of Common Lisp htmx app _cl-github-timeline into Python using FastAPI. This project tries to prove, that with h

Jan Vlčinský 4 Mar 25, 2022
Local Telegram Bot With FastAPI & Ngrok

An easy local telegram bot server with python, fastapi and ngrok.

Ömer Faruk Özdemir 7 Dec 25, 2022
Signalling for FastAPI.

fastapi-signals Signalling for FastAPI.

Henshal B 7 May 04, 2022
SuperSaaSFastAPI - Python SaaS Boilerplate for building Software-as-Service (SAAS) apps with FastAPI, Vue.js & Tailwind

Python SaaS Boilerplate for building Software-as-Service (SAAS) apps with FastAP

Rudy Bekker 31 Jan 10, 2023
LuSyringe is a documentation injection tool for your classes when using Fast API

LuSyringe LuSyringe is a documentation injection tool for your classes when using Fast API Benefits The main benefit is being able to separate your bu

Enzo Ferrari 2 Sep 06, 2021
Light, Flexible and Extensible ASGI API framework

Starlite Starlite is a light and flexible ASGI API framework. Using Starlette and pydantic as foundations. Check out the Starlite documentation 📚 Cor

1.5k Jan 04, 2023
Drop-in MessagePack support for ASGI applications and frameworks

msgpack-asgi msgpack-asgi allows you to add automatic MessagePack content negotiation to ASGI applications (Starlette, FastAPI, Quart, etc.), with a s

Florimond Manca 128 Jan 02, 2023
flask extension for integration with the awesome pydantic package

flask extension for integration with the awesome pydantic package

249 Jan 06, 2023
FastAPI interesting concepts.

fastapi_related_stuffs FastAPI interesting concepts. FastAPI version :- 0.70 Python3 version :- 3.9.x Steps Test Django Like settings export FASTAPI_S

Mohd Mujtaba 3 Feb 06, 2022
Code for my FastAPI tutorial

FastAPI tutorial Code for my video tutorial FastAPI tutorial What is FastAPI? FastAPI is a high-performant REST API framework for Python. It's built o

José Haro Peralta 9 Nov 15, 2022
Voucher FastAPI

Voucher-API Requirement Docker Installed on system Libraries Pandas Psycopg2 FastAPI PyArrow Pydantic Uvicorn How to run Download the repo on your sys

Hassan Munir 1 Jan 26, 2022