Package: tartiflette-aiohttp
tartiflette-aiohttpis a wrapper ofaiohttpwhich includes the Tartiflette GraphQL Engine. You can take a look at theTartiflette API documentation.Usage# main.pyfromaiohttpimportwebfromtartifletteimportResolverfromtartiflette_aiohttpimportregister_graphql_handlers@Resolver("Query.hello")asyncdefresolver_hello(parent,args,ctx,info):return"hello "+args["name"]sdl="""type Query {hello(name: String): String}"""web.run_app(register_graphql_handlers(web.Application(),engine_sdl=sdl))Save the file and start the server.$pythonmain.py========Runningonhttp://0.0.0.0:8080========(PressCTRL+Ctoquit)Note: The server will be listening on the/graphqlpath by default.Send a request to your servercurl -v -d '{"query": "query { hello(name: "Chuck") }"}' -H "Content-Type: application/json" http://localhost:8080/graphqlInstallationtartiflette-aiohttpis available onpypi.org.WARNING: Do not forget to install thetartiflette dependencies beforehand as explained in the tutorial.pipinstalltartiflette-aiohttpHow to useUse with built-in Tartiflette EngineThe basic and common way to use Tartiflette withaiohttp, is to create anaiohttpweb.Applicationand use theregister_graphql_handlershelper to bind Tartiflette andaiohttptogether.engine_*parameters will be forwarded to the built-intartifletteengine instance.fromaiohttpimportwebfromtartiflette_aiohttpimportregister_graphql_handlerssdl="""type Query {hello(name: String): String}"""ctx={'user_service':user_service}web.run_app(register_graphql_handlers(app=web.Application(),engine_sdl=sdl,engine_schema_name="default",executor_context=ctx,executor_http_endpoint='/graphql',executor_http_methods=['POST','GET']))Parameters:engine_sdl: Contains theSchema Definition LanguageCan be a string which contains the SDLCan be an array of strings, which contain the SDLsCan be a path to an SDLCan be an array of paths which contain the SDLsengine_schema_name: Name of the schema used by the built-in engine. Useful for advanced use-cases, seeSchema Registry API.executor_context: Context which will be passed to each resolver (as a dict). Very useful for passing handlers to services, functions or data that you want to use in your resolvers. The context reference isuniqueper request, a shallow copy is created based on the context passed.req: Request object fromaiohttpapp: Application object fromaiohttpexecutor_http_endpoint: Endpoint where the GraphQL Engine will be attached, by default on/graphqlexecutor_http_methods: HTTP Methods where the GraphQL Engine will be attached, by default onPOSTandGET.Use with custom Tartiflette engineIn the case you already have a Tartiflette Engine instance, or, you do not want to use the built-in instance. You can pass an existing instance to theregister_graphql_handlershelper.# main.pyfromaiohttpimportwebfromtartifletteimportResolver,Enginefromtartiflette_aiohttpimportregister_graphql_handlers@Resolver("Query.hello")asyncdefresolver_hello(parent,args,ctx,info):return"hello "+args["name"]sdl="""type Query {hello(name: String): String}"""engine=Engine(sdl)ctx={'user_service':user_service}web.run_app(register_graphql_handlers(app=web.Application(),engine=engine,executor_context=ctx,executor_http_endpoint='/graphql',executor_http_methods=['POST','GET']))Parameters:engine: an instance of the Tartiflette Engineexecutor_context: Context which will be passed to each resolver (as a dict). Very useful for passing handlers to services, functions or data that you want to use in your resolvers.req: Request object fromaiohttpapp: Application object fromaiohttpexecutor_http_endpoint: Endpoint where the GraphQL Engine will be attached, by default on/graphqlexecutor_http_methods: HTTP Methods where the GraphQL Engine will be attached, by default onPOSTandGETTartiflette with subscriptionsTartiflette embeds an easy way to deal with subscriptions. The only thing to do is
to fill in thesubscription_ws_endpointparameter and everything will work out
of the box withaiohttpWebSockets. You can see a full examplehere.Enable GraphiQL handlerTartiflette allows you to set up an instance of GraphiQL easily to quickly test
your queries. The easiest way to do that is to set thegraphiql_enabledparameter toTrue. Then, you can customize your GraphiQL instance by filling
thegraphiql_optionsparameter as bellow:fromaiohttpimportwebfromtartiflette_aiohttpimportregister_graphql_handlers_SDL="""type Query {hello(name: String): String}"""web.run_app(register_graphql_handlers(app=web.Application(),engine_sdl=_SDL,graphiql_enabled=True,graphiql_options={# This is optional"endpoint":"/explorer",# Default: `/graphiql`,"default_query":"""query Hello($name: String) {hello(name: $name)}""","default_variables":{"name":"Bob",},"default_headers":{"Authorization":"Bearer <default_token>",},},))Parameters:engine_sdl: Contains theSchema Definition LanguageCan be a string which contains the SDLCan be an array of strings, which contain the SDLsCan be a path to an SDLCan be an array of paths which contain the SDLsgraphiql_enabled(Optional[bool] = False): Determines whether or not we should include a GraphiQL interfacegraphiql_options(Optional[dict] = None): Customization options for the GraphiQL instance:endpoint(Optional[str] = "/graphiql"): allows to customize the GraphiQL interface endpoint pathdefault_query(Optional[str] = None): allows you to pre-fill the GraphiQL interface with a default querydefault_variables(Optional[dict] = None): allows you to pre-fill the GraphiQL interface with default variablesdefault_headers(Optional[dict] = None): allows you to add default headers to each request sent through the GraphiQL instanceAdvance Use CaseResponse header manipulation from resolverIt is possible to set header to the response directly from the resolver usingset_response_headersmethod like:fromtartiflette_aiohttpimportset_response_headers@Resolver("Query.X")asyncdefresolver_x(parent_result,args,ctx,info):# do thingsset_response_headers({"Header":"Value","AnotherHeader":"AnotherValue"})returnresultNote that this feature uses ContextVar and will only works for python 3.7.1 and later.OR it is also possible to do, if you do not have ContextVar, or don't want to use them:fromaiohttpimportwebdefa_callable(req,data,ctx):returnweb.json_response(data,headers=ctx["_any_custom_key"])web.run_app(register_graphql_handlers(app=web.Application(),engine_sdl=_SDL,response_formatter=a_callable))@Resolver("Type.field_name")asyncdeffiel_name_resolver(pr,args,ctx,info):ctx["_any_custom_key"]={"X-Header":"What a wonderfull value"}returnsomething