Created
January 13, 2019 13:24
-
-
Save messa/2c13b9c5b88d98cc186f6c51fb5194db to your computer and use it in GitHub Desktop.
Aiohttp GraphQL server example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aiohttp import web | |
from aiohttp_graphql import GraphQLView | |
from graphql.execution.executors.asyncio import AsyncioExecutor | |
from graphql import ( | |
graphql, | |
GraphQLSchema, | |
GraphQLObjectType, | |
GraphQLField, | |
GraphQLNonNull, | |
GraphQLString, | |
GraphQLInt, | |
GraphQLList, | |
GraphQLID | |
) | |
class Movie: | |
def __init__(self, title, year): | |
self.title = title | |
self.year = year | |
class SampleModel: | |
async def list_movies(self): | |
return [ | |
Movie('The Matrix', 1999), | |
Movie('The Matrix Reloaded', 2003), | |
Movie('The Matrix Revolutions', 2003), | |
] | |
MovieType = GraphQLObjectType( | |
name='Movie', | |
fields={ | |
'title': GraphQLField(type=GraphQLString), | |
'year': GraphQLField(type=GraphQLInt), | |
} | |
) | |
async def resolve_movies(root, info): | |
model = info.context['request'].app['model'] | |
return await model.list_movies() | |
Schema = GraphQLSchema( | |
query=GraphQLObjectType( | |
name='RootQueryType', | |
fields={ | |
'movies': GraphQLField( | |
type=GraphQLList(MovieType), | |
resolver=resolve_movies), | |
}, | |
)) | |
routes = web.RouteTableDef() | |
@routes.get('/') | |
async def index(request): | |
return web.Response( | |
text='Go to <a href="/graphql">/grphql</a>\n', | |
content_type='text/html') | |
def get_app(): | |
app = web.Application() | |
app.add_routes(routes) | |
app['model'] = SampleModel() | |
GraphQLView.attach( | |
app, | |
route_path='/graphql', | |
schema=Schema, | |
graphiql=True, | |
executor=AsyncioExecutor()) | |
return app | |
app = get_app() | |
if __name__ == '__main__': | |
web.run_app(app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment