Fastapi: Getting the value of an async method in a non-async path operation function

Created on 17 Jul 2020  路  3Comments  路  Source: tiangolo/fastapi

I'm using SQLAlchemy ORM so I made my path operation function using def not async def. In my function though I want to call request.json() which is async and must be awaited. How can I get the full body of the request in a non-async function?

question

Most helpful comment

Thanks for the help here @SnkSynthesis! :clap: :bow:

Thanks for reporting back and closing the issue @orientalperil :+1:

All 3 comments

@orientalperil

To call request.json() in synchronous function

You can use asyncio

from fastapi import FastAPI, Request
import asyncio

app = FastAPI()

@app.post('/')
def sync_func(request: Request):
    data = asyncio.run(request.json())
    return data

or you can use asgiref (pip3 install asgiref)

from fastapi import FastAPI, Request
from asgiref.sync import async_to_sync

app  = FastAPI()

@app.post('/')
def sync_func(request: Request):
    get_json = async_to_sync(request.json)
    data = get_json()
    return data

Oh right this is so obvious once I see it

Thanks for the help here @SnkSynthesis! :clap: :bow:

Thanks for reporting back and closing the issue @orientalperil :+1:

Was this page helpful?
0 / 5 - 0 ratings