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?
@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:
Most helpful comment
Thanks for the help here @SnkSynthesis! :clap: :bow:
Thanks for reporting back and closing the issue @orientalperil :+1: