question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

using async resolvers for third-party api calls

See original GitHub issue

Hi, I’m trying to do some api calls outside of django with graphene-django. However, I cannot figure out how to do this with the GraphQLView from graphene_django.views in urls.py.

schema.py

import graphene
import requests

url = 'https://www.passwordrandom.com/query?command=int&format=json'

class RandomNumberType(graphene.ObjectType):
    number = graphene.Int()

    async def resolve_number(self, info):
        session = info.context["session"]
        async with session.get(url) as response:
            result = await response.json()
            return result['random'][0]

class Query(graphene.ObjectType):
    random_numbers = graphene.List(RandomNumberType)

    def resolve_random_numbers(self, info):
        return [RandomNumberType()] * 5

schema = graphene.Schema(query=Query)

This schema works when I run it in a simple test by executing python async_resolvers_test.py. It will print {'randomNumbers': [{'number': 70}, {'number': 2}, {'number': 34}, {'number': 34}, {'number': 70}]} within a second as the individual requests are called parallel.

async_resolvers_test.py:

import aiohttp
import asyncio
from graphql.execution.executors.asyncio import AsyncioExecutor

from async_resolvers.schema import schema

async def main():
    query = """
        {
          randomNumbers {
              number
          }
        }
    """
    async with aiohttp.ClientSession() as session:
        res = await schema.execute(
            query,
            context={"session": session,},
            executor=AsyncioExecutor(loop=asyncio.get_running_loop()),
            return_promise=True,
        )
        assert not res.errors, repr(res.errors)
        print(res.data)

if __name__ == "__main__":
    asyncio.run(main())

Now, I would like to do the same thing for every execution with graphene-django, but I cannot work out how to do this. I have tried many things, but nothing works (for example adding executor=AsyncExecutor() to GraphQLView.as_view(...)).

urls.py:

from django.contrib import admin
from django.urls import path
from graphene_django.views import GraphQLView

urlpatterns = [
    path('admin/', admin.site.urls),
    path("graphql", GraphQLView.as_view(graphiql=True)),
]

I am getting this error: There is no current event loop in thread 'Thread-1', when I try to execute in GraphiQL:

{
  randomNumbers {
    number
  }
}

I am sure this has something to do with not properly setting up an async session, but I get very confused with everything that is out there and I thus have no idea how to do this.

Please let me know if you have any idea or if anything here is unclear. Thanks in advance!

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:2
  • Comments:7

github_iconTop GitHub Comments

5reactions
Suorcommented, Sep 22, 2020

Apparently setting executor doesn’t work. It would be nice to have this since Django 3.1 already have async views.

3reactions
blazing-gigcommented, Jul 1, 2021

It would be really nice to have a separate AsyncGraphQLView similar to this one from the Strawberry library. Any suggestions or alternatives would be really appreciated as well.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Resolvers - Apollo GraphQL Docs
A resolver is a function that's responsible for populating the data for a single field in your schema. It can populate that data...
Read more >
Using a Third Party API | RedwoodJS Docs
This how to will present the scenario of accessing a third party's API from a Redwood app. We'll show an example of accessing...
Read more >
GraphQL - Prisma - resolvers using external API
1 Answer 1 ... The solution is: We should use a resolver on the field level. schema.graphql. type Charge { id: ID! invoice:...
Read more >
How to call a protected external API using AppSync HTTP ...
To send the Telegram message, we'll add another HTTP resolver that interacts directly with the Telegram API. To combine these two resolvers, we' ......
Read more >
Evolving REST APIs with GraphQL using AWS AppSync Direct ...
Data Sources are the backend services that the API will use to fulfill requests. Finally, resolvers connect the fields, queries, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found