Convert Figma logo to code with AI

graphql-python logoflask-graphql

Adds GraphQL support to your Flask application.

1,320
139
1,320
42

Top Related Projects

GraphQL framework for Python

Build powerful, efficient, and flexible GraphQL APIs with seamless Django integration.

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.

🧘 Rewrite of a fully-featured GraphQL Server with focus on easy setup, performance & great developer experience. The core of Yoga implements WHATWG Fetch API and can run/deploy on any JS environment.

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.

Quick Overview

Flask-GraphQL is a library that integrates GraphQL with Flask, a popular Python web framework. It allows developers to easily create GraphQL APIs using Flask and the Graphene library, providing a seamless way to implement GraphQL functionality in Flask applications.

Pros

  • Easy integration with existing Flask applications
  • Supports both GraphQL queries and mutations
  • Provides a GraphiQL interface for testing and exploring the API
  • Compatible with various GraphQL client libraries

Cons

  • Limited documentation and examples
  • Requires knowledge of both Flask and GraphQL concepts
  • May have performance limitations for large-scale applications
  • Not actively maintained (last update was in 2019)

Code Examples

  1. Basic Flask-GraphQL setup:
from flask import Flask
from flask_graphql import GraphQLView
import graphene

app = Flask(__name__)

class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="World"))

    def resolve_hello(self, info, name):
        return f"Hello {name}!"

schema = graphene.Schema(query=Query)

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

if __name__ == '__main__':
    app.run()
  1. Defining a mutation:
class CreateUser(graphene.Mutation):
    class Arguments:
        name = graphene.String()

    user = graphene.Field(lambda: User)

    def mutate(self, info, name):
        user = User(name=name)
        return CreateUser(user=user)

class Mutation(graphene.ObjectType):
    create_user = CreateUser.Field()

schema = graphene.Schema(query=Query, mutation=Mutation)
  1. Using custom middleware:
from graphql import GraphQLMiddleware

class LoggingMiddleware(GraphQLMiddleware):
    def resolve(self, next, root, info, **args):
        print(f"Resolving: {info.field_name}")
        return next(root, info, **args)

schema = graphene.Schema(query=Query)
app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, middleware=[LoggingMiddleware()]))

Getting Started

  1. Install Flask-GraphQL:

    pip install flask-graphql
    
  2. Create a Flask application and define your GraphQL schema:

    from flask import Flask
    from flask_graphql import GraphQLView
    import graphene
    
    app = Flask(__name__)
    
    class Query(graphene.ObjectType):
        hello = graphene.String()
    
        def resolve_hello(self, info):
            return "Hello, World!"
    
    schema = graphene.Schema(query=Query)
    
    app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True))
    
    if __name__ == '__main__':
        app.run()
    
  3. Run your Flask application and navigate to http://localhost:5000/graphql to access the GraphiQL interface.

Competitor Comparisons

GraphQL framework for Python

Pros of Graphene

  • More comprehensive GraphQL framework, supporting schema definition, resolvers, and execution
  • Can be used with multiple web frameworks (Flask, Django, etc.), not limited to Flask
  • Offers more advanced features like relay support and custom scalars

Cons of Graphene

  • Steeper learning curve due to more complex API and features
  • May be overkill for simple GraphQL implementations
  • Requires additional setup and configuration compared to Flask-GraphQL

Code Comparison

Graphene:

import graphene

class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="World"))

    def resolve_hello(self, info, name):
        return f"Hello {name}!"

schema = graphene.Schema(query=Query)

Flask-GraphQL:

from flask import Flask
from flask_graphql import GraphQLView

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

Summary

Graphene is a more feature-rich GraphQL framework for Python, offering greater flexibility and advanced capabilities. Flask-GraphQL, on the other hand, is a simpler integration specifically for Flask applications. Choose Graphene for complex GraphQL implementations or when working with multiple frameworks, and Flask-GraphQL for quick and easy GraphQL setup in Flask projects.

Build powerful, efficient, and flexible GraphQL APIs with seamless Django integration.

Pros of graphene-django

  • Seamless integration with Django ORM and models
  • Built-in support for Django's authentication and permissions
  • Automatic schema generation based on Django models

Cons of graphene-django

  • Steeper learning curve for developers new to Django
  • Less flexibility compared to Flask for custom GraphQL implementations
  • Potential performance overhead due to Django's ORM

Code Comparison

graphene-django:

import graphene
from graphene_django import DjangoObjectType
from .models import Book

class BookType(DjangoObjectType):
    class Meta:
        model = Book

class Query(graphene.ObjectType):
    books = graphene.List(BookType)

    def resolve_books(self, info):
        return Book.objects.all()

schema = graphene.Schema(query=Query)

flask-graphql:

from flask import Flask
from flask_graphql import GraphQLView
import graphene

class Query(graphene.ObjectType):
    hello = graphene.String()

    def resolve_hello(self, info):
        return "Hello, World!"

schema = graphene.Schema(query=Query)

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

The code comparison shows that graphene-django leverages Django's ORM and models, while flask-graphql provides a more lightweight and flexible approach for implementing GraphQL in Flask applications.

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.

Pros of Apollo Server

  • More comprehensive and feature-rich GraphQL server implementation
  • Better documentation and community support
  • Built-in support for subscriptions and real-time updates

Cons of Apollo Server

  • Steeper learning curve for beginners
  • Potentially more complex setup for simple projects
  • JavaScript/Node.js ecosystem, which may not be suitable for Python-centric projects

Code Comparison

Apollo Server:

const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

Flask-GraphQL:

from flask import Flask
from flask_graphql import GraphQLView
import graphene

class Query(graphene.ObjectType):
    hello = graphene.String()

    def resolve_hello(self, info):
        return 'Hello world!'

app = Flask(__name__)
app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=graphene.Schema(query=Query), graphiql=True))

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

Both implementations provide a simple GraphQL server with a "hello world" query. Apollo Server offers a more concise setup, while Flask-GraphQL integrates seamlessly with the Flask framework, making it a natural choice for Python developers already familiar with Flask.

🧘 Rewrite of a fully-featured GraphQL Server with focus on easy setup, performance & great developer experience. The core of Yoga implements WHATWG Fetch API and can run/deploy on any JS environment.

Pros of GraphQL Yoga

  • More feature-rich and batteries-included approach
  • Better TypeScript support and type safety
  • Easier setup and configuration for common use cases

Cons of GraphQL Yoga

  • Potentially more opinionated and less flexible for custom setups
  • Larger bundle size due to included features
  • May have a steeper learning curve for beginners

Code Comparison

Flask-GraphQL:

from flask import Flask
from flask_graphql import GraphQLView

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

GraphQL Yoga:

import { createYoga } from 'graphql-yoga'
import { createServer } from 'http'

const yoga = createYoga({ schema })
const server = createServer(yoga)
server.listen(4000, () => {
  console.log('Server is running on http://localhost:4000/graphql')
})

Both examples demonstrate basic setup, but GraphQL Yoga provides a more concise and modern approach with built-in features like GraphiQL. Flask-GraphQL requires more manual configuration but offers greater flexibility in integration with existing Flask applications.

Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events.

Pros of graphql-engine

  • Provides a ready-to-use GraphQL API with minimal setup
  • Offers real-time subscriptions out of the box
  • Includes a user-friendly admin interface for managing the GraphQL schema

Cons of graphql-engine

  • Less flexible for custom business logic compared to Flask-GraphQL
  • Steeper learning curve for developers unfamiliar with Hasura's ecosystem
  • Potentially more resource-intensive for simple applications

Code Comparison

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))

graphql-engine:

version: '3.6'
services:
  graphql-engine:
    image: hasura/graphql-engine:v2.x.x
    ports:
      - "8080:8080"
    environment:
      HASURA_GRAPHQL_DATABASE_URL: postgres://username:password@hostname:port/dbname

Summary

Flask-GraphQL offers more flexibility and control over the GraphQL implementation, making it suitable for developers who need to integrate custom logic or have specific requirements. On the other hand, graphql-engine provides a more comprehensive solution with built-in features like real-time subscriptions and an admin interface, making it ideal for rapid development and projects that align well with its capabilities.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.