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
API Simples com python utilizando a biblioteca FastApi

api-fastapi-python API Simples com python utilizando a biblioteca FastApi Para rodar esse script são necessárias duas bibliotecas: Fastapi: Comando de

Leonardo Grava 0 Apr 29, 2022
cookiecutter template for web API with python

Python project template for Web API with cookiecutter What's this This provides the project template including minimum test/lint/typechecking package

Hitoshi Manabe 4 Jan 28, 2021
api versioning for fastapi web applications

fastapi-versioning api versioning for fastapi web applications Installation pip install fastapi-versioning Examples from fastapi import FastAPI from f

Dean Way 472 Jan 02, 2023
FastAPI application and service structure for a more maintainable codebase

Abstracting FastAPI Services See this article for more information: https://camillovisini.com/article/abstracting-fastapi-services/ Poetry poetry inst

Camillo Visini 309 Jan 04, 2023
Generate modern Python clients from OpenAPI

openapi-python-client Generate modern Python clients from OpenAPI 3.x documents. This generator does not support OpenAPI 2.x FKA Swagger. If you need

Triax Technologies 558 Jan 07, 2023
Adds GraphQL support to your Flask application.

Flask-GraphQL Adds GraphQL support to your Flask application. Usage Just use the GraphQLView view from flask_graphql from flask import Flask from flas

GraphQL Python 1.3k Dec 31, 2022
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 310 Dec 14, 2022
A set of demo of deploying a Machine Learning Model in production using various methods

Machine Learning Model in Production This git is for those who have concern about serving your machine learning model to production. Overview The tuto

Vo Van Tu 53 Sep 14, 2022
FastAPI Skeleton App to serve machine learning models production-ready.

FastAPI Model Server Skeleton Serving machine learning models production-ready, fast, easy and secure powered by the great FastAPI by Sebastián Ramíre

268 Jan 01, 2023
A simple example of deploying FastAPI as a Zeit Serverless Function

FastAPI Zeit Now Deploy a FastAPI app as a Zeit Serverless Function. This repo deploys the FastAPI SQL Databases Tutorial to demonstrate how a FastAPI

Paul Weidner 26 Dec 21, 2022
Cube-CRUD is a simple example of a REST API CRUD in a context of rubik's cube review service.

Cube-CRUD is a simple example of a REST API CRUD in a context of rubik's cube review service. It uses Sqlalchemy ORM to manage the connection and database operations.

Sebastian Andrade 1 Dec 11, 2021
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
Docker Sample Project - FastAPI + NGINX

Docker Sample Project - FastAPI + NGINX Run FastAPI and Nginx using Docker container Installation Make sure Docker is installed on your local machine

1 Feb 11, 2022
REST API with FastAPI and PostgreSQL

REST API with FastAPI and PostgreSQL To have the same data in db: create table CLIENT_DATA (id SERIAL PRIMARY KEY, fullname VARCHAR(50) NOT NULL,email

Luis Quiñones Requelme 1 Nov 11, 2021
Signalling for FastAPI.

fastapi-signals Signalling for FastAPI.

Henshal B 7 May 04, 2022
FastAPI CRUD template using Deta Base

Deta Base FastAPI CRUD FastAPI CRUD template using Deta Base Setup Install the requirements for the CRUD: pip3 install -r requirements.txt Add your D

Sebastian Ponce 2 Dec 15, 2021
Dead-simple mailer micro-service for static websites

Mailer Dead-simple mailer micro-service for static websites A free and open-source software alternative to contact form services such as FormSpree, to

Romain Clement 42 Dec 21, 2022
Simple notes app backend using Python's FastAPI framework.

my-notes-app Simple notes app backend using Python's FastAPI framework. Route "/": User login (GET): return 200, list of all of their notes; User sign

José Gabriel Mourão Bezerra 2 Sep 17, 2022
Twitter API monitor with fastAPI + MongoDB

Twitter API monitor with fastAPI + MongoDB You need to have a file .env with the following variables: DB_URL="mongodb+srv://mongodb_path" DB_URL2=

Leonardo Ferreira 3 Apr 08, 2022
Qwerkey is a social media platform for connecting and learning more about mechanical keyboards built on React and Redux in the frontend and Flask in the backend on top of a PostgreSQL database.

Flask React Project This is the backend for the Flask React project. Getting started Clone this repository (only this branch) git clone https://github

Peter Mai 22 Dec 20, 2022