Giter Site home page Giter Site logo

aiohttp-graphql's Introduction

aiohttp-graphql

Adds GraphQL support to your aiohttp application.

Based on flask-graphql by Syrus Akbary and sanic-graphql by Sergey Porivaev.

PyPI version Build Status Coverage Status

Usage

Use the GraphQLView view from aiohttp_graphql

from aiohttp import web
from aiohttp_graphql import GraphQLView

from schema import schema

app = web.Application()

GraphQLView.attach(app, schema=schema, graphiql=True)

# Optional, for adding batch query support (used in Apollo-Client)
GraphQLView.attach(app, schema=schema, batch=True, route_path="/graphql/batch")

if __name__ == '__main__':
    web.run_app(app)

This will add /graphql endpoint to your app (customizable by passing route_path='/mypath' to GraphQLView.attach) and enable the GraphiQL IDE.

Note: GraphQLView.attach is just a convenience function, and the same functionality can be achieved with

gql_view = GraphQLView(schema=schema, graphiql=True)
app.router.add_route('*', '/graphql', gql_view, name='graphql')

It's worth noting that the the "view function" of GraphQLView is contained in GraphQLView.__call__. So, when you create an instance, that instance is callable with the request object as the sole positional argument. To illustrate:

gql_view = GraphQLView(schema=Schema, **kwargs)
gql_view(request)  # <-- the instance is callable and expects a `aiohttp.web.Request` object.

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".
  • jinja_env: Sets jinja environment to be used to process GraphiQL template. If Jinja’s async mode is enabled (by enable_async=True), uses Template.render_async instead of Template.render. If environment is not set, fallbacks to simple regex-based renderer.
  • batch: Set the GraphQL view as batch (for using in Apollo-Client or ReactRelayNetworkLayer)
  • middleware: A list of graphql middlewares.
  • max_age: Sets the response header Access-Control-Max-Age for preflight requests.
  • 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.
  • enable_async: whether async mode will be enabled.
  • 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.

Contributing

Since v3, aiohttp-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.

License

Copyright for portions of project aiohttp-graphql are held by Syrus Akbary as part of project flask-graphql and sanic-graphql as part of project Sergey Porivaev. All other claims to this project aiohttp-graphql are held by Devin Fee.

This project is licensed under the MIT License.

aiohttp-graphql's People

Contributors

ambientlighter avatar cito avatar dfee avatar hellzed avatar jkimbo avatar kingdarboja avatar syrusakbary avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aiohttp-graphql's Issues

async/await allowed for mutations and queries?

I want to be able to async/await for a mutate method

class UploadFileMutation(graphene.ClientIDMutation):
    class Input:
        pass

    ok = graphene.Boolean()

    @classmethod
    async def mutate_and_get_payload(cls, root, info, **input):
        # do something with your file
        return UploadFileMutation(ok=True)

Is this not possible?

The server just kind of hangs

Also with query

class SearchableQuestionPair(graphene.ObjectType):
    question = graphene.String(required=True)
    answer = graphene.String(required=True)

class SearchInput(graphene.InputObjectType):
    _input = graphene.String(name="input", argument=graphene.String(), description="Text to search for")


class RootQuery(graphene.ObjectType):
    searchable_question_pairs = graphene.List(SearchableQuestionPair, argument=SearchInput(required=True))
    ok = graphene.Boolean(default_value=True)

    async def resolve_searchable_question_pairs(self, info, argument):
        return [SearchableQuestionPair(question="foo", answer="bar"),
                SearchableQuestionPair(question="buzz", answer="zap")]

content-type header not allowed

When trying to connect to the graphql endpoint with Apollo, the following error occurs:

Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

However curl pulls just well:

curl -X POST -H "Content-Type: application/json" --data '{"query": "{hello}"}' http://randomhost/graphql
{"data":{"hello": "world"}}

Attached as such:

app = web.Application()
GraphQLView.attach(app, schema=schema, executor=AsyncioExecutor(loop=app.loop), graphiql=True)

Update:
Tried to create a child for GraphQLView as such:

class GQLView(GraphQLView):
    def process_preflight(self, request):
        """ Preflight request support for apollo-client
        https://www.w3.org/TR/cors/#resource-preflight-requests """
        headers = request.headers
        origin = headers.get('Origin', '')
        method = headers.get('Access-Control-Request-Method', '').upper()

        accepted_methods = ['GET', 'POST', 'PUT', 'DELETE']
        if method and method in accepted_methods:
            return web.Response(
                status=200,
                headers={
                    'Access-Control-Allow-Origin': origin,
                    'Access-Control-Allow-Methods': ', '.join(accepted_methods),
                    'Access-Control-Max-Age': str(self.max_age),
                    'Access-Control-Allow-Headers': "Content-Type"
                }
            )
        return web.Response(status=400)

When using this, I can see the query hits the server (packet capture), and I get this error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

graphql-server-core breaking change

The deps in setup.py pull in graphl-server-core>=1.0.dev which pulls in the 1.1rc0 but keeps graphql-core at 2.0. graphql-server-core 1.1rc0 and graphql-core 2.0 are incompatible. This breaks aiohttp-graphql.

It is probably not a good idea to define such a wide range for dependencies on core graphql libs so this won't happen again.

Workaround for now is to downgrade graphql-server-core in my project to graphql-server-core==1.0.dev20170322001

Example for GraphQL client usage

So this can also be used as a GraphQL client, using the client functionality in aiohttp? Can you provide an example of how this is used?

Would be a nice addition to the main README.md

Add offline support for graphiql

There are several scripts and a stylesheet included in aiohttp_graphql/render_graphiql.py for the domain cdn.jsdelivr.net. The use of this CDN prevents the graphiql interface from being used offline.

The same issue was seen here graphql/graphiql#676

The entire bundle is about +725k to add directly to the package.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.