title: Running fastapi with motor async framework
body: <p>I am trying to play around with fastapi by creating a simple mongo based rest api . Below is what i have done so far :</p>
  <p>File : <code>mongo.py</code> This has all the code for getting the data from mongo db using <code>motor</code> framework:</p>
  <pre><code>&quot;&quot;&quot;Module for handling the motor mongo package code.&quot;&quot;&quot;
  from typing import Any, Dict, List
  
  import motor.motor_asyncio
  
  DB = &quot;books&quot;
  COLLECTION = &quot;books&quot;
  
  
  class MongoBackend:
      def __init__(self, uri: str) -&gt; None:
          self._client = motor.motor_asyncio.AsyncIOMotorClient(uri)
  
      async def get_all_books(self) -&gt; List[Dict[str, Any]]:
          cursor = self._client[DB][COLLECTION].find({}, {&quot;_id&quot;: 0})
          return [doc async for doc in cursor]
  
      async def get_single_book(self, book_id: str) -&gt; Dict[str, Any]:
          return await self._client[DB][COLLECTION].find_one(
              {&quot;book_id&quot;: book_id}, {&quot;_id&quot;: 0}
          )
  
      async def update_one_book(self, book_id: str, data: Dict[str, Any]) -&gt; None:
          data[&quot;book_id&quot;] = book_id
          await self._client[DB][COLLECTION].update(
              {&quot;book_id&quot;: book_id}, data, upsert=True
          )
  
      async def insert_one_book(self, data: Dict[str, Any]) -&gt; None:
          await self._client[DB][COLLECTION].insert_one(data)
  
      async def delete_one_book(self, book_id: str) -&gt; None:
          await self._client[DB][COLLECTION].delete_one({&quot;book_id&quot;: book_id})
  </code></pre>
  <p>My <code>routers.py</code> file looks like this :</p>
  <pre><code>&quot;&quot;&quot;Module for containing the routes for the application.&quot;&quot;&quot;
  import uuid
  from typing import Dict, Any, Tuple, List
  
  from fastapi import APIRouter, Depends
  import application.models as models
  import application.mongo as mongo
  import os
  import functools
  
  
  router = APIRouter()
  
  
  @functools.lru_cache()
  def mongo_backend():
      return mongo.MongoBackend(uri=os.getenv(&quot;MONGODB_URI&quot;))
  
  
  @functools.lru_cache()
  def base_uri():
      return os.getenv(&quot;BASE_URI&quot;)
  
  
  def add_hyper_link_to_book(book: Dict[str, Any]) -&gt; Dict[str, Any]:
      book_id = book.pop(&quot;book_id&quot;)
      book[&quot;_link&quot;] = f&quot;{base_uri()}book/{book_id}&quot;
      return book
  
  
  @router.get(&quot;/books&quot;)
  async def get_all_books():
      backend = mongo_backend()
      print(id(backend))
      all_books = [
          add_hyper_link_to_book(book)
          for book in await backend.get_all_books()
      ]
      return all_books
  
  
  @router.post(&quot;/books&quot;)
  async def add_a_book(book: models.Book) -&gt; Tuple[List[Dict[str, Any]], int]:
      backend = mongo_backend()
      book_to_insert = book.dict()
      book_to_insert[&quot;book_id&quot;] = str(uuid.uuid1())
      await backend.insert_one_book(data=book_to_insert)
      return [
          add_hyper_link_to_book(book)
          for book in await backend.get_all_books()
      ], 201
  
  
  @router.get(&quot;/book/{book_id}&quot;)
  async def get_a_single_book(book_id: str, backend: mongo.MongoBackend = Depends(mongo_backend)):
      book = await backend.get_single_book(book_id=book_id)
      if book is None:
          return {&quot;message&quot;: &quot;No such book exist!!&quot;}
      return add_hyper_link_to_book(book)
  </code></pre>
  <p>So as of now i have 3 routes and i want to dependency inject my backend object into the routes and i also i want it to be a singleton.</p>
  <p>In order to show the difference between what works and what does not i have dependency injected into only one of the routes (<code>/book</code>) while for the rest of the routes (<code>/books</code>) i have just called the function to create the backend (<code>mongo_backend</code>) directly.</p>
  <p>I do not quite understand what i am doing wrong because when i try to query the route in which i have dependency injected the backend object throws this error :</p>
  <pre><code>ERROR:    Exception in ASGI application
  Traceback (most recent call last):
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py&quot;, line 396, in run_asgi
      result = await app(self.scope, self.receive, self.send)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py&quot;, line 45, in __call__
      return await self.app(scope, receive, send)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/fastapi/applications.py&quot;, line 199, in __call__
      await super().__call__(scope, receive, send)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/applications.py&quot;, line 111, in __call__
      await self.middleware_stack(scope, receive, send)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/middleware/errors.py&quot;, line 181, in __call__
      raise exc from None
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/middleware/errors.py&quot;, line 159, in __call__
      await self.app(scope, receive, _send)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/exceptions.py&quot;, line 82, in __call__
      raise exc from None
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/exceptions.py&quot;, line 71, in __call__
      await self.app(scope, receive, sender)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/routing.py&quot;, line 566, in __call__
      await route.handle(scope, receive, send)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/routing.py&quot;, line 227, in handle
      await self.app(scope, receive, send)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/routing.py&quot;, line 41, in app
      response = await func(request)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/fastapi/routing.py&quot;, line 191, in app
      solved_result = await solve_dependencies(
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/fastapi/dependencies/utils.py&quot;, line 550, in solve_dependencies
      solved = await run_in_threadpool(call, **sub_values)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/starlette/concurrency.py&quot;, line 34, in run_in_threadpool
      return await loop.run_in_executor(None, func, *args)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/concurrent/futures/thread.py&quot;, line 57, in run
      result = self.fn(*self.args, **self.kwargs)
    File &quot;./application/routers.py&quot;, line 17, in mongo_backend
      return mongo.MongoBackend(uri=os.getenv(&quot;MONGODB_URI&quot;))
    File &quot;./application/mongo.py&quot;, line 12, in __init__
      self._client = motor.motor_asyncio.AsyncIOMotorClient(uri)
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/motor/core.py&quot;, line 150, in __init__
      io_loop = self._framework.get_event_loop()
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/site-packages/motor/frameworks/asyncio/__init__.py&quot;, line 42, in get_event_loop
      return asyncio.get_event_loop()
    File &quot;/home/subhayan/anaconda3/envs/mongo-book-store-fastapi/lib/python3.8/asyncio/events.py&quot;, line 639, in get_event_loop
      raise RuntimeError('There is no current event loop in thread %r.'
  RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-1_0'.
  </code></pre>
  <p>The rest of the two routes work fine. Can someone please help me with what needs to be done to make this work.</p>
  <p>In case it helps this is my <code>app.py</code>:</p>
  <pre><code>&quot;&quot;&quot;Main module for the fastapi app.&quot;&quot;&quot;
  import pathlib
  
  from dotenv import load_dotenv
  from fastapi import FastAPI
  import application.routers as routers
  
  # load the environment from the file app.env in the project directory
  basedir = pathlib.Path(__file__).parent.parent
  load_dotenv(basedir / &quot;app.env&quot;)
  
  app = FastAPI()
  
  app.include_router(routers.router)
  </code></pre>